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