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