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