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