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