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