Remove unused second argument to ip_stripoptions().
[dragonfly.git] / sys / netinet / tcp_input.c
1 /*
2  * Copyright (c) 2002-2003 Jeffrey Hsu
3  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
4  *      The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *      This product includes software developed by the University of
17  *      California, Berkeley and its contributors.
18  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
35  * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
36  * $DragonFly: src/sys/netinet/tcp_input.c,v 1.17 2004/03/06 07:30:43 hsu Exp $
37  */
38
39 #include "opt_ipfw.h"           /* for ipfw_fwd         */
40 #include "opt_inet6.h"
41 #include "opt_ipsec.h"
42 #include "opt_tcpdebug.h"
43 #include "opt_tcp_input.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/kernel.h>
48 #include <sys/sysctl.h>
49 #include <sys/malloc.h>
50 #include <sys/mbuf.h>
51 #include <sys/proc.h>           /* for proc0 declaration */
52 #include <sys/protosw.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/syslog.h>
56 #include <sys/in_cksum.h>
57
58 #include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
59
60 #include <net/if.h>
61 #include <net/route.h>
62
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
66 #include <netinet/ip_icmp.h>    /* for ICMP_BANDLIM             */
67 #include <netinet/in_var.h>
68 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM             */
69 #include <netinet/in_pcb.h>
70 #include <netinet/ip_var.h>
71 #include <netinet/ip6.h>
72 #include <netinet/icmp6.h>
73 #include <netinet6/nd6.h>
74 #include <netinet6/ip6_var.h>
75 #include <netinet6/in6_pcb.h>
76 #include <netinet/tcp.h>
77 #include <netinet/tcp_fsm.h>
78 #include <netinet/tcp_seq.h>
79 #include <netinet/tcp_timer.h>
80 #include <netinet/tcp_var.h>
81 #include <netinet6/tcp6_var.h>
82 #include <netinet/tcpip.h>
83 #ifdef TCPDEBUG
84 #include <netinet/tcp_debug.h>
85
86 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
87 struct tcphdr tcp_savetcp;
88 #endif /* TCPDEBUG */
89
90 #ifdef FAST_IPSEC
91 #include <netipsec/ipsec.h>
92 #include <netipsec/ipsec6.h>
93 #endif
94
95 #ifdef IPSEC
96 #include <netinet6/ipsec.h>
97 #include <netinet6/ipsec6.h>
98 #include <netproto/key/key.h>
99 #endif /*IPSEC*/
100
101 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
102
103 static const int tcprexmtthresh = 3;
104 tcp_cc  tcp_ccgen;
105
106 struct  tcpstat tcpstat;
107 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
108     &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
109
110 static int log_in_vain = 0;
111 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW, 
112     &log_in_vain, 0, "Log all incoming TCP connections");
113
114 static int blackhole = 0;
115 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
116     &blackhole, 0, "Do not send RST when dropping refused connections");
117
118 int tcp_delack_enabled = 1;
119 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW, 
120     &tcp_delack_enabled, 0, 
121     "Delay ACK to try and piggyback it onto a data packet");
122
123 #ifdef TCP_DROP_SYNFIN
124 static int drop_synfin = 0;
125 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
126     &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
127 #endif
128
129 static int tcp_do_limitedtransmit = 1;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
131     &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
132
133 static int tcp_do_rfc3390 = 1;
134 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
135     &tcp_do_rfc3390, 0,
136     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
137
138 static int tcp_do_eifel_detect = 1;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
140     &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
141
142 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
143     "TCP Segment Reassembly Queue");
144
145 int tcp_reass_maxseg = 0;
146 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
147     &tcp_reass_maxseg, 0,
148     "Global maximum number of TCP Segments in Reassembly Queue");
149
150 int tcp_reass_qsize = 0;
151 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
152     &tcp_reass_qsize, 0,
153     "Global number of TCP Segments currently in Reassembly Queue");
154
155 static int tcp_reass_overflows = 0;
156 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
157     &tcp_reass_overflows, 0,
158     "Global number of TCP Segment Reassembly Queue Overflows");
159
160 struct inpcbinfo tcbinfo;
161
162 static void      tcp_dooptions(struct tcpopt *, u_char *, int, int);
163 static void      tcp_pulloutofband(struct socket *,
164                      struct tcphdr *, struct mbuf *, int);
165 static int       tcp_reass(struct tcpcb *, struct tcphdr *, int *,
166                      struct mbuf *);
167 static void      tcp_xmit_timer(struct tcpcb *, int);
168 static void      tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
169
170 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
171 #ifdef INET6
172 #define ND6_HINT(tp) \
173 do { \
174         if ((tp) && (tp)->t_inpcb && \
175             ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
176             (tp)->t_inpcb->in6p_route.ro_rt) \
177                 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
178 } while (0)
179 #else
180 #define ND6_HINT(tp)
181 #endif
182
183 /*
184  * Indicate whether this ack should be delayed.  We can delay the ack if
185  *      - delayed acks are enabled and
186  *      - there is no delayed ack timer in progress and
187  *      - our last ack wasn't a 0-sized window.  We never want to delay
188  *        the ack that opens up a 0-sized window.
189  */
190 #define DELAY_ACK(tp) \
191         (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
192         (tp->t_flags & TF_RXWIN0SENT) == 0)
193
194 static int
195 tcp_reass(tp, th, tlenp, m)
196         struct tcpcb *tp;
197         struct tcphdr *th;
198         int *tlenp;
199         struct mbuf *m;
200 {
201         struct tseg_qent *q;
202         struct tseg_qent *p = NULL;
203         struct tseg_qent *nq;
204         struct tseg_qent *te;
205         struct socket *so = tp->t_inpcb->inp_socket;
206         int flags;
207
208         /*
209          * Call with th==0 after become established to
210          * force pre-ESTABLISHED data up to user socket.
211          */
212         if (th == 0)
213                 goto present;
214
215         /*
216          * Limit the number of segments in the reassembly queue to prevent
217          * holding on to too many segments (and thus running out of mbufs).
218          * Make sure to let the missing segment through which caused this
219          * queue.  Always keep one global queue entry spare to be able to
220          * process the missing segment.
221          */
222         if (th->th_seq != tp->rcv_nxt &&
223             tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
224                 tcp_reass_overflows++;
225                 tcpstat.tcps_rcvmemdrop++;
226                 m_freem(m);
227                 return (0);
228         }
229
230         /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
231         MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
232                M_NOWAIT);
233         if (te == NULL) {
234                 tcpstat.tcps_rcvmemdrop++;
235                 m_freem(m);
236                 return (0);
237         }
238         tcp_reass_qsize++;
239
240         /*
241          * Find a segment which begins after this one does.
242          */
243         LIST_FOREACH(q, &tp->t_segq, tqe_q) {
244                 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
245                         break;
246                 p = q;
247         }
248
249         /*
250          * If there is a preceding segment, it may provide some of
251          * our data already.  If so, drop the data from the incoming
252          * segment.  If it provides all of our data, drop us.
253          */
254         if (p != NULL) {
255                 int i;
256                 /* conversion to int (in i) handles seq wraparound */
257                 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
258                 if (i > 0) {
259                         if (i >= *tlenp) {
260                                 tcpstat.tcps_rcvduppack++;
261                                 tcpstat.tcps_rcvdupbyte += *tlenp;
262                                 m_freem(m);
263                                 free(te, M_TSEGQ);
264                                 tcp_reass_qsize--;
265                                 /*
266                                  * Try to present any queued data
267                                  * at the left window edge to the user.
268                                  * This is needed after the 3-WHS
269                                  * completes.
270                                  */
271                                 goto present;   /* ??? */
272                         }
273                         m_adj(m, i);
274                         *tlenp -= i;
275                         th->th_seq += i;
276                 }
277         }
278         tcpstat.tcps_rcvoopack++;
279         tcpstat.tcps_rcvoobyte += *tlenp;
280
281         /*
282          * While we overlap succeeding segments trim them or,
283          * if they are completely covered, dequeue them.
284          */
285         while (q) {
286                 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
287                 if (i <= 0)
288                         break;
289                 if (i < q->tqe_len) {
290                         q->tqe_th->th_seq += i;
291                         q->tqe_len -= i;
292                         m_adj(q->tqe_m, i);
293                         break;
294                 }
295
296                 nq = LIST_NEXT(q, tqe_q);
297                 LIST_REMOVE(q, tqe_q);
298                 m_freem(q->tqe_m);
299                 free(q, M_TSEGQ);
300                 tcp_reass_qsize--;
301                 q = nq;
302         }
303
304         /* Insert the new segment queue entry into place. */
305         te->tqe_m = m;
306         te->tqe_th = th;
307         te->tqe_len = *tlenp;
308
309         if (p == NULL) {
310                 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
311         } else {
312                 LIST_INSERT_AFTER(p, te, tqe_q);
313         }
314
315 present:
316         /*
317          * Present data to user, advancing rcv_nxt through
318          * completed sequence space.
319          */
320         if (!TCPS_HAVEESTABLISHED(tp->t_state))
321                 return (0);
322         q = LIST_FIRST(&tp->t_segq);
323         if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
324                 return (0);
325         do {
326                 tp->rcv_nxt += q->tqe_len;
327                 flags = q->tqe_th->th_flags & TH_FIN;
328                 nq = LIST_NEXT(q, tqe_q);
329                 LIST_REMOVE(q, tqe_q);
330                 if (so->so_state & SS_CANTRCVMORE)
331                         m_freem(q->tqe_m);
332                 else
333                         sbappend(&so->so_rcv, q->tqe_m);
334                 free(q, M_TSEGQ);
335                 tcp_reass_qsize--;
336                 q = nq;
337         } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
338         ND6_HINT(tp);
339         sorwakeup(so);
340         return (flags);
341 }
342
343 /*
344  * TCP input routine, follows pages 65-76 of the
345  * protocol specification dated September, 1981 very closely.
346  */
347 #ifdef INET6
348 int
349 tcp6_input(mp, offp, proto)
350         struct mbuf **mp;
351         int *offp, proto;
352 {
353         struct mbuf *m = *mp;
354         struct in6_ifaddr *ia6;
355
356         IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
357
358         /*
359          * draft-itojun-ipv6-tcp-to-anycast
360          * better place to put this in?
361          */
362         ia6 = ip6_getdstifaddr(m);
363         if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {                
364                 struct ip6_hdr *ip6;
365
366                 ip6 = mtod(m, struct ip6_hdr *);
367                 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
368                             (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
369                 return IPPROTO_DONE;
370         }
371
372         tcp_input(m, *offp, proto);
373         return IPPROTO_DONE;
374 }
375 #endif
376
377 void
378 tcp_input(m, off0, proto)
379         struct mbuf *m;
380         int off0, proto;
381 {
382         struct tcphdr *th;
383         struct ip *ip = NULL;
384         struct ipovly *ipov;
385         struct inpcb *inp = NULL;
386         u_char *optp = NULL;
387         int optlen = 0;
388         int len, tlen, off;
389         int drop_hdrlen;
390         struct tcpcb *tp = NULL;
391         int thflags;
392         struct socket *so = 0;
393         int todrop, acked, ourfinisacked, needoutput = 0;
394         u_long tiwin;
395         struct tcpopt to;               /* options in this segment */
396         struct rmxp_tao *taop;          /* pointer to our TAO cache entry */
397         struct rmxp_tao tao_noncached;  /* in case there's no cached entry */
398         struct sockaddr_in *next_hop = NULL;
399         int rstreason; /* For badport_bandlim accounting purposes */
400         struct ip6_hdr *ip6 = NULL;
401 #ifdef INET6
402         int isipv6;
403 #else
404         const int isipv6 = 0;
405 #endif
406 #ifdef TCPDEBUG
407         short ostate = 0;
408 #endif
409
410         /* Grab info from MT_TAG mbufs prepended to the chain. */
411         for (;m && m->m_type == MT_TAG; m = m->m_next) {
412                 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
413                         next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
414         }
415 #ifdef INET6
416         isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
417 #endif
418         bzero((char *)&to, sizeof(to));
419
420         tcpstat.tcps_rcvtotal++;
421
422         if (isipv6) {
423                 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
424                 ip6 = mtod(m, struct ip6_hdr *);
425                 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
426                 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
427                         tcpstat.tcps_rcvbadsum++;
428                         goto drop;
429                 }
430                 th = (struct tcphdr *)((caddr_t)ip6 + off0);
431
432                 /*
433                  * Be proactive about unspecified IPv6 address in source.
434                  * As we use all-zero to indicate unbounded/unconnected pcb,
435                  * unspecified IPv6 address can be used to confuse us.
436                  *
437                  * Note that packets with unspecified IPv6 destination is
438                  * already dropped in ip6_input.
439                  */
440                 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
441                         /* XXX stat */
442                         goto drop;
443                 }
444         } else {
445                 /*
446                  * Get IP and TCP header together in first mbuf.
447                  * Note: IP leaves IP header in first mbuf.
448                  */
449                 if (off0 > sizeof(struct ip)) {
450                         ip_stripoptions(m);
451                         off0 = sizeof(struct ip);
452                 }
453                 if (m->m_len < sizeof(struct tcpiphdr)) {
454                         if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
455                                 tcpstat.tcps_rcvshort++;
456                                 return;
457                         }
458                 }
459                 ip = mtod(m, struct ip *);
460                 ipov = (struct ipovly *)ip;
461                 th = (struct tcphdr *)((caddr_t)ip + off0);
462                 tlen = ip->ip_len;
463
464                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
465                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
466                                 th->th_sum = m->m_pkthdr.csum_data;
467                         else
468                                 th->th_sum = in_pseudo(ip->ip_src.s_addr,
469                                                 ip->ip_dst.s_addr,
470                                                 htonl(m->m_pkthdr.csum_data +
471                                                         ip->ip_len +
472                                                         IPPROTO_TCP));
473                         th->th_sum ^= 0xffff;
474                 } else {
475                         /*
476                          * Checksum extended TCP header and data.
477                          */
478                         len = sizeof(struct ip) + tlen;
479                         bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
480                         ipov->ih_len = (u_short)tlen;
481                         ipov->ih_len = htons(ipov->ih_len);
482                         th->th_sum = in_cksum(m, len);
483                 }
484                 if (th->th_sum) {
485                         tcpstat.tcps_rcvbadsum++;
486                         goto drop;
487                 }
488 #ifdef INET6
489                 /* Re-initialization for later version check */
490                 ip->ip_v = IPVERSION;
491 #endif
492         }
493
494         /*
495          * Check that TCP offset makes sense,
496          * pull out TCP options and adjust length.              XXX
497          */
498         off = th->th_off << 2;
499         if (off < sizeof(struct tcphdr) || off > tlen) {
500                 tcpstat.tcps_rcvbadoff++;
501                 goto drop;
502         }
503         tlen -= off;    /* tlen is used instead of ti->ti_len */
504         if (off > sizeof(struct tcphdr)) {
505                 if (isipv6) {
506                         IP6_EXTHDR_CHECK(m, off0, off, );
507                         ip6 = mtod(m, struct ip6_hdr *);
508                         th = (struct tcphdr *)((caddr_t)ip6 + off0);
509                 } else {
510                         if (m->m_len < sizeof(struct ip) + off) {
511                                 if ((m = m_pullup(m, sizeof(struct ip) + off))
512                                                 == 0) {
513                                         tcpstat.tcps_rcvshort++;
514                                         return;
515                                 }
516                                 ip = mtod(m, struct ip *);
517                                 ipov = (struct ipovly *)ip;
518                                 th = (struct tcphdr *)((caddr_t)ip + off0);
519                         }
520                 }
521                 optlen = off - sizeof(struct tcphdr);
522                 optp = (u_char *)(th + 1);
523         }
524         thflags = th->th_flags;
525
526 #ifdef TCP_DROP_SYNFIN
527         /*
528          * If the drop_synfin option is enabled, drop all packets with
529          * both the SYN and FIN bits set. This prevents e.g. nmap from
530          * identifying the TCP/IP stack.
531          *
532          * This is a violation of the TCP specification.
533          */
534         if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
535                 goto drop;
536 #endif
537
538         /*
539          * Convert TCP protocol specific fields to host format.
540          */
541         th->th_seq = ntohl(th->th_seq);
542         th->th_ack = ntohl(th->th_ack);
543         th->th_win = ntohs(th->th_win);
544         th->th_urp = ntohs(th->th_urp);
545
546         /*
547          * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
548          * until after ip6_savecontrol() is called and before other functions
549          * which don't want those proto headers.
550          * Because ip6_savecontrol() is going to parse the mbuf to
551          * search for data to be passed up to user-land, it wants mbuf
552          * parameters to be unchanged.
553          * XXX: the call of ip6_savecontrol() has been obsoleted based on
554          * latest version of the advanced API (20020110).
555          */
556         drop_hdrlen = off0 + off;
557
558         /*
559          * Locate pcb for segment.
560          */
561 findpcb:
562         /* IPFIREWALL_FORWARD section */
563         if (next_hop != NULL && isipv6 == 0) {  /* IPv6 support is not yet */
564                 /*
565                  * Transparently forwarded. Pretend to be the destination.
566                  * already got one like this? 
567                  */
568                 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
569                                         ip->ip_dst, th->th_dport,
570                                         0, m->m_pkthdr.rcvif);
571                 if (!inp) {
572                         /* It's new.  Try find the ambushing socket. */
573                         inp = in_pcblookup_hash(&tcbinfo,
574                                                 ip->ip_src, th->th_sport,
575                                                 next_hop->sin_addr,
576                                                 next_hop->sin_port ?
577                                                     ntohs(next_hop->sin_port) :
578                                                     th->th_dport,
579                                                 1, m->m_pkthdr.rcvif);
580                 }
581         } else {
582                 if (isipv6)
583                         inp = in6_pcblookup_hash(&tcbinfo,
584                                                  &ip6->ip6_src, th->th_sport,
585                                                  &ip6->ip6_dst, th->th_dport,
586                                                  1, m->m_pkthdr.rcvif);
587                 else
588                         inp = in_pcblookup_hash(&tcbinfo,
589                                                 ip->ip_src, th->th_sport,
590                                                 ip->ip_dst, th->th_dport,
591                                                 1, m->m_pkthdr.rcvif);
592       }
593
594 #ifdef IPSEC
595         if (isipv6) {
596                 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
597                         ipsec6stat.in_polvio++;
598                         goto drop;
599                 }
600         } else {
601                 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
602                         ipsecstat.in_polvio++;
603                         goto drop;
604                 }
605         }
606 #endif
607 #ifdef FAST_IPSEC
608         if (isipv6) {
609                 if (inp != NULL && ipsec6_in_reject(m, inp)) {
610                         goto drop;
611                 }
612         } else {
613                 if (inp != NULL && ipsec4_in_reject(m, inp)) {
614                         goto drop;
615                 }
616         }
617 #endif
618
619         /*
620          * If the state is CLOSED (i.e., TCB does not exist) then
621          * all data in the incoming segment is discarded.
622          * If the TCB exists but is in CLOSED state, it is embryonic,
623          * but should either do a listen or a connect soon.
624          */
625         if (inp == NULL) {
626                 if (log_in_vain) {
627 #ifdef INET6
628                         char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
629 #else
630                         char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
631 #endif
632                         if (isipv6) {
633                                 strcpy(dbuf, "[");
634                                 strcpy(sbuf, "[");
635                                 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
636                                 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
637                                 strcat(dbuf, "]");
638                                 strcat(sbuf, "]");
639                         } else {
640                                 strcpy(dbuf, inet_ntoa(ip->ip_dst));
641                                 strcpy(sbuf, inet_ntoa(ip->ip_src));
642                         }
643                         switch (log_in_vain) {
644                         case 1:
645                                 if ((thflags & TH_SYN) == 0)
646                                         break;
647                         case 2:
648                                 log(LOG_INFO,
649                                     "Connection attempt to TCP %s:%d "
650                                     "from %s:%d flags:0x%02x\n",
651                                     dbuf, ntohs(th->th_dport), sbuf,
652                                     ntohs(th->th_sport), thflags);
653                                 break;
654                         default:
655                                 break;
656                         }
657                 }
658                 if (blackhole) { 
659                         switch (blackhole) {
660                         case 1:
661                                 if (thflags & TH_SYN)
662                                         goto drop;
663                                 break;
664                         case 2:
665                                 goto drop;
666                         default:
667                                 goto drop;
668                         }
669                 }
670                 rstreason = BANDLIM_RST_CLOSEDPORT;
671                 goto dropwithreset;
672         }
673         tp = intotcpcb(inp);
674         if (tp == NULL) {
675                 rstreason = BANDLIM_RST_CLOSEDPORT;
676                 goto dropwithreset;
677         }
678         if (tp->t_state == TCPS_CLOSED)
679                 goto drop;
680
681         /* Unscale the window into a 32-bit value. */
682         if ((thflags & TH_SYN) == 0)
683                 tiwin = th->th_win << tp->snd_scale;
684         else
685                 tiwin = th->th_win;
686
687         so = inp->inp_socket;
688
689 #ifdef TCPDEBUG
690         if (so->so_options & SO_DEBUG) {
691                 ostate = tp->t_state;
692                 if (isipv6)
693                         bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
694                 else
695                         bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
696                 tcp_savetcp = *th;
697         }
698 #endif
699
700         if (so->so_options & SO_ACCEPTCONN) {
701                 struct in_conninfo inc;
702
703 #ifdef INET6
704                 inc.inc_isipv6 = isipv6;
705 #endif
706                 if (isipv6) {
707                         inc.inc6_faddr = ip6->ip6_src;
708                         inc.inc6_laddr = ip6->ip6_dst;
709                         inc.inc6_route.ro_rt = NULL;            /* XXX */
710                 } else {
711                         inc.inc_faddr = ip->ip_src;
712                         inc.inc_laddr = ip->ip_dst;
713                         inc.inc_route.ro_rt = NULL;             /* XXX */
714                 }
715                 inc.inc_fport = th->th_sport;
716                 inc.inc_lport = th->th_dport;
717
718                 /*
719                  * If the state is LISTEN then ignore segment if it contains
720                  * a RST.  If the segment contains an ACK then it is bad and
721                  * send a RST.  If it does not contain a SYN then it is not
722                  * interesting; drop it.
723                  *
724                  * If the state is SYN_RECEIVED (syncache) and seg contains
725                  * an ACK, but not for our SYN/ACK, send a RST.  If the seg
726                  * contains a RST, check the sequence number to see if it
727                  * is a valid reset segment.
728                  */
729                 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
730                         if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
731                                 if (!syncache_expand(&inc, th, &so, m)) {
732                                         /*
733                                          * No syncache entry, or ACK was not
734                                          * for our SYN/ACK.  Send a RST.
735                                          */
736                                         tcpstat.tcps_badsyn++;
737                                         rstreason = BANDLIM_RST_OPENPORT;
738                                         goto dropwithreset;
739                                 }
740                                 if (so == NULL)
741                                         /*
742                                          * Could not complete 3-way handshake,
743                                          * connection is being closed down, and
744                                          * syncache will free mbuf.
745                                          */
746                                         return;
747                                 /*
748                                  * Socket is created in state SYN_RECEIVED.
749                                  * Continue processing segment.
750                                  */
751                                 inp = sotoinpcb(so);
752                                 tp = intotcpcb(inp);
753                                 /*
754                                  * This is what would have happened in
755                                  * tcp_output() when the SYN,ACK was sent.
756                                  */
757                                 tp->snd_up = tp->snd_una;
758                                 tp->snd_max = tp->snd_nxt = tp->iss + 1;
759                                 tp->last_ack_sent = tp->rcv_nxt;
760 /*
761  * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
762  * until the _second_ ACK is received:
763  *    rcv SYN (set wscale opts)  --> send SYN/ACK, set snd_wnd = window.
764  *    rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
765  *        move to ESTAB, set snd_wnd to tiwin.
766  */        
767                                 tp->snd_wnd = tiwin;    /* unscaled */
768                                 goto after_listen;
769                         }
770                         if (thflags & TH_RST) {
771                                 syncache_chkrst(&inc, th);
772                                 goto drop;
773                         }
774                         if (thflags & TH_ACK) {
775                                 syncache_badack(&inc);
776                                 tcpstat.tcps_badsyn++;
777                                 rstreason = BANDLIM_RST_OPENPORT;
778                                 goto dropwithreset;
779                         }
780                         goto drop;
781                 }
782
783                 /*
784                  * Segment's flags are (SYN) or (SYN|FIN).
785                  */
786 #ifdef INET6
787                 /*
788                  * If deprecated address is forbidden,
789                  * we do not accept SYN to deprecated interface
790                  * address to prevent any new inbound connection from
791                  * getting established.
792                  * When we do not accept SYN, we send a TCP RST,
793                  * with deprecated source address (instead of dropping
794                  * it).  We compromise it as it is much better for peer
795                  * to send a RST, and RST will be the final packet
796                  * for the exchange.
797                  *
798                  * If we do not forbid deprecated addresses, we accept
799                  * the SYN packet.  RFC2462 does not suggest dropping
800                  * SYN in this case.
801                  * If we decipher RFC2462 5.5.4, it says like this:
802                  * 1. use of deprecated addr with existing
803                  *    communication is okay - "SHOULD continue to be
804                  *    used"
805                  * 2. use of it with new communication:
806                  *   (2a) "SHOULD NOT be used if alternate address
807                  *        with sufficient scope is available"
808                  *   (2b) nothing mentioned otherwise.
809                  * Here we fall into (2b) case as we have no choice in
810                  * our source address selection - we must obey the peer.
811                  *
812                  * The wording in RFC2462 is confusing, and there are
813                  * multiple description text for deprecated address
814                  * handling - worse, they are not exactly the same.
815                  * I believe 5.5.4 is the best one, so we follow 5.5.4.
816                  */
817                 if (isipv6 && !ip6_use_deprecated) {
818                         struct in6_ifaddr *ia6;
819
820                         if ((ia6 = ip6_getdstifaddr(m)) &&
821                             (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
822                                 tp = NULL;
823                                 rstreason = BANDLIM_RST_OPENPORT;
824                                 goto dropwithreset;
825                         }
826                 }
827 #endif
828                 /*
829                  * If it is from this socket, drop it, it must be forged.
830                  * Don't bother responding if the destination was a broadcast.
831                  */
832                 if (th->th_dport == th->th_sport) {
833                         if (isipv6) {
834                                 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
835                                                        &ip6->ip6_src))
836                                         goto drop;
837                         } else {
838                                 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
839                                         goto drop;
840                         }
841                 }
842                 /*
843                  * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
844                  *
845                  * Note that it is quite possible to receive unicast
846                  * link-layer packets with a broadcast IP address. Use
847                  * in_broadcast() to find them.
848                  */
849                 if (m->m_flags & (M_BCAST|M_MCAST))
850                         goto drop;
851                 if (isipv6) {
852                         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
853                             IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
854                                 goto drop;
855                 } else {
856                         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
857                             IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
858                             ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
859                             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
860                                 goto drop;
861                 }
862                 /*
863                  * SYN appears to be valid; create compressed TCP state
864                  * for syncache, or perform t/tcp connection.
865                  */
866                 if (so->so_qlen <= so->so_qlimit) {
867                         tcp_dooptions(&to, optp, optlen, 1);
868                         if (!syncache_add(&inc, &to, th, &so, m))
869                                 goto drop;
870                         if (so == NULL)
871                                 /*
872                                  * Entry added to syncache, mbuf used to
873                                  * send SYN,ACK packet.
874                                  */
875                                 return;
876                         /*
877                          * Segment passed TAO tests.
878                          */
879                         inp = sotoinpcb(so);
880                         tp = intotcpcb(inp);
881                         tp->snd_wnd = tiwin;
882                         tp->t_starttime = ticks;
883                         tp->t_state = TCPS_ESTABLISHED;
884
885                         /*
886                          * If there is a FIN, or if there is data and the
887                          * connection is local, then delay SYN,ACK(SYN) in
888                          * the hope of piggy-backing it on a response
889                          * segment.  Otherwise must send ACK now in case
890                          * the other side is slow starting.
891                          */
892                         if (DELAY_ACK(tp) &&
893                             ((thflags & TH_FIN) ||
894                              (tlen != 0 &&
895                               ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
896                                (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
897                                 callout_reset(tp->tt_delack, tcp_delacktime,  
898                                                 tcp_timer_delack, tp);  
899                                 tp->t_flags |= TF_NEEDSYN;
900                         } else 
901                                 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
902
903                         tcpstat.tcps_connects++;
904                         soisconnected(so);
905                         goto trimthenstep6;
906                 }
907                 goto drop;
908         }
909 after_listen:
910
911 /* XXX temp debugging */
912         /* should not happen - syncache should pick up these connections */
913         if (tp->t_state == TCPS_LISTEN)
914                 panic("tcp_input: TCPS_LISTEN");
915
916         /*
917          * Segment received on connection.
918          * Reset idle time and keep-alive timer.
919          */
920         tp->t_rcvtime = ticks;
921         if (TCPS_HAVEESTABLISHED(tp->t_state))
922                 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
923
924         /*
925          * Process options.
926          * XXX this is tradtitional behavior, may need to be cleaned up.
927          */
928         tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
929         if (thflags & TH_SYN) {
930                 if (to.to_flags & TOF_SCALE) {
931                         tp->t_flags |= TF_RCVD_SCALE;
932                         tp->requested_s_scale = to.to_requested_s_scale;
933                 }
934                 if (to.to_flags & TOF_TS) {
935                         tp->t_flags |= TF_RCVD_TSTMP;
936                         tp->ts_recent = to.to_tsval;
937                         tp->ts_recent_age = ticks;
938                 }
939                 if (to.to_flags & (TOF_CC|TOF_CCNEW))
940                         tp->t_flags |= TF_RCVD_CC;
941                 if (to.to_flags & TOF_MSS)
942                         tcp_mss(tp, to.to_mss);
943         }
944
945         /*
946          * Header prediction: check for the two common cases
947          * of a uni-directional data xfer.  If the packet has
948          * no control flags, is in-sequence, the window didn't
949          * change and we're not retransmitting, it's a
950          * candidate.  If the length is zero and the ack moved
951          * forward, we're the sender side of the xfer.  Just
952          * free the data acked & wake any higher level process
953          * that was blocked waiting for space.  If the length
954          * is non-zero and the ack didn't move, we're the
955          * receiver side.  If we're getting packets in-order
956          * (the reassembly queue is empty), add the data to
957          * the socket buffer and note that we need a delayed ack.
958          * Make sure that the hidden state-flags are also off.
959          * Since we check for TCPS_ESTABLISHED above, it can only
960          * be TH_NEEDSYN.
961          */
962         if (tp->t_state == TCPS_ESTABLISHED &&
963             (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
964             ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
965             ((to.to_flags & TOF_TS) == 0 ||
966              TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
967             /*
968              * Using the CC option is compulsory if once started:
969              *   the segment is OK if no T/TCP was negotiated or
970              *   if the segment has a CC option equal to CCrecv
971              */
972             ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
973              ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
974             th->th_seq == tp->rcv_nxt &&
975             tiwin && tiwin == tp->snd_wnd &&
976             tp->snd_nxt == tp->snd_max) {
977
978                 /*
979                  * If last ACK falls within this segment's sequence numbers,
980                  * record the timestamp.
981                  * NOTE that the test is modified according to the latest
982                  * proposal of the tcplw@cray.com list (Braden 1993/04/26).
983                  */
984                 if ((to.to_flags & TOF_TS) != 0 &&
985                     SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
986                         tp->ts_recent_age = ticks;
987                         tp->ts_recent = to.to_tsval;
988                 }
989
990                 if (tlen == 0) {
991                         if (SEQ_GT(th->th_ack, tp->snd_una) &&
992                             SEQ_LEQ(th->th_ack, tp->snd_max) &&
993                             tp->snd_cwnd >= tp->snd_wnd &&
994                             ((!tcp_do_newreno &&
995                               tp->t_dupacks < tcprexmtthresh) ||
996                              (tcp_do_newreno && !IN_FASTRECOVERY(tp)))) {
997                                 /*
998                                  * this is a pure ack for outstanding data.
999                                  */
1000                                 ++tcpstat.tcps_predack;
1001                                 /*
1002                                  * "bad retransmit" recovery
1003                                  *
1004                                  * If Eifel detection applies, then
1005                                  * it is deterministic, so use it
1006                                  * unconditionally over the old heuristic.
1007                                  * Otherwise, fall back to the old heuristic.
1008                                  */
1009                                 if (tcp_do_eifel_detect &&
1010                                     (to.to_flags & TOF_TS) && to.to_tsecr &&
1011                                     (tp->t_flags & TF_FIRSTACCACK)) {
1012                                         /* Eifel detection applicable. */
1013                                         if (to.to_tsecr < tp->t_rexmtTS) {
1014                                                 tcp_revert_congestion_state(tp);
1015                                                 ++tcpstat.tcps_eifeldetected;
1016                                         }
1017                                 } else if (tp->t_rxtshift == 1 &&
1018                                            ticks < tp->t_badrxtwin) {
1019                                         tcp_revert_congestion_state(tp);
1020                                         ++tcpstat.tcps_rttdetected;
1021                                 }
1022                                 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
1023                                 /*
1024                                  * Recalculate the retransmit timer / rtt.
1025                                  *
1026                                  * Some machines (certain windows boxes) 
1027                                  * send broken timestamp replies during the
1028                                  * SYN+ACK phase, ignore timestamps of 0.
1029                                  */
1030                                 if ((to.to_flags & TOF_TS) != 0 &&
1031                                     to.to_tsecr) {
1032                                         tcp_xmit_timer(tp,
1033                                             ticks - to.to_tsecr + 1);
1034                                 } else if (tp->t_rtttime &&
1035                                             SEQ_GT(th->th_ack, tp->t_rtseq)) {
1036                                         tcp_xmit_timer(tp,
1037                                                        ticks - tp->t_rtttime);
1038                                 }
1039                                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1040                                 acked = th->th_ack - tp->snd_una;
1041                                 tcpstat.tcps_rcvackpack++;
1042                                 tcpstat.tcps_rcvackbyte += acked;
1043                                 sbdrop(&so->so_snd, acked);
1044                                 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1045                                     SEQ_LEQ(th->th_ack, tp->snd_recover))
1046                                         tp->snd_recover = th->th_ack - 1;
1047                                 tp->snd_una = th->th_ack;
1048                                 tp->t_dupacks = 0;
1049                                 m_freem(m);
1050                                 ND6_HINT(tp); /* some progress has been done */
1051
1052                                 /*
1053                                  * If all outstanding data are acked, stop
1054                                  * retransmit timer, otherwise restart timer
1055                                  * using current (possibly backed-off) value.
1056                                  * If process is waiting for space,
1057                                  * wakeup/selwakeup/signal.  If data
1058                                  * are ready to send, let tcp_output
1059                                  * decide between more output or persist.
1060                                  */
1061                                 if (tp->snd_una == tp->snd_max)
1062                                         callout_stop(tp->tt_rexmt);
1063                                 else if (!callout_active(tp->tt_persist))
1064                                         callout_reset(tp->tt_rexmt, 
1065                                                       tp->t_rxtcur,
1066                                                       tcp_timer_rexmt, tp);
1067
1068                                 sowwakeup(so);
1069                                 if (so->so_snd.sb_cc)
1070                                         (void) tcp_output(tp);
1071                                 return;
1072                         }
1073                 } else if (th->th_ack == tp->snd_una &&
1074                     LIST_EMPTY(&tp->t_segq) &&
1075                     tlen <= sbspace(&so->so_rcv)) {
1076                         /*
1077                          * this is a pure, in-sequence data packet
1078                          * with nothing on the reassembly queue and
1079                          * we have enough buffer space to take it.
1080                          */
1081                         ++tcpstat.tcps_preddat;
1082                         tp->rcv_nxt += tlen;
1083                         tcpstat.tcps_rcvpack++;
1084                         tcpstat.tcps_rcvbyte += tlen;
1085                         ND6_HINT(tp);   /* some progress has been done */
1086                         /*
1087                          * Add data to socket buffer.
1088                          */
1089                         if (so->so_state & SS_CANTRCVMORE) {
1090                                 m_freem(m);
1091                         } else {
1092                                 m_adj(m, drop_hdrlen);  /* delayed header drop */
1093                                 sbappend(&so->so_rcv, m);
1094                         }
1095                         sorwakeup(so);
1096                         if (DELAY_ACK(tp)) {
1097                                 callout_reset(tp->tt_delack, tcp_delacktime,
1098                                     tcp_timer_delack, tp);
1099                         } else {
1100                                 tp->t_flags |= TF_ACKNOW;
1101                                 tcp_output(tp);
1102                         }
1103                         return;
1104                 }
1105         }
1106
1107         /*
1108          * Calculate amount of space in receive window,
1109          * and then do TCP input processing.
1110          * Receive window is amount of space in rcv queue,
1111          * but not less than advertised window.
1112          */
1113         { int win;
1114
1115         win = sbspace(&so->so_rcv);
1116         if (win < 0)
1117                 win = 0;
1118         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1119         }
1120
1121         switch (tp->t_state) {
1122
1123         /*
1124          * If the state is SYN_RECEIVED:
1125          *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
1126          */
1127         case TCPS_SYN_RECEIVED:
1128                 if ((thflags & TH_ACK) &&
1129                     (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1130                      SEQ_GT(th->th_ack, tp->snd_max))) {
1131                                 rstreason = BANDLIM_RST_OPENPORT;
1132                                 goto dropwithreset;
1133                 }
1134                 break;
1135
1136         /*
1137          * If the state is SYN_SENT:
1138          *      if seg contains an ACK, but not for our SYN, drop the input.
1139          *      if seg contains a RST, then drop the connection.
1140          *      if seg does not contain SYN, then drop it.
1141          * Otherwise this is an acceptable SYN segment
1142          *      initialize tp->rcv_nxt and tp->irs
1143          *      if seg contains ack then advance tp->snd_una
1144          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1145          *      arrange for segment to be acked (eventually)
1146          *      continue processing rest of data/controls, beginning with URG
1147          */
1148         case TCPS_SYN_SENT:
1149                 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1150                         taop = &tao_noncached;
1151                         bzero(taop, sizeof(*taop));
1152                 }
1153
1154                 if ((thflags & TH_ACK) &&
1155                     (SEQ_LEQ(th->th_ack, tp->iss) ||
1156                      SEQ_GT(th->th_ack, tp->snd_max))) {
1157                         /*
1158                          * If we have a cached CCsent for the remote host,
1159                          * hence we haven't just crashed and restarted,
1160                          * do not send a RST.  This may be a retransmission
1161                          * from the other side after our earlier ACK was lost.
1162                          * Our new SYN, when it arrives, will serve as the
1163                          * needed ACK.
1164                          */
1165                         if (taop->tao_ccsent != 0)
1166                                 goto drop;
1167                         else {
1168                                 rstreason = BANDLIM_UNLIMITED;
1169                                 goto dropwithreset;
1170                         }
1171                 }
1172                 if (thflags & TH_RST) {
1173                         if (thflags & TH_ACK)
1174                                 tp = tcp_drop(tp, ECONNREFUSED);
1175                         goto drop;
1176                 }
1177                 if ((thflags & TH_SYN) == 0)
1178                         goto drop;
1179                 tp->snd_wnd = th->th_win;       /* initial send window */
1180                 tp->cc_recv = to.to_cc;         /* foreign CC */
1181
1182                 tp->irs = th->th_seq;
1183                 tcp_rcvseqinit(tp);
1184                 if (thflags & TH_ACK) {
1185                         /*
1186                          * Our SYN was acked.  If segment contains CC.ECHO
1187                          * option, check it to make sure this segment really
1188                          * matches our SYN.  If not, just drop it as old
1189                          * duplicate, but send an RST if we're still playing
1190                          * by the old rules.  If no CC.ECHO option, make sure
1191                          * we don't get fooled into using T/TCP.
1192                          */
1193                         if (to.to_flags & TOF_CCECHO) {
1194                                 if (tp->cc_send != to.to_ccecho) {
1195                                         if (taop->tao_ccsent != 0)
1196                                                 goto drop;
1197                                         else {
1198                                                 rstreason = BANDLIM_UNLIMITED;
1199                                                 goto dropwithreset;
1200                                         }
1201                                 }
1202                         } else
1203                                 tp->t_flags &= ~TF_RCVD_CC;
1204                         tcpstat.tcps_connects++;
1205                         soisconnected(so);
1206                         /* Do window scaling on this connection? */
1207                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1208                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1209                                 tp->snd_scale = tp->requested_s_scale;
1210                                 tp->rcv_scale = tp->request_r_scale;
1211                         }
1212                         /* Segment is acceptable, update cache if undefined. */
1213                         if (taop->tao_ccsent == 0)
1214                                 taop->tao_ccsent = to.to_ccecho;
1215
1216                         tp->rcv_adv += tp->rcv_wnd;
1217                         tp->snd_una++;          /* SYN is acked */
1218                         /*
1219                          * If there's data, delay ACK; if there's also a FIN
1220                          * ACKNOW will be turned on later.
1221                          */
1222                         if (DELAY_ACK(tp) && tlen != 0)
1223                                 callout_reset(tp->tt_delack, tcp_delacktime,  
1224                                     tcp_timer_delack, tp);  
1225                         else
1226                                 tp->t_flags |= TF_ACKNOW;
1227                         /*
1228                          * Received <SYN,ACK> in SYN_SENT[*] state.
1229                          * Transitions:
1230                          *      SYN_SENT  --> ESTABLISHED
1231                          *      SYN_SENT* --> FIN_WAIT_1
1232                          */
1233                         tp->t_starttime = ticks;
1234                         if (tp->t_flags & TF_NEEDFIN) {
1235                                 tp->t_state = TCPS_FIN_WAIT_1;
1236                                 tp->t_flags &= ~TF_NEEDFIN;
1237                                 thflags &= ~TH_SYN;
1238                         } else {
1239                                 tp->t_state = TCPS_ESTABLISHED;
1240                                 callout_reset(tp->tt_keep, tcp_keepidle,
1241                                               tcp_timer_keep, tp);
1242                         }
1243                 } else {
1244                         /*
1245                          * Received initial SYN in SYN-SENT[*] state =>
1246                          * simultaneous open.  If segment contains CC option
1247                          * and there is a cached CC, apply TAO test.
1248                          * If it succeeds, connection is * half-synchronized.
1249                          * Otherwise, do 3-way handshake:
1250                          *        SYN-SENT -> SYN-RECEIVED
1251                          *        SYN-SENT* -> SYN-RECEIVED*
1252                          * If there was no CC option, clear cached CC value.
1253                          */
1254                         tp->t_flags |= TF_ACKNOW;
1255                         callout_stop(tp->tt_rexmt);
1256                         if (to.to_flags & TOF_CC) {
1257                                 if (taop->tao_cc != 0 &&
1258                                     CC_GT(to.to_cc, taop->tao_cc)) {
1259                                         /*
1260                                          * update cache and make transition:
1261                                          *        SYN-SENT -> ESTABLISHED*
1262                                          *        SYN-SENT* -> FIN-WAIT-1*
1263                                          */
1264                                         taop->tao_cc = to.to_cc;
1265                                         tp->t_starttime = ticks;
1266                                         if (tp->t_flags & TF_NEEDFIN) {
1267                                                 tp->t_state = TCPS_FIN_WAIT_1;
1268                                                 tp->t_flags &= ~TF_NEEDFIN;
1269                                         } else {
1270                                                 tp->t_state = TCPS_ESTABLISHED;
1271                                                 callout_reset(tp->tt_keep,
1272                                                               tcp_keepidle,
1273                                                               tcp_timer_keep,
1274                                                               tp);
1275                                         }
1276                                         tp->t_flags |= TF_NEEDSYN;
1277                                 } else
1278                                         tp->t_state = TCPS_SYN_RECEIVED;
1279                         } else {
1280                                 /* CC.NEW or no option => invalidate cache */
1281                                 taop->tao_cc = 0;
1282                                 tp->t_state = TCPS_SYN_RECEIVED;
1283                         }
1284                 }
1285
1286 trimthenstep6:
1287                 /*
1288                  * Advance th->th_seq to correspond to first data byte.
1289                  * If data, trim to stay within window,
1290                  * dropping FIN if necessary.
1291                  */
1292                 th->th_seq++;
1293                 if (tlen > tp->rcv_wnd) {
1294                         todrop = tlen - tp->rcv_wnd;
1295                         m_adj(m, -todrop);
1296                         tlen = tp->rcv_wnd;
1297                         thflags &= ~TH_FIN;
1298                         tcpstat.tcps_rcvpackafterwin++;
1299                         tcpstat.tcps_rcvbyteafterwin += todrop;
1300                 }
1301                 tp->snd_wl1 = th->th_seq - 1;
1302                 tp->rcv_up = th->th_seq;
1303                 /*
1304                  * Client side of transaction: already sent SYN and data.
1305                  * If the remote host used T/TCP to validate the SYN,
1306                  * our data will be ACK'd; if so, enter normal data segment
1307                  * processing in the middle of step 5, ack processing.
1308                  * Otherwise, goto step 6.
1309                  */
1310                 if (thflags & TH_ACK)
1311                         goto process_ACK;
1312
1313                 goto step6;
1314
1315         /*
1316          * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1317          *      if segment contains a SYN and CC [not CC.NEW] option:
1318          *              if state == TIME_WAIT and connection duration > MSL,
1319          *                  drop packet and send RST;
1320          *
1321          *              if SEG.CC > CCrecv then is new SYN, and can implicitly
1322          *                  ack the FIN (and data) in retransmission queue.
1323          *                  Complete close and delete TCPCB.  Then reprocess
1324          *                  segment, hoping to find new TCPCB in LISTEN state;
1325          *
1326          *              else must be old SYN; drop it.
1327          *      else do normal processing.
1328          */
1329         case TCPS_LAST_ACK:
1330         case TCPS_CLOSING:
1331         case TCPS_TIME_WAIT:
1332                 if ((thflags & TH_SYN) &&
1333                     (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1334                         if (tp->t_state == TCPS_TIME_WAIT &&
1335                                         (ticks - tp->t_starttime) > tcp_msl) {
1336                                 rstreason = BANDLIM_UNLIMITED;
1337                                 goto dropwithreset;
1338                         }
1339                         if (CC_GT(to.to_cc, tp->cc_recv)) {
1340                                 tp = tcp_close(tp);
1341                                 goto findpcb;
1342                         }
1343                         else
1344                                 goto drop;
1345                 }
1346                 break;  /* continue normal processing */
1347         }
1348
1349         /*
1350          * States other than LISTEN or SYN_SENT.
1351          * First check the RST flag and sequence number since reset segments
1352          * are exempt from the timestamp and connection count tests.  This
1353          * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1354          * below which allowed reset segments in half the sequence space
1355          * to fall though and be processed (which gives forged reset
1356          * segments with a random sequence number a 50 percent chance of
1357          * killing a connection).
1358          * Then check timestamp, if present.
1359          * Then check the connection count, if present.
1360          * Then check that at least some bytes of segment are within
1361          * receive window.  If segment begins before rcv_nxt,
1362          * drop leading data (and SYN); if nothing left, just ack.
1363          *
1364          *
1365          * If the RST bit is set, check the sequence number to see
1366          * if this is a valid reset segment.
1367          * RFC 793 page 37:
1368          *   In all states except SYN-SENT, all reset (RST) segments
1369          *   are validated by checking their SEQ-fields.  A reset is
1370          *   valid if its sequence number is in the window.
1371          * Note: this does not take into account delayed ACKs, so
1372          *   we should test against last_ack_sent instead of rcv_nxt.
1373          *   The sequence number in the reset segment is normally an
1374          *   echo of our outgoing acknowlegement numbers, but some hosts
1375          *   send a reset with the sequence number at the rightmost edge
1376          *   of our receive window, and we have to handle this case.
1377          * If we have multiple segments in flight, the intial reset
1378          * segment sequence numbers will be to the left of last_ack_sent,
1379          * but they will eventually catch up.
1380          * In any case, it never made sense to trim reset segments to
1381          * fit the receive window since RFC 1122 says:
1382          *   4.2.2.12  RST Segment: RFC-793 Section 3.4
1383          *
1384          *    A TCP SHOULD allow a received RST segment to include data.
1385          *
1386          *    DISCUSSION
1387          *         It has been suggested that a RST segment could contain
1388          *         ASCII text that encoded and explained the cause of the
1389          *         RST.  No standard has yet been established for such
1390          *         data.
1391          *
1392          * If the reset segment passes the sequence number test examine
1393          * the state:
1394          *    SYN_RECEIVED STATE:
1395          *      If passive open, return to LISTEN state.
1396          *      If active open, inform user that connection was refused.
1397          *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1398          *      Inform user that connection was reset, and close tcb.
1399          *    CLOSING, LAST_ACK STATES:
1400          *      Close the tcb.
1401          *    TIME_WAIT STATE:
1402          *      Drop the segment - see Stevens, vol. 2, p. 964 and
1403          *      RFC 1337.
1404          */
1405         if (thflags & TH_RST) {
1406                 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1407                     SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1408                         switch (tp->t_state) {
1409
1410                         case TCPS_SYN_RECEIVED:
1411                                 so->so_error = ECONNREFUSED;
1412                                 goto close;
1413
1414                         case TCPS_ESTABLISHED:
1415                         case TCPS_FIN_WAIT_1:
1416                         case TCPS_FIN_WAIT_2:
1417                         case TCPS_CLOSE_WAIT:
1418                                 so->so_error = ECONNRESET;
1419                         close:
1420                                 tp->t_state = TCPS_CLOSED;
1421                                 tcpstat.tcps_drops++;
1422                                 tp = tcp_close(tp);
1423                                 break;
1424
1425                         case TCPS_CLOSING:
1426                         case TCPS_LAST_ACK:
1427                                 tp = tcp_close(tp);
1428                                 break;
1429
1430                         case TCPS_TIME_WAIT:
1431                                 break;
1432                         }
1433                 }
1434                 goto drop;
1435         }
1436
1437         /*
1438          * RFC 1323 PAWS: If we have a timestamp reply on this segment
1439          * and it's less than ts_recent, drop it.
1440          */
1441         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1442             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1443
1444                 /* Check to see if ts_recent is over 24 days old.  */
1445                 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1446                         /*
1447                          * Invalidate ts_recent.  If this segment updates
1448                          * ts_recent, the age will be reset later and ts_recent
1449                          * will get a valid value.  If it does not, setting
1450                          * ts_recent to zero will at least satisfy the
1451                          * requirement that zero be placed in the timestamp
1452                          * echo reply when ts_recent isn't valid.  The
1453                          * age isn't reset until we get a valid ts_recent
1454                          * because we don't want out-of-order segments to be
1455                          * dropped when ts_recent is old.
1456                          */
1457                         tp->ts_recent = 0;
1458                 } else {
1459                         tcpstat.tcps_rcvduppack++;
1460                         tcpstat.tcps_rcvdupbyte += tlen;
1461                         tcpstat.tcps_pawsdrop++;
1462                         if (tlen)
1463                                 goto dropafterack;
1464                         goto drop;
1465                 }
1466         }
1467
1468         /*
1469          * T/TCP mechanism
1470          *   If T/TCP was negotiated and the segment doesn't have CC,
1471          *   or if its CC is wrong then drop the segment.
1472          *   RST segments do not have to comply with this.
1473          */
1474         if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1475             ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1476                 goto dropafterack;
1477
1478         /*
1479          * In the SYN-RECEIVED state, validate that the packet belongs to
1480          * this connection before trimming the data to fit the receive
1481          * window.  Check the sequence number versus IRS since we know
1482          * the sequence numbers haven't wrapped.  This is a partial fix
1483          * for the "LAND" DoS attack.
1484          */
1485         if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1486                 rstreason = BANDLIM_RST_OPENPORT;
1487                 goto dropwithreset;
1488         }
1489
1490         todrop = tp->rcv_nxt - th->th_seq;
1491         if (todrop > 0) {
1492                 if (thflags & TH_SYN) {
1493                         thflags &= ~TH_SYN;
1494                         th->th_seq++;
1495                         if (th->th_urp > 1)
1496                                 th->th_urp--;
1497                         else
1498                                 thflags &= ~TH_URG;
1499                         todrop--;
1500                 }
1501                 /*
1502                  * Following if statement from Stevens, vol. 2, p. 960.
1503                  */
1504                 if (todrop > tlen
1505                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1506                         /*
1507                          * Any valid FIN must be to the left of the window.
1508                          * At this point the FIN must be a duplicate or out
1509                          * of sequence; drop it.
1510                          */
1511                         thflags &= ~TH_FIN;
1512
1513                         /*
1514                          * Send an ACK to resynchronize and drop any data.
1515                          * But keep on processing for RST or ACK.
1516                          */
1517                         tp->t_flags |= TF_ACKNOW;
1518                         todrop = tlen;
1519                         tcpstat.tcps_rcvduppack++;
1520                         tcpstat.tcps_rcvdupbyte += todrop;
1521                 } else {
1522                         tcpstat.tcps_rcvpartduppack++;
1523                         tcpstat.tcps_rcvpartdupbyte += todrop;
1524                 }
1525                 drop_hdrlen += todrop;  /* drop from the top afterwards */
1526                 th->th_seq += todrop;
1527                 tlen -= todrop;
1528                 if (th->th_urp > todrop)
1529                         th->th_urp -= todrop;
1530                 else {
1531                         thflags &= ~TH_URG;
1532                         th->th_urp = 0;
1533                 }
1534         }
1535
1536         /*
1537          * If new data are received on a connection after the
1538          * user processes are gone, then RST the other end.
1539          */
1540         if ((so->so_state & SS_NOFDREF) &&
1541             tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1542                 tp = tcp_close(tp);
1543                 tcpstat.tcps_rcvafterclose++;
1544                 rstreason = BANDLIM_UNLIMITED;
1545                 goto dropwithreset;
1546         }
1547
1548         /*
1549          * If segment ends after window, drop trailing data
1550          * (and PUSH and FIN); if nothing left, just ACK.
1551          */
1552         todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1553         if (todrop > 0) {
1554                 tcpstat.tcps_rcvpackafterwin++;
1555                 if (todrop >= tlen) {
1556                         tcpstat.tcps_rcvbyteafterwin += tlen;
1557                         /*
1558                          * If a new connection request is received
1559                          * while in TIME_WAIT, drop the old connection
1560                          * and start over if the sequence numbers
1561                          * are above the previous ones.
1562                          */
1563                         if (thflags & TH_SYN &&
1564                             tp->t_state == TCPS_TIME_WAIT &&
1565                             SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1566                                 tp = tcp_close(tp);
1567                                 goto findpcb;
1568                         }
1569                         /*
1570                          * If window is closed can only take segments at
1571                          * window edge, and have to drop data and PUSH from
1572                          * incoming segments.  Continue processing, but
1573                          * remember to ack.  Otherwise, drop segment
1574                          * and ack.
1575                          */
1576                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1577                                 tp->t_flags |= TF_ACKNOW;
1578                                 tcpstat.tcps_rcvwinprobe++;
1579                         } else
1580                                 goto dropafterack;
1581                 } else
1582                         tcpstat.tcps_rcvbyteafterwin += todrop;
1583                 m_adj(m, -todrop);
1584                 tlen -= todrop;
1585                 thflags &= ~(TH_PUSH|TH_FIN);
1586         }
1587
1588         /*
1589          * If last ACK falls within this segment's sequence numbers,
1590          * record its timestamp.
1591          * NOTE that the test is modified according to the latest
1592          * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1593          */
1594         if ((to.to_flags & TOF_TS) != 0 &&
1595             SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1596                 tp->ts_recent_age = ticks;
1597                 tp->ts_recent = to.to_tsval;
1598         }
1599
1600         /*
1601          * If a SYN is in the window, then this is an
1602          * error and we send an RST and drop the connection.
1603          */
1604         if (thflags & TH_SYN) {
1605                 tp = tcp_drop(tp, ECONNRESET);
1606                 rstreason = BANDLIM_UNLIMITED;
1607                 goto dropwithreset;
1608         }
1609
1610         /*
1611          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1612          * flag is on (half-synchronized state), then queue data for
1613          * later processing; else drop segment and return.
1614          */
1615         if ((thflags & TH_ACK) == 0) {
1616                 if (tp->t_state == TCPS_SYN_RECEIVED ||
1617                     (tp->t_flags & TF_NEEDSYN))
1618                         goto step6;
1619                 else
1620                         goto drop;
1621         }
1622
1623         /*
1624          * Ack processing.
1625          */
1626         switch (tp->t_state) {
1627
1628         /*
1629          * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1630          * ESTABLISHED state and continue processing.
1631          * The ACK was checked above.
1632          */
1633         case TCPS_SYN_RECEIVED:
1634
1635                 tcpstat.tcps_connects++;
1636                 soisconnected(so);
1637                 /* Do window scaling? */
1638                 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1639                         (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1640                         tp->snd_scale = tp->requested_s_scale;
1641                         tp->rcv_scale = tp->request_r_scale;
1642                 }
1643                 /*
1644                  * Upon successful completion of 3-way handshake,
1645                  * update cache.CC if it was undefined, pass any queued
1646                  * data to the user, and advance state appropriately.
1647                  */
1648                 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1649                     taop->tao_cc == 0)
1650                         taop->tao_cc = tp->cc_recv;
1651
1652                 /*
1653                  * Make transitions:
1654                  *      SYN-RECEIVED  -> ESTABLISHED
1655                  *      SYN-RECEIVED* -> FIN-WAIT-1
1656                  */
1657                 tp->t_starttime = ticks;
1658                 if (tp->t_flags & TF_NEEDFIN) {
1659                         tp->t_state = TCPS_FIN_WAIT_1;
1660                         tp->t_flags &= ~TF_NEEDFIN;
1661                 } else {
1662                         tp->t_state = TCPS_ESTABLISHED;
1663                         callout_reset(tp->tt_keep, tcp_keepidle, 
1664                                       tcp_timer_keep, tp);
1665                 }
1666                 /*
1667                  * If segment contains data or ACK, will call tcp_reass()
1668                  * later; if not, do so now to pass queued data to user.
1669                  */
1670                 if (tlen == 0 && (thflags & TH_FIN) == 0)
1671                         (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1672                             (struct mbuf *)0);
1673                 tp->snd_wl1 = th->th_seq - 1;
1674                 /* fall into ... */
1675
1676         /*
1677          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1678          * ACKs.  If the ack is in the range
1679          *      tp->snd_una < th->th_ack <= tp->snd_max
1680          * then advance tp->snd_una to th->th_ack and drop
1681          * data from the retransmission queue.  If this ACK reflects
1682          * more up to date window information we update our window information.
1683          */
1684         case TCPS_ESTABLISHED:
1685         case TCPS_FIN_WAIT_1:
1686         case TCPS_FIN_WAIT_2:
1687         case TCPS_CLOSE_WAIT:
1688         case TCPS_CLOSING:
1689         case TCPS_LAST_ACK:
1690         case TCPS_TIME_WAIT:
1691
1692                 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1693                         if (tlen == 0 && tiwin == tp->snd_wnd) {
1694                                 tcpstat.tcps_rcvdupack++;
1695                                 /*
1696                                  * If we have outstanding data (other than
1697                                  * a window probe), this is a completely
1698                                  * duplicate ack (ie, window info didn't
1699                                  * change), the ack is the biggest we've
1700                                  * seen and we've seen exactly our rexmt
1701                                  * threshhold of them, assume a packet
1702                                  * has been dropped and retransmit it.
1703                                  * Kludge snd_nxt & the congestion
1704                                  * window so we send only this one
1705                                  * packet.
1706                                  *
1707                                  * We know we're losing at the current
1708                                  * window size so do congestion avoidance
1709                                  * (set ssthresh to half the current window
1710                                  * and pull our congestion window back to
1711                                  * the new ssthresh).
1712                                  *
1713                                  * Dup acks mean that packets have left the
1714                                  * network (they're now cached at the receiver)
1715                                  * so bump cwnd by the amount in the receiver
1716                                  * to keep a constant cwnd packets in the
1717                                  * network.
1718                                  */
1719                                 if (!callout_active(tp->tt_rexmt) ||
1720                                     th->th_ack != tp->snd_una)
1721                                         tp->t_dupacks = 0;
1722                                 else if (++tp->t_dupacks > tcprexmtthresh ||
1723                                          (tcp_do_newreno &&
1724                                           IN_FASTRECOVERY(tp))) {
1725                                         tp->snd_cwnd += tp->t_maxseg;
1726                                         (void) tcp_output(tp);
1727                                         goto drop;
1728                                 } else if (tp->t_dupacks == tcprexmtthresh) {
1729                                         tcp_seq onxt = tp->snd_nxt;
1730                                         u_int win;
1731                                         if (tcp_do_newreno &&
1732                                             SEQ_LEQ(th->th_ack,
1733                                                     tp->snd_recover)) {
1734                                                 tp->t_dupacks = 0;
1735                                                 break;
1736                                         }
1737                                         if (tcp_do_eifel_detect &&
1738                                             (tp->t_flags & TF_RCVD_TSTMP)) {
1739                                                 tcp_save_congestion_state(tp);
1740                                                 tp->t_flags |= TF_FASTREXMT;
1741                                         }
1742                                         win = min(tp->snd_wnd, tp->snd_cwnd) /
1743                                             2 / tp->t_maxseg;
1744                                         if (win < 2)
1745                                                 win = 2;
1746                                         tp->snd_ssthresh = win * tp->t_maxseg;
1747                                         ENTER_FASTRECOVERY(tp);
1748                                         tp->snd_recover = tp->snd_max;
1749                                         callout_stop(tp->tt_rexmt);
1750                                         tp->t_rtttime = 0;
1751                                         tp->snd_nxt = th->th_ack;
1752                                         tp->snd_cwnd = tp->t_maxseg;
1753                                         (void) tcp_output(tp);
1754                                         KASSERT(tp->snd_limited <= 2,
1755                                             ("tp->snd_limited too big"));
1756                                         tp->snd_cwnd = tp->snd_ssthresh +
1757                                             (tp->t_maxseg *
1758                                              (tp->t_dupacks - tp->snd_limited));
1759                                         if (SEQ_GT(onxt, tp->snd_nxt))
1760                                                 tp->snd_nxt = onxt;
1761                                         goto drop;
1762                                 } else if (tcp_do_limitedtransmit) {
1763                                         u_long oldcwnd = tp->snd_cwnd;
1764                                         tcp_seq oldsndmax = tp->snd_max;
1765                                         u_int sent;
1766
1767                                         KASSERT(tp->t_dupacks == 1 ||
1768                                             tp->t_dupacks == 2,
1769                                             ("dupacks not 1 or 2"));
1770                                         if (tp->t_dupacks == 1)
1771                                                 tp->snd_limited = 0;
1772                                         tp->snd_cwnd =
1773                                             (tp->snd_nxt - tp->snd_una) +
1774                                             (tp->t_dupacks - tp->snd_limited) *
1775                                             tp->t_maxseg;
1776                                         (void) tcp_output(tp);
1777                                         sent = tp->snd_max - oldsndmax;
1778                                         if (sent > tp->t_maxseg) {
1779                                                 KASSERT((tp->t_dupacks == 2 &&
1780                                                     tp->snd_limited == 0) ||
1781                                                    (sent == tp->t_maxseg + 1 &&
1782                                                     tp->t_flags & TF_SENTFIN),
1783                                                     ("sent too much"));
1784                                                 tp->snd_limited = 2;
1785                                         } else if (sent > 0)
1786                                                 ++tp->snd_limited;
1787                                         tp->snd_cwnd = oldcwnd;
1788                                         goto drop;
1789                                 }
1790                         } else
1791                                 tp->t_dupacks = 0;
1792                         break;
1793                 }
1794
1795                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1796
1797                 /*
1798                  * If the congestion window was inflated to account
1799                  * for the other side's cached packets, retract it.
1800                  */
1801                 if (tcp_do_newreno) {
1802                         if (IN_FASTRECOVERY(tp)) {
1803                                 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1804                                         tcp_newreno_partial_ack(tp, th);
1805                                 } else {
1806                                         /*
1807                                          * Window inflation should have left us
1808                                          * with approximately snd_ssthresh
1809                                          * outstanding data.
1810                                          * But in case we would be inclined to
1811                                          * send a burst, better to do it via
1812                                          * the slow start mechanism.
1813                                          */
1814                                         if (SEQ_GT(th->th_ack +
1815                                                         tp->snd_ssthresh,
1816                                                    tp->snd_max))
1817                                                 tp->snd_cwnd = tp->snd_max -
1818                                                                 th->th_ack +
1819                                                                 tp->t_maxseg;
1820                                         else
1821                                                 tp->snd_cwnd = tp->snd_ssthresh;
1822                                 }
1823                         }
1824                 } else {
1825                         if (tp->t_dupacks >= tcprexmtthresh &&
1826                             tp->snd_cwnd > tp->snd_ssthresh)
1827                                 tp->snd_cwnd = tp->snd_ssthresh;
1828                 }
1829                 tp->t_dupacks = 0;
1830                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1831                         tcpstat.tcps_rcvacktoomuch++;
1832                         goto dropafterack;
1833                 }
1834                 /*
1835                  * If we reach this point, ACK is not a duplicate,
1836                  *     i.e., it ACKs something we sent.
1837                  */
1838                 if (tp->t_flags & TF_NEEDSYN) {
1839                         /*
1840                          * T/TCP: Connection was half-synchronized, and our
1841                          * SYN has been ACK'd (so connection is now fully
1842                          * synchronized).  Go to non-starred state,
1843                          * increment snd_una for ACK of SYN, and check if
1844                          * we can do window scaling.
1845                          */
1846                         tp->t_flags &= ~TF_NEEDSYN;
1847                         tp->snd_una++;
1848                         /* Do window scaling? */
1849                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1850                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1851                                 tp->snd_scale = tp->requested_s_scale;
1852                                 tp->rcv_scale = tp->request_r_scale;
1853                         }
1854                 }
1855
1856 process_ACK:
1857                 acked = th->th_ack - tp->snd_una;
1858                 tcpstat.tcps_rcvackpack++;
1859                 tcpstat.tcps_rcvackbyte += acked;
1860
1861                 /*
1862                  * If we just performed our first retransmit, and the ACK
1863                  * arrives within our recovery window, then it was a mistake
1864                  * to do the retransmit in the first place.  Recover our
1865                  * original cwnd and ssthresh, and proceed to transmit where
1866                  * we left off.
1867                  */
1868                 if (tcp_do_eifel_detect && acked &&
1869                     (to.to_flags & TOF_TS) && to.to_tsecr &&
1870                     (tp->t_flags & TF_FIRSTACCACK)) {
1871                         /* Eifel detection applicable. */
1872                         if (to.to_tsecr < tp->t_rexmtTS) {
1873                                 tcp_revert_congestion_state(tp);
1874                                 ++tcpstat.tcps_eifeldetected;
1875                         }
1876                 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1877                         tcp_revert_congestion_state(tp);
1878                         ++tcpstat.tcps_rttdetected;
1879                 }
1880
1881                 /*
1882                  * If we have a timestamp reply, update smoothed
1883                  * round trip time.  If no timestamp is present but
1884                  * transmit timer is running and timed sequence
1885                  * number was acked, update smoothed round trip time.
1886                  * Since we now have an rtt measurement, cancel the
1887                  * timer backoff (cf., Phil Karn's retransmit alg.).
1888                  * Recompute the initial retransmit timer.
1889                  *
1890                  * Some machines (certain windows boxes) send broken
1891                  * timestamp replies during the SYN+ACK phase, ignore 
1892                  * timestamps of 0.
1893                  */
1894                 if ((to.to_flags & TOF_TS) != 0 &&
1895                     to.to_tsecr) {
1896                         tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1897                 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1898                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1899                 }
1900                 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1901
1902                 /*
1903                  * If all outstanding data is acked, stop retransmit
1904                  * timer and remember to restart (more output or persist).
1905                  * If there is more data to be acked, restart retransmit
1906                  * timer, using current (possibly backed-off) value.
1907                  */
1908                 if (th->th_ack == tp->snd_max) {
1909                         callout_stop(tp->tt_rexmt);
1910                         needoutput = 1;
1911                 } else if (!callout_active(tp->tt_persist))
1912                         callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1913                                       tcp_timer_rexmt, tp);
1914
1915                 /*
1916                  * If no data (only SYN) was ACK'd,
1917                  *    skip rest of ACK processing.
1918                  */
1919                 if (acked == 0)
1920                         goto step6;
1921
1922                 /* Stop looking for an acceptable ACK since one was received. */
1923                 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT);
1924
1925                 /*
1926                  * When new data is acked, open the congestion window.
1927                  * If the window gives us less than ssthresh packets
1928                  * in flight, open exponentially (maxseg per packet).
1929                  * Otherwise open linearly: maxseg per window
1930                  * (maxseg^2 / cwnd per packet).
1931                  */
1932                 if (!tcp_do_newreno || !IN_FASTRECOVERY(tp)) {
1933                         u_int cw = tp->snd_cwnd;
1934                         u_int incr = tp->t_maxseg;
1935                         if (cw > tp->snd_ssthresh)
1936                                 incr = incr * incr / cw;
1937                         tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
1938                 }
1939                 if (acked > so->so_snd.sb_cc) {
1940                         tp->snd_wnd -= so->so_snd.sb_cc;
1941                         sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1942                         ourfinisacked = 1;
1943                 } else {
1944                         sbdrop(&so->so_snd, acked);
1945                         tp->snd_wnd -= acked;
1946                         ourfinisacked = 0;
1947                 }
1948                 sowwakeup(so);
1949                 /* detect una wraparound */
1950                 if (tcp_do_newreno && !IN_FASTRECOVERY(tp) &&
1951                     SEQ_GT(tp->snd_una, tp->snd_recover) &&
1952                     SEQ_LEQ(th->th_ack, tp->snd_recover))
1953                         tp->snd_recover = th->th_ack - 1;
1954                 if (tcp_do_newreno && IN_FASTRECOVERY(tp) &&
1955                     SEQ_GEQ(th->th_ack, tp->snd_recover))
1956                         EXIT_FASTRECOVERY(tp);
1957                 tp->snd_una = th->th_ack;
1958                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1959                         tp->snd_nxt = tp->snd_una;
1960
1961                 switch (tp->t_state) {
1962
1963                 /*
1964                  * In FIN_WAIT_1 STATE in addition to the processing
1965                  * for the ESTABLISHED state if our FIN is now acknowledged
1966                  * then enter FIN_WAIT_2.
1967                  */
1968                 case TCPS_FIN_WAIT_1:
1969                         if (ourfinisacked) {
1970                                 /*
1971                                  * If we can't receive any more
1972                                  * data, then closing user can proceed.
1973                                  * Starting the timer is contrary to the
1974                                  * specification, but if we don't get a FIN
1975                                  * we'll hang forever.
1976                                  */
1977                                 if (so->so_state & SS_CANTRCVMORE) {
1978                                         soisdisconnected(so);
1979                                         callout_reset(tp->tt_2msl, tcp_maxidle,
1980                                                       tcp_timer_2msl, tp);
1981                                 }
1982                                 tp->t_state = TCPS_FIN_WAIT_2;
1983                         }
1984                         break;
1985
1986                 /*
1987                  * In CLOSING STATE in addition to the processing for
1988                  * the ESTABLISHED state if the ACK acknowledges our FIN
1989                  * then enter the TIME-WAIT state, otherwise ignore
1990                  * the segment.
1991                  */
1992                 case TCPS_CLOSING:
1993                         if (ourfinisacked) {
1994                                 tp->t_state = TCPS_TIME_WAIT;
1995                                 tcp_canceltimers(tp);
1996                                 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1997                                 if (tp->cc_recv != 0 &&
1998                                     (ticks - tp->t_starttime) < tcp_msl)
1999                                         callout_reset(tp->tt_2msl,
2000                                                       tp->t_rxtcur *
2001                                                       TCPTV_TWTRUNC,
2002                                                       tcp_timer_2msl, tp);
2003                                 else
2004                                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2005                                                       tcp_timer_2msl, tp);
2006                                 soisdisconnected(so);
2007                         }
2008                         break;
2009
2010                 /*
2011                  * In LAST_ACK, we may still be waiting for data to drain
2012                  * and/or to be acked, as well as for the ack of our FIN.
2013                  * If our FIN is now acknowledged, delete the TCB,
2014                  * enter the closed state and return.
2015                  */
2016                 case TCPS_LAST_ACK:
2017                         if (ourfinisacked) {
2018                                 tp = tcp_close(tp);
2019                                 goto drop;
2020                         }
2021                         break;
2022
2023                 /*
2024                  * In TIME_WAIT state the only thing that should arrive
2025                  * is a retransmission of the remote FIN.  Acknowledge
2026                  * it and restart the finack timer.
2027                  */
2028                 case TCPS_TIME_WAIT:
2029                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2030                                       tcp_timer_2msl, tp);
2031                         goto dropafterack;
2032                 }
2033         }
2034
2035 step6:
2036         /*
2037          * Update window information.
2038          * Don't look at window if no ACK: TAC's send garbage on first SYN.
2039          */
2040         if ((thflags & TH_ACK) &&
2041             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2042             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2043              (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2044                 /* keep track of pure window updates */
2045                 if (tlen == 0 &&
2046                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2047                         tcpstat.tcps_rcvwinupd++;
2048                 tp->snd_wnd = tiwin;
2049                 tp->snd_wl1 = th->th_seq;
2050                 tp->snd_wl2 = th->th_ack;
2051                 if (tp->snd_wnd > tp->max_sndwnd)
2052                         tp->max_sndwnd = tp->snd_wnd;
2053                 needoutput = 1;
2054         }
2055
2056         /*
2057          * Process segments with URG.
2058          */
2059         if ((thflags & TH_URG) && th->th_urp &&
2060             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2061                 /*
2062                  * This is a kludge, but if we receive and accept
2063                  * random urgent pointers, we'll crash in
2064                  * soreceive.  It's hard to imagine someone
2065                  * actually wanting to send this much urgent data.
2066                  */
2067                 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2068                         th->th_urp = 0;                 /* XXX */
2069                         thflags &= ~TH_URG;             /* XXX */
2070                         goto dodata;                    /* XXX */
2071                 }
2072                 /*
2073                  * If this segment advances the known urgent pointer,
2074                  * then mark the data stream.  This should not happen
2075                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2076                  * a FIN has been received from the remote side.
2077                  * In these states we ignore the URG.
2078                  *
2079                  * According to RFC961 (Assigned Protocols),
2080                  * the urgent pointer points to the last octet
2081                  * of urgent data.  We continue, however,
2082                  * to consider it to indicate the first octet
2083                  * of data past the urgent section as the original
2084                  * spec states (in one of two places).
2085                  */
2086                 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2087                         tp->rcv_up = th->th_seq + th->th_urp;
2088                         so->so_oobmark = so->so_rcv.sb_cc +
2089                             (tp->rcv_up - tp->rcv_nxt) - 1;
2090                         if (so->so_oobmark == 0)
2091                                 so->so_state |= SS_RCVATMARK;
2092                         sohasoutofband(so);
2093                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2094                 }
2095                 /*
2096                  * Remove out of band data so doesn't get presented to user.
2097                  * This can happen independent of advancing the URG pointer,
2098                  * but if two URG's are pending at once, some out-of-band
2099                  * data may creep in... ick.
2100                  */
2101                 if (th->th_urp <= (u_long)tlen
2102 #ifdef SO_OOBINLINE
2103                      && (so->so_options & SO_OOBINLINE) == 0
2104 #endif
2105                      )
2106                         tcp_pulloutofband(so, th, m,
2107                                 drop_hdrlen);   /* hdr drop is delayed */
2108         } else {
2109                 /*
2110                  * If no out of band data is expected,
2111                  * pull receive urgent pointer along
2112                  * with the receive window.
2113                  */
2114                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2115                         tp->rcv_up = tp->rcv_nxt;
2116         }
2117 dodata:                                                 /* XXX */
2118
2119         /*
2120          * Process the segment text, merging it into the TCP sequencing queue,
2121          * and arranging for acknowledgment of receipt if necessary.
2122          * This process logically involves adjusting tp->rcv_wnd as data
2123          * is presented to the user (this happens in tcp_usrreq.c,
2124          * case PRU_RCVD).  If a FIN has already been received on this
2125          * connection then we just ignore the text.
2126          */
2127         if ((tlen || (thflags & TH_FIN)) &&
2128             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2129                 m_adj(m, drop_hdrlen);  /* delayed header drop */
2130                 /*
2131                  * Insert segment which includes th into TCP reassembly queue
2132                  * with control block tp.  Set thflags to whether reassembly now
2133                  * includes a segment with FIN.  This handles the common case
2134                  * inline (segment is the next to be received on an established
2135                  * connection, and the queue is empty), avoiding linkage into
2136                  * and removal from the queue and repetition of various
2137                  * conversions.
2138                  * Set DELACK for segments received in order, but ack
2139                  * immediately when segments are out of order (so
2140                  * fast retransmit can work).
2141                  */
2142                 if (th->th_seq == tp->rcv_nxt &&
2143                     LIST_EMPTY(&tp->t_segq) &&
2144                     TCPS_HAVEESTABLISHED(tp->t_state)) {
2145                         if (DELAY_ACK(tp))
2146                                 callout_reset(tp->tt_delack, tcp_delacktime,
2147                                               tcp_timer_delack, tp);
2148                         else
2149                                 tp->t_flags |= TF_ACKNOW;
2150                         tp->rcv_nxt += tlen;
2151                         thflags = th->th_flags & TH_FIN;
2152                         tcpstat.tcps_rcvpack++;
2153                         tcpstat.tcps_rcvbyte += tlen;
2154                         ND6_HINT(tp);
2155                         if (so->so_state & SS_CANTRCVMORE)
2156                                 m_freem(m);
2157                         else
2158                                 sbappend(&so->so_rcv, m);
2159                         sorwakeup(so);
2160                 } else {
2161                         thflags = tcp_reass(tp, th, &tlen, m);
2162                         tp->t_flags |= TF_ACKNOW;
2163                 }
2164
2165                 /*
2166                  * Note the amount of data that peer has sent into
2167                  * our window, in order to estimate the sender's
2168                  * buffer size.
2169                  */
2170                 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2171         } else {
2172                 m_freem(m);
2173                 thflags &= ~TH_FIN;
2174         }
2175
2176         /*
2177          * If FIN is received ACK the FIN and let the user know
2178          * that the connection is closing.
2179          */
2180         if (thflags & TH_FIN) {
2181                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2182                         socantrcvmore(so);
2183                         /*
2184                          * If connection is half-synchronized
2185                          * (ie NEEDSYN flag on) then delay ACK,
2186                          * so it may be piggybacked when SYN is sent.
2187                          * Otherwise, since we received a FIN then no
2188                          * more input can be expected, send ACK now.
2189                          */
2190                         if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2191                                 callout_reset(tp->tt_delack, tcp_delacktime,  
2192                                     tcp_timer_delack, tp);  
2193                         else
2194                                 tp->t_flags |= TF_ACKNOW;
2195                         tp->rcv_nxt++;
2196                 }
2197                 switch (tp->t_state) {
2198
2199                 /*
2200                  * In SYN_RECEIVED and ESTABLISHED STATES
2201                  * enter the CLOSE_WAIT state.
2202                  */
2203                 case TCPS_SYN_RECEIVED:
2204                         tp->t_starttime = ticks;
2205                         /*FALLTHROUGH*/
2206                 case TCPS_ESTABLISHED:
2207                         tp->t_state = TCPS_CLOSE_WAIT;
2208                         break;
2209
2210                 /*
2211                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
2212                  * enter the CLOSING state.
2213                  */
2214                 case TCPS_FIN_WAIT_1:
2215                         tp->t_state = TCPS_CLOSING;
2216                         break;
2217
2218                 /*
2219                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
2220                  * starting the time-wait timer, turning off the other
2221                  * standard timers.
2222                  */
2223                 case TCPS_FIN_WAIT_2:
2224                         tp->t_state = TCPS_TIME_WAIT;
2225                         tcp_canceltimers(tp);
2226                         /* Shorten TIME_WAIT [RFC-1644, p.28] */
2227                         if (tp->cc_recv != 0 &&
2228                             (ticks - tp->t_starttime) < tcp_msl) {
2229                                 callout_reset(tp->tt_2msl,
2230                                               tp->t_rxtcur * TCPTV_TWTRUNC,
2231                                               tcp_timer_2msl, tp);
2232                                 /* For transaction client, force ACK now. */
2233                                 tp->t_flags |= TF_ACKNOW;
2234                         }
2235                         else
2236                                 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2237                                               tcp_timer_2msl, tp);
2238                         soisdisconnected(so);
2239                         break;
2240
2241                 /*
2242                  * In TIME_WAIT state restart the 2 MSL time_wait timer.
2243                  */
2244                 case TCPS_TIME_WAIT:
2245                         callout_reset(tp->tt_2msl, 2 * tcp_msl,
2246                                       tcp_timer_2msl, tp);
2247                         break;
2248                 }
2249         }
2250 #ifdef TCPDEBUG
2251         if (so->so_options & SO_DEBUG)
2252                 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2253                           &tcp_savetcp, 0);
2254 #endif
2255
2256         /*
2257          * Return any desired output.
2258          */
2259         if (needoutput || (tp->t_flags & TF_ACKNOW))
2260                 (void) tcp_output(tp);
2261         return;
2262
2263 dropafterack:
2264         /*
2265          * Generate an ACK dropping incoming segment if it occupies
2266          * sequence space, where the ACK reflects our state.
2267          *
2268          * We can now skip the test for the RST flag since all
2269          * paths to this code happen after packets containing
2270          * RST have been dropped.
2271          *
2272          * In the SYN-RECEIVED state, don't send an ACK unless the
2273          * segment we received passes the SYN-RECEIVED ACK test.
2274          * If it fails send a RST.  This breaks the loop in the
2275          * "LAND" DoS attack, and also prevents an ACK storm
2276          * between two listening ports that have been sent forged
2277          * SYN segments, each with the source address of the other.
2278          */
2279         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2280             (SEQ_GT(tp->snd_una, th->th_ack) ||
2281              SEQ_GT(th->th_ack, tp->snd_max)) ) {
2282                 rstreason = BANDLIM_RST_OPENPORT;
2283                 goto dropwithreset;
2284         }
2285 #ifdef TCPDEBUG
2286         if (so->so_options & SO_DEBUG)
2287                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2288                           &tcp_savetcp, 0);
2289 #endif
2290         m_freem(m);
2291         tp->t_flags |= TF_ACKNOW;
2292         (void) tcp_output(tp);
2293         return;
2294
2295 dropwithreset:
2296         /*
2297          * Generate a RST, dropping incoming segment.
2298          * Make ACK acceptable to originator of segment.
2299          * Don't bother to respond if destination was broadcast/multicast.
2300          */
2301         if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2302                 goto drop;
2303         if (isipv6) {
2304                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2305                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2306                         goto drop;
2307         } else {
2308                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2309                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2310                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2311                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2312                         goto drop;
2313         }
2314         /* IPv6 anycast check is done at tcp6_input() */
2315
2316         /*
2317          * Perform bandwidth limiting.
2318          */
2319 #ifdef ICMP_BANDLIM
2320         if (badport_bandlim(rstreason) < 0)
2321                 goto drop;
2322 #endif
2323
2324 #ifdef TCPDEBUG
2325         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2326                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2327                           &tcp_savetcp, 0);
2328 #endif
2329         if (thflags & TH_ACK)
2330                 /* mtod() below is safe as long as hdr dropping is delayed */
2331                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2332                             TH_RST);
2333         else {
2334                 if (thflags & TH_SYN)
2335                         tlen++;
2336                 /* mtod() below is safe as long as hdr dropping is delayed */
2337                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2338                             (tcp_seq)0, TH_RST|TH_ACK);
2339         }
2340         return;
2341
2342 drop:
2343         /*
2344          * Drop space held by incoming segment and return.
2345          */
2346 #ifdef TCPDEBUG
2347         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2348                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2349                           &tcp_savetcp, 0);
2350 #endif
2351         m_freem(m);
2352         return;
2353 }
2354
2355 /*
2356  * Parse TCP options and place in tcpopt.
2357  */
2358 static void
2359 tcp_dooptions(to, cp, cnt, is_syn)
2360         struct tcpopt *to;
2361         u_char *cp;
2362         int cnt;
2363 {
2364         int opt, optlen;
2365
2366         to->to_flags = 0;
2367         for (; cnt > 0; cnt -= optlen, cp += optlen) {
2368                 opt = cp[0];
2369                 if (opt == TCPOPT_EOL)
2370                         break;
2371                 if (opt == TCPOPT_NOP)
2372                         optlen = 1;
2373                 else {
2374                         if (cnt < 2)
2375                                 break;
2376                         optlen = cp[1];
2377                         if (optlen < 2 || optlen > cnt)
2378                                 break;
2379                 }
2380                 switch (opt) {
2381                 case TCPOPT_MAXSEG:
2382                         if (optlen != TCPOLEN_MAXSEG)
2383                                 continue;
2384                         if (!is_syn)
2385                                 continue;
2386                         to->to_flags |= TOF_MSS;
2387                         bcopy((char *)cp + 2,
2388                             (char *)&to->to_mss, sizeof(to->to_mss));
2389                         to->to_mss = ntohs(to->to_mss);
2390                         break;
2391                 case TCPOPT_WINDOW:
2392                         if (optlen != TCPOLEN_WINDOW)
2393                                 continue;
2394                         if (! is_syn)
2395                                 continue;
2396                         to->to_flags |= TOF_SCALE;
2397                         to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2398                         break;
2399                 case TCPOPT_TIMESTAMP:
2400                         if (optlen != TCPOLEN_TIMESTAMP)
2401                                 continue;
2402                         to->to_flags |= TOF_TS;
2403                         bcopy((char *)cp + 2,
2404                             (char *)&to->to_tsval, sizeof(to->to_tsval));
2405                         to->to_tsval = ntohl(to->to_tsval);
2406                         bcopy((char *)cp + 6,
2407                             (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2408                         to->to_tsecr = ntohl(to->to_tsecr);
2409                         break;
2410                 case TCPOPT_CC:
2411                         if (optlen != TCPOLEN_CC)
2412                                 continue;
2413                         to->to_flags |= TOF_CC;
2414                         bcopy((char *)cp + 2,
2415                             (char *)&to->to_cc, sizeof(to->to_cc));
2416                         to->to_cc = ntohl(to->to_cc);
2417                         break;
2418                 case TCPOPT_CCNEW:
2419                         if (optlen != TCPOLEN_CC)
2420                                 continue;
2421                         if (!is_syn)
2422                                 continue;
2423                         to->to_flags |= TOF_CCNEW;
2424                         bcopy((char *)cp + 2,
2425                             (char *)&to->to_cc, sizeof(to->to_cc));
2426                         to->to_cc = ntohl(to->to_cc);
2427                         break;
2428                 case TCPOPT_CCECHO:
2429                         if (optlen != TCPOLEN_CC)
2430                                 continue;
2431                         if (!is_syn)
2432                                 continue;
2433                         to->to_flags |= TOF_CCECHO;
2434                         bcopy((char *)cp + 2,
2435                             (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2436                         to->to_ccecho = ntohl(to->to_ccecho);
2437                         break;
2438                 default:
2439                         continue;
2440                 }
2441         }
2442 }
2443
2444 /*
2445  * Pull out of band byte out of a segment so
2446  * it doesn't appear in the user's data queue.
2447  * It is still reflected in the segment length for
2448  * sequencing purposes.
2449  */
2450 static void
2451 tcp_pulloutofband(so, th, m, off)
2452         struct socket *so;
2453         struct tcphdr *th;
2454         struct mbuf *m;
2455         int off;                /* delayed to be droped hdrlen */
2456 {
2457         int cnt = off + th->th_urp - 1;
2458
2459         while (cnt >= 0) {
2460                 if (m->m_len > cnt) {
2461                         char *cp = mtod(m, caddr_t) + cnt;
2462                         struct tcpcb *tp = sototcpcb(so);
2463
2464                         tp->t_iobc = *cp;
2465                         tp->t_oobflags |= TCPOOB_HAVEDATA;
2466                         bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2467                         m->m_len--;
2468                         if (m->m_flags & M_PKTHDR)
2469                                 m->m_pkthdr.len--;
2470                         return;
2471                 }
2472                 cnt -= m->m_len;
2473                 m = m->m_next;
2474                 if (m == 0)
2475                         break;
2476         }
2477         panic("tcp_pulloutofband");
2478 }
2479
2480 /*
2481  * Collect new round-trip time estimate
2482  * and update averages and current timeout.
2483  */
2484 static void
2485 tcp_xmit_timer(tp, rtt)
2486         struct tcpcb *tp;
2487         int rtt;
2488 {
2489         int delta;
2490
2491         tcpstat.tcps_rttupdated++;
2492         tp->t_rttupdated++;
2493         if (tp->t_srtt != 0) {
2494                 /*
2495                  * srtt is stored as fixed point with 5 bits after the
2496                  * binary point (i.e., scaled by 8).  The following magic
2497                  * is equivalent to the smoothing algorithm in rfc793 with
2498                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2499                  * point).  Adjust rtt to origin 0.
2500                  */
2501                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2502                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2503
2504                 if ((tp->t_srtt += delta) <= 0)
2505                         tp->t_srtt = 1;
2506
2507                 /*
2508                  * We accumulate a smoothed rtt variance (actually, a
2509                  * smoothed mean difference), then set the retransmit
2510                  * timer to smoothed rtt + 4 times the smoothed variance.
2511                  * rttvar is stored as fixed point with 4 bits after the
2512                  * binary point (scaled by 16).  The following is
2513                  * equivalent to rfc793 smoothing with an alpha of .75
2514                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
2515                  * rfc793's wired-in beta.
2516                  */
2517                 if (delta < 0)
2518                         delta = -delta;
2519                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2520                 if ((tp->t_rttvar += delta) <= 0)
2521                         tp->t_rttvar = 1;
2522                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2523                         tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2524         } else {
2525                 /*
2526                  * No rtt measurement yet - use the unsmoothed rtt.
2527                  * Set the variance to half the rtt (so our first
2528                  * retransmit happens at 3*rtt).
2529                  */
2530                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2531                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2532                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2533         }
2534         tp->t_rtttime = 0;
2535         tp->t_rxtshift = 0;
2536
2537         /*
2538          * the retransmit should happen at rtt + 4 * rttvar.
2539          * Because of the way we do the smoothing, srtt and rttvar
2540          * will each average +1/2 tick of bias.  When we compute
2541          * the retransmit timer, we want 1/2 tick of rounding and
2542          * 1 extra tick because of +-1/2 tick uncertainty in the
2543          * firing of the timer.  The bias will give us exactly the
2544          * 1.5 tick we need.  But, because the bias is
2545          * statistical, we have to test that we don't drop below
2546          * the minimum feasible timer (which is 2 ticks).
2547          */
2548         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2549                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2550
2551         /*
2552          * We received an ack for a packet that wasn't retransmitted;
2553          * it is probably safe to discard any error indications we've
2554          * received recently.  This isn't quite right, but close enough
2555          * for now (a route might have failed after we sent a segment,
2556          * and the return path might not be symmetrical).
2557          */
2558         tp->t_softerror = 0;
2559 }
2560
2561 /*
2562  * Determine a reasonable value for maxseg size.
2563  * If the route is known, check route for mtu.
2564  * If none, use an mss that can be handled on the outgoing
2565  * interface without forcing IP to fragment; if bigger than
2566  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2567  * to utilize large mbufs.  If no route is found, route has no mtu,
2568  * or the destination isn't local, use a default, hopefully conservative
2569  * size (usually 512 or the default IP max size, but no more than the mtu
2570  * of the interface), as we can't discover anything about intervening
2571  * gateways or networks.  We also initialize the congestion/slow start
2572  * window to be a single segment if the destination isn't local.
2573  * While looking at the routing entry, we also initialize other path-dependent
2574  * parameters from pre-set or cached values in the routing entry.
2575  *
2576  * Also take into account the space needed for options that we
2577  * send regularly.  Make maxseg shorter by that amount to assure
2578  * that we can send maxseg amount of data even when the options
2579  * are present.  Store the upper limit of the length of options plus
2580  * data in maxopd.
2581  *
2582  * NOTE that this routine is only called when we process an incoming
2583  * segment, for outgoing segments only tcp_mssopt is called.
2584  *
2585  * In case of T/TCP, we call this routine during implicit connection
2586  * setup as well (offer = -1), to initialize maxseg from the cached
2587  * MSS of our peer.
2588  */
2589 void
2590 tcp_mss(tp, offer)
2591         struct tcpcb *tp;
2592         int offer;
2593 {
2594         struct rtentry *rt;
2595         struct ifnet *ifp;
2596         int rtt, mss;
2597         u_long bufsize;
2598         struct inpcb *inp = tp->t_inpcb;
2599         struct socket *so;
2600         struct rmxp_tao *taop;
2601         int origoffer = offer;
2602 #ifdef INET6
2603         int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2604         size_t min_protoh = isipv6 ?
2605                             sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2606                             sizeof(struct tcpiphdr);
2607 #else
2608         const int isipv6 = 0;
2609         const size_t min_protoh = sizeof(struct tcpiphdr);
2610 #endif
2611
2612         if (isipv6)
2613                 rt = tcp_rtlookup6(&inp->inp_inc);
2614         else
2615                 rt = tcp_rtlookup(&inp->inp_inc);
2616         if (rt == NULL) {
2617                 tp->t_maxopd = tp->t_maxseg =
2618                                 isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2619                 return;
2620         }
2621         ifp = rt->rt_ifp;
2622         so = inp->inp_socket;
2623
2624         taop = rmx_taop(rt->rt_rmx);
2625         /*
2626          * Offer == -1 means that we didn't receive SYN yet,
2627          * use cached value in that case;
2628          */
2629         if (offer == -1)
2630                 offer = taop->tao_mssopt;
2631         /*
2632          * Offer == 0 means that there was no MSS on the SYN segment,
2633          * in this case we use tcp_mssdflt.
2634          */
2635         if (offer == 0)
2636                 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2637         else
2638                 /*
2639                  * Sanity check: make sure that maxopd will be large
2640                  * enough to allow some data on segments even is the
2641                  * all the option space is used (40bytes).  Otherwise
2642                  * funny things may happen in tcp_output.
2643                  */
2644                 offer = max(offer, 64);
2645         taop->tao_mssopt = offer;
2646
2647         /*
2648          * While we're here, check if there's an initial rtt
2649          * or rttvar.  Convert from the route-table units
2650          * to scaled multiples of the slow timeout timer.
2651          */
2652         if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2653                 /*
2654                  * XXX the lock bit for RTT indicates that the value
2655                  * is also a minimum value; this is subject to time.
2656                  */
2657                 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2658                         tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2659                 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2660                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2661                 tcpstat.tcps_usedrtt++;
2662                 if (rt->rt_rmx.rmx_rttvar) {
2663                         tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2664                             (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2665                         tcpstat.tcps_usedrttvar++;
2666                 } else {
2667                         /* default variation is +- 1 rtt */
2668                         tp->t_rttvar =
2669                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2670                 }
2671                 TCPT_RANGESET(tp->t_rxtcur,
2672                               ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2673                               tp->t_rttmin, TCPTV_REXMTMAX);
2674         }
2675         /*
2676          * if there's an mtu associated with the route, use it
2677          * else, use the link mtu.
2678          */
2679         if (rt->rt_rmx.rmx_mtu)
2680                 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2681         else {
2682                 if (isipv6) {
2683                         mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2684                                 min_protoh;
2685                         if (!in6_localaddr(&inp->in6p_faddr))
2686                                 mss = min(mss, tcp_v6mssdflt);
2687                 } else {
2688                         mss = ifp->if_mtu - min_protoh;
2689                         if (!in_localaddr(inp->inp_faddr))
2690                                 mss = min(mss, tcp_mssdflt);
2691                 }
2692         }
2693         mss = min(mss, offer);
2694         /*
2695          * maxopd stores the maximum length of data AND options
2696          * in a segment; maxseg is the amount of data in a normal
2697          * segment.  We need to store this value (maxopd) apart
2698          * from maxseg, because now every segment carries options
2699          * and thus we normally have somewhat less data in segments.
2700          */
2701         tp->t_maxopd = mss;
2702
2703         /*
2704          * In case of T/TCP, origoffer==-1 indicates, that no segments
2705          * were received yet.  In this case we just guess, otherwise
2706          * we do the same as before T/TCP.
2707          */
2708         if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2709             (origoffer == -1 ||
2710              (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2711                 mss -= TCPOLEN_TSTAMP_APPA;
2712         if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2713             (origoffer == -1 ||
2714              (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2715                 mss -= TCPOLEN_CC_APPA;
2716
2717 #if     (MCLBYTES & (MCLBYTES - 1)) == 0
2718                 if (mss > MCLBYTES)
2719                         mss &= ~(MCLBYTES-1);
2720 #else
2721                 if (mss > MCLBYTES)
2722                         mss = mss / MCLBYTES * MCLBYTES;
2723 #endif
2724         /*
2725          * If there's a pipesize, change the socket buffer
2726          * to that size.  Make the socket buffers an integral
2727          * number of mss units; if the mss is larger than
2728          * the socket buffer, decrease the mss.
2729          */
2730 #ifdef RTV_SPIPE
2731         if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2732 #endif
2733                 bufsize = so->so_snd.sb_hiwat;
2734         if (bufsize < mss)
2735                 mss = bufsize;
2736         else {
2737                 bufsize = roundup(bufsize, mss);
2738                 if (bufsize > sb_max)
2739                         bufsize = sb_max;
2740                 if (bufsize > so->so_snd.sb_hiwat)
2741                         (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2742         }
2743         tp->t_maxseg = mss;
2744
2745 #ifdef RTV_RPIPE
2746         if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2747 #endif
2748                 bufsize = so->so_rcv.sb_hiwat;
2749         if (bufsize > mss) {
2750                 bufsize = roundup(bufsize, mss);
2751                 if (bufsize > sb_max)
2752                         bufsize = sb_max;
2753                 if (bufsize > so->so_rcv.sb_hiwat)
2754                         (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2755         }
2756
2757         /*
2758          * Set the slow-start flight size depending on whether this
2759          * is a local network or not.
2760          */
2761         if (tcp_do_rfc3390)
2762                 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2763         else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2764                  (!isipv6 && in_localaddr(inp->inp_faddr)))
2765                 tp->snd_cwnd = mss * ss_fltsz_local;
2766         else
2767                 tp->snd_cwnd = mss * ss_fltsz;
2768
2769         if (rt->rt_rmx.rmx_ssthresh) {
2770                 /*
2771                  * There's some sort of gateway or interface
2772                  * buffer limit on the path.  Use this to set
2773                  * the slow start threshhold, but set the
2774                  * threshold to no less than 2*mss.
2775                  */
2776                 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2777                 tcpstat.tcps_usedssthresh++;
2778         }
2779 }
2780
2781 /*
2782  * Determine the MSS option to send on an outgoing SYN.
2783  */
2784 int
2785 tcp_mssopt(tp)
2786         struct tcpcb *tp;
2787 {
2788         struct rtentry *rt;
2789 #ifdef INET6
2790         int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2791         int min_protoh = isipv6 ?
2792                              sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2793                              sizeof(struct tcpiphdr);
2794 #else
2795         const int isipv6 = 0;
2796         const size_t min_protoh = sizeof(struct tcpiphdr);
2797 #endif
2798
2799         if (isipv6)
2800                 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2801         else
2802                 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2803         if (rt == NULL)
2804                 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2805
2806         return (rt->rt_ifp->if_mtu - min_protoh);
2807 }
2808
2809
2810 /*
2811  * When a partial ack arrives, force the retransmission of the
2812  * next unacknowledged segment.  Do not clear tp->t_dupacks.
2813  * By setting snd_nxt to ti_ack, this forces retransmission timer to
2814  * be started again.
2815  */
2816 static void
2817 tcp_newreno_partial_ack(tp, th)
2818         struct tcpcb *tp;
2819         struct tcphdr *th;
2820 {
2821         tcp_seq onxt = tp->snd_nxt;
2822         u_long  ocwnd = tp->snd_cwnd;
2823
2824         callout_stop(tp->tt_rexmt);
2825         tp->t_rtttime = 0;
2826         tp->snd_nxt = th->th_ack;
2827         /*
2828          * Set snd_cwnd to one segment beyond acknowledged offset
2829          * (tp->snd_una has not yet been updated when this function is called.)
2830          */
2831         tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2832         tp->t_flags |= TF_ACKNOW;
2833         (void) tcp_output(tp);
2834         tp->snd_cwnd = ocwnd;
2835         if (SEQ_GT(onxt, tp->snd_nxt))
2836                 tp->snd_nxt = onxt;
2837         /*
2838          * Partial window deflation.  Relies on fact that tp->snd_una
2839          * not updated yet.
2840          */
2841         tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2842 }