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