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