]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/netinet/tcp_input.c
MFC r305389:
[FreeBSD/stable/10.git] / sys / netinet / tcp_input.c
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3  *      The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 2007-2008,2010
5  *      Swinburne University of Technology, Melbourne, Australia.
6  * Copyright (c) 2009-2010 Lawrence Stewart <lstewart@freebsd.org>
7  * Copyright (c) 2010 The FreeBSD Foundation
8  * Copyright (c) 2010-2011 Juniper Networks, Inc.
9  * All rights reserved.
10  *
11  * Portions of this software were developed at the Centre for Advanced Internet
12  * Architectures, Swinburne University of Technology, by Lawrence Stewart,
13  * James Healy and David Hayes, made possible in part by a grant from the Cisco
14  * University Research Program Fund at Community Foundation Silicon Valley.
15  *
16  * Portions of this software were developed at the Centre for Advanced
17  * Internet Architectures, Swinburne University of Technology, Melbourne,
18  * Australia by David Hayes under sponsorship from the FreeBSD Foundation.
19  *
20  * Portions of this software were developed by Robert N. M. Watson under
21  * contract to Juniper Networks, Inc.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 4. Neither the name of the University nor the names of its contributors
32  *    may be used to endorse or promote products derived from this software
33  *    without specific prior written permission.
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
36  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
39  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
40  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
41  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
42  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
43  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
44  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
45  * SUCH DAMAGE.
46  *
47  *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
48  */
49
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
52
53 #include "opt_ipfw.h"           /* for ipfw_fwd */
54 #include "opt_inet.h"
55 #include "opt_inet6.h"
56 #include "opt_ipsec.h"
57 #include "opt_kdtrace.h"
58 #include "opt_tcpdebug.h"
59
60 #include <sys/param.h>
61 #include <sys/kernel.h>
62 #include <sys/hhook.h>
63 #include <sys/malloc.h>
64 #include <sys/mbuf.h>
65 #include <sys/proc.h>           /* for proc0 declaration */
66 #include <sys/protosw.h>
67 #include <sys/sdt.h>
68 #include <sys/signalvar.h>
69 #include <sys/socket.h>
70 #include <sys/socketvar.h>
71 #include <sys/sysctl.h>
72 #include <sys/syslog.h>
73 #include <sys/systm.h>
74
75 #include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
76
77 #include <vm/uma.h>
78
79 #include <net/if.h>
80 #include <net/route.h>
81 #include <net/vnet.h>
82
83 #define TCPSTATES               /* for logging */
84
85 #include <netinet/cc.h>
86 #include <netinet/in.h>
87 #include <netinet/in_kdtrace.h>
88 #include <netinet/in_pcb.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/in_var.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h>    /* required for icmp_var.h */
93 #include <netinet/icmp_var.h>   /* for ICMP_BANDLIM */
94 #include <netinet/ip_var.h>
95 #include <netinet/ip_options.h>
96 #include <netinet/ip6.h>
97 #include <netinet/icmp6.h>
98 #include <netinet6/in6_pcb.h>
99 #include <netinet6/ip6_var.h>
100 #include <netinet6/nd6.h>
101 #ifdef TCP_RFC7413
102 #include <netinet/tcp_fastopen.h>
103 #endif
104 #include <netinet/tcp_fsm.h>
105 #include <netinet/tcp_seq.h>
106 #include <netinet/tcp_timer.h>
107 #include <netinet/tcp_var.h>
108 #include <netinet6/tcp6_var.h>
109 #include <netinet/tcpip.h>
110 #include <netinet/tcp_syncache.h>
111 #ifdef TCPDEBUG
112 #include <netinet/tcp_debug.h>
113 #endif /* TCPDEBUG */
114 #ifdef TCP_OFFLOAD
115 #include <netinet/tcp_offload.h>
116 #endif
117
118 #ifdef IPSEC
119 #include <netipsec/ipsec.h>
120 #include <netipsec/ipsec6.h>
121 #endif /*IPSEC*/
122
123 #include <machine/in_cksum.h>
124
125 #include <security/mac/mac_framework.h>
126
127 const int tcprexmtthresh = 3;
128
129 int tcp_log_in_vain = 0;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
131     &tcp_log_in_vain, 0,
132     "Log all incoming TCP segments to closed ports");
133
134 VNET_DEFINE(int, blackhole) = 0;
135 #define V_blackhole             VNET(blackhole)
136 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
137     &VNET_NAME(blackhole), 0,
138     "Do not send RST on segments to closed ports");
139
140 VNET_DEFINE(int, tcp_delack_enabled) = 1;
141 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
142     &VNET_NAME(tcp_delack_enabled), 0,
143     "Delay ACK to try and piggyback it onto a data packet");
144
145 VNET_DEFINE(int, drop_synfin) = 0;
146 #define V_drop_synfin           VNET(drop_synfin)
147 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
148     &VNET_NAME(drop_synfin), 0,
149     "Drop TCP packets with SYN+FIN set");
150
151 VNET_DEFINE(int, tcp_do_rfc6675_pipe) = 0;
152 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_pipe, CTLFLAG_VNET | CTLFLAG_RW,
153     &VNET_NAME(tcp_do_rfc6675_pipe), 0,
154     "Use calculated pipe/in-flight bytes per RFC 6675");
155
156 VNET_DEFINE(int, tcp_do_rfc3042) = 1;
157 #define V_tcp_do_rfc3042        VNET(tcp_do_rfc3042)
158 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
159     &VNET_NAME(tcp_do_rfc3042), 0,
160     "Enable RFC 3042 (Limited Transmit)");
161
162 VNET_DEFINE(int, tcp_do_rfc3390) = 1;
163 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
164     &VNET_NAME(tcp_do_rfc3390), 0,
165     "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
166
167 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, experimental, CTLFLAG_RW, 0,
168     "Experimental TCP extensions");
169
170 VNET_DEFINE(int, tcp_do_initcwnd10) = 1;
171 SYSCTL_VNET_INT(_net_inet_tcp_experimental, OID_AUTO, initcwnd10, CTLFLAG_RW,
172     &VNET_NAME(tcp_do_initcwnd10), 0,
173     "Enable RFC 6928 (Increasing initial CWND to 10)");
174
175 VNET_DEFINE(int, tcp_do_rfc3465) = 1;
176 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
177     &VNET_NAME(tcp_do_rfc3465), 0,
178     "Enable RFC 3465 (Appropriate Byte Counting)");
179
180 VNET_DEFINE(int, tcp_abc_l_var) = 2;
181 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
182     &VNET_NAME(tcp_abc_l_var), 2,
183     "Cap the max cwnd increment during slow-start to this number of segments");
184
185 static SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
186
187 VNET_DEFINE(int, tcp_do_ecn) = 2;
188 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
189     &VNET_NAME(tcp_do_ecn), 0,
190     "TCP ECN support");
191
192 VNET_DEFINE(int, tcp_ecn_maxretries) = 1;
193 SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
194     &VNET_NAME(tcp_ecn_maxretries), 0,
195     "Max retries before giving up on ECN");
196
197 VNET_DEFINE(int, tcp_insecure_rst) = 0;
198 #define V_tcp_insecure_rst      VNET(tcp_insecure_rst)
199 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
200     &VNET_NAME(tcp_insecure_rst), 0,
201     "Follow the old (insecure) criteria for accepting RST packets");
202
203 VNET_DEFINE(int, tcp_recvspace) = 1024*64;
204 #define V_tcp_recvspace VNET(tcp_recvspace)
205 SYSCTL_VNET_INT(_net_inet_tcp, TCPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
206     &VNET_NAME(tcp_recvspace), 0, "Initial receive socket buffer size");
207
208 VNET_DEFINE(int, tcp_do_autorcvbuf) = 1;
209 #define V_tcp_do_autorcvbuf     VNET(tcp_do_autorcvbuf)
210 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
211     &VNET_NAME(tcp_do_autorcvbuf), 0,
212     "Enable automatic receive buffer sizing");
213
214 VNET_DEFINE(int, tcp_autorcvbuf_inc) = 16*1024;
215 #define V_tcp_autorcvbuf_inc    VNET(tcp_autorcvbuf_inc)
216 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
217     &VNET_NAME(tcp_autorcvbuf_inc), 0,
218     "Incrementor step size of automatic receive buffer");
219
220 VNET_DEFINE(int, tcp_autorcvbuf_max) = 2*1024*1024;
221 #define V_tcp_autorcvbuf_max    VNET(tcp_autorcvbuf_max)
222 SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
223     &VNET_NAME(tcp_autorcvbuf_max), 0,
224     "Max size of automatic receive buffer");
225
226 VNET_DEFINE(struct inpcbhead, tcb);
227 #define tcb6    tcb  /* for KAME src sync over BSD*'s */
228 VNET_DEFINE(struct inpcbinfo, tcbinfo);
229
230 static void      tcp_dooptions(struct tcpopt *, u_char *, int, int);
231 static void      tcp_do_segment(struct mbuf *, struct tcphdr *,
232                      struct socket *, struct tcpcb *, int, int, uint8_t,
233                      int);
234 static void      tcp_dropwithreset(struct mbuf *, struct tcphdr *,
235                      struct tcpcb *, int, int);
236 static void      tcp_pulloutofband(struct socket *,
237                      struct tcphdr *, struct mbuf *, int);
238 static void      tcp_xmit_timer(struct tcpcb *, int);
239 static void      tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
240 static void inline      cc_ack_received(struct tcpcb *tp, struct tcphdr *th,
241                             uint16_t type);
242 static void inline      cc_conn_init(struct tcpcb *tp);
243 static void inline      cc_post_recovery(struct tcpcb *tp, struct tcphdr *th);
244 static void inline      hhook_run_tcp_est_in(struct tcpcb *tp,
245                             struct tcphdr *th, struct tcpopt *to);
246
247 /*
248  * TCP statistics are stored in an "array" of counter(9)s.
249  */
250 VNET_PCPUSTAT_DEFINE(struct tcpstat, tcpstat);
251 VNET_PCPUSTAT_SYSINIT(tcpstat);
252 SYSCTL_VNET_PCPUSTAT(_net_inet_tcp, TCPCTL_STATS, stats, struct tcpstat,
253     tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
254
255 #ifdef VIMAGE
256 VNET_PCPUSTAT_SYSUNINIT(tcpstat);
257 #endif /* VIMAGE */
258 /*
259  * Kernel module interface for updating tcpstat.  The argument is an index
260  * into tcpstat treated as an array.
261  */
262 void
263 kmod_tcpstat_inc(int statnum)
264 {
265
266         counter_u64_add(VNET(tcpstat)[statnum], 1);
267 }
268
269 /*
270  * Wrapper for the TCP established input helper hook.
271  */
272 static void inline
273 hhook_run_tcp_est_in(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
274 {
275         struct tcp_hhook_data hhook_data;
276
277         if (V_tcp_hhh[HHOOK_TCP_EST_IN]->hhh_nhooks > 0) {
278                 hhook_data.tp = tp;
279                 hhook_data.th = th;
280                 hhook_data.to = to;
281
282                 hhook_run_hooks(V_tcp_hhh[HHOOK_TCP_EST_IN], &hhook_data,
283                     tp->osd);
284         }
285 }
286
287 /*
288  * CC wrapper hook functions
289  */
290 static void inline
291 cc_ack_received(struct tcpcb *tp, struct tcphdr *th, uint16_t type)
292 {
293         INP_WLOCK_ASSERT(tp->t_inpcb);
294
295         tp->ccv->bytes_this_ack = BYTES_THIS_ACK(tp, th);
296         if (tp->snd_cwnd <= tp->snd_wnd)
297                 tp->ccv->flags |= CCF_CWND_LIMITED;
298         else
299                 tp->ccv->flags &= ~CCF_CWND_LIMITED;
300
301         if (type == CC_ACK) {
302                 if (tp->snd_cwnd > tp->snd_ssthresh) {
303                         tp->t_bytes_acked += min(tp->ccv->bytes_this_ack,
304                              V_tcp_abc_l_var * tp->t_maxseg);
305                         if (tp->t_bytes_acked >= tp->snd_cwnd) {
306                                 tp->t_bytes_acked -= tp->snd_cwnd;
307                                 tp->ccv->flags |= CCF_ABC_SENTAWND;
308                         }
309                 } else {
310                                 tp->ccv->flags &= ~CCF_ABC_SENTAWND;
311                                 tp->t_bytes_acked = 0;
312                 }
313         }
314
315         if (CC_ALGO(tp)->ack_received != NULL) {
316                 /* XXXLAS: Find a way to live without this */
317                 tp->ccv->curack = th->th_ack;
318                 CC_ALGO(tp)->ack_received(tp->ccv, type);
319         }
320 }
321
322 static void inline
323 cc_conn_init(struct tcpcb *tp)
324 {
325         struct hc_metrics_lite metrics;
326         struct inpcb *inp = tp->t_inpcb;
327         int rtt;
328
329         INP_WLOCK_ASSERT(tp->t_inpcb);
330
331         tcp_hc_get(&inp->inp_inc, &metrics);
332
333         if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
334                 tp->t_srtt = rtt;
335                 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
336                 TCPSTAT_INC(tcps_usedrtt);
337                 if (metrics.rmx_rttvar) {
338                         tp->t_rttvar = metrics.rmx_rttvar;
339                         TCPSTAT_INC(tcps_usedrttvar);
340                 } else {
341                         /* default variation is +- 1 rtt */
342                         tp->t_rttvar =
343                             tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
344                 }
345                 TCPT_RANGESET(tp->t_rxtcur,
346                     ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
347                     tp->t_rttmin, TCPTV_REXMTMAX);
348         }
349         if (metrics.rmx_ssthresh) {
350                 /*
351                  * There's some sort of gateway or interface
352                  * buffer limit on the path.  Use this to set
353                  * the slow start threshhold, but set the
354                  * threshold to no less than 2*mss.
355                  */
356                 tp->snd_ssthresh = max(2 * tp->t_maxseg, metrics.rmx_ssthresh);
357                 TCPSTAT_INC(tcps_usedssthresh);
358         }
359
360         /*
361          * Set the initial slow-start flight size.
362          *
363          * RFC5681 Section 3.1 specifies the default conservative values.
364          * RFC3390 specifies slightly more aggressive values.
365          * RFC6928 increases it to ten segments.
366          *
367          * If a SYN or SYN/ACK was lost and retransmitted, we have to
368          * reduce the initial CWND to one segment as congestion is likely
369          * requiring us to be cautious.
370          */
371         if (tp->snd_cwnd == 1)
372                 tp->snd_cwnd = tp->t_maxseg;            /* SYN(-ACK) lost */
373         else if (V_tcp_do_initcwnd10)
374                 tp->snd_cwnd = min(10 * tp->t_maxseg,
375                     max(2 * tp->t_maxseg, 14600));
376         else if (V_tcp_do_rfc3390)
377                 tp->snd_cwnd = min(4 * tp->t_maxseg,
378                     max(2 * tp->t_maxseg, 4380));
379         else {
380                 /* Per RFC5681 Section 3.1 */
381                 if (tp->t_maxseg > 2190)
382                         tp->snd_cwnd = 2 * tp->t_maxseg;
383                 else if (tp->t_maxseg > 1095)
384                         tp->snd_cwnd = 3 * tp->t_maxseg;
385                 else
386                         tp->snd_cwnd = 4 * tp->t_maxseg;
387         }
388
389         if (CC_ALGO(tp)->conn_init != NULL)
390                 CC_ALGO(tp)->conn_init(tp->ccv);
391 }
392
393 void inline
394 cc_cong_signal(struct tcpcb *tp, struct tcphdr *th, uint32_t type)
395 {
396         INP_WLOCK_ASSERT(tp->t_inpcb);
397
398         switch(type) {
399         case CC_NDUPACK:
400                 if (!IN_FASTRECOVERY(tp->t_flags)) {
401                         tp->snd_recover = tp->snd_max;
402                         if (tp->t_flags & TF_ECN_PERMIT)
403                                 tp->t_flags |= TF_ECN_SND_CWR;
404                 }
405                 break;
406         case CC_ECN:
407                 if (!IN_CONGRECOVERY(tp->t_flags)) {
408                         TCPSTAT_INC(tcps_ecn_rcwnd);
409                         tp->snd_recover = tp->snd_max;
410                         if (tp->t_flags & TF_ECN_PERMIT)
411                                 tp->t_flags |= TF_ECN_SND_CWR;
412                 }
413                 break;
414         case CC_RTO:
415                 tp->t_dupacks = 0;
416                 tp->t_bytes_acked = 0;
417                 EXIT_RECOVERY(tp->t_flags);
418                 tp->snd_ssthresh = max(2, min(tp->snd_wnd, tp->snd_cwnd) / 2 /
419                     tp->t_maxseg) * tp->t_maxseg;
420                 tp->snd_cwnd = tp->t_maxseg;
421                 break;
422         case CC_RTO_ERR:
423                 TCPSTAT_INC(tcps_sndrexmitbad);
424                 /* RTO was unnecessary, so reset everything. */
425                 tp->snd_cwnd = tp->snd_cwnd_prev;
426                 tp->snd_ssthresh = tp->snd_ssthresh_prev;
427                 tp->snd_recover = tp->snd_recover_prev;
428                 if (tp->t_flags & TF_WASFRECOVERY)
429                         ENTER_FASTRECOVERY(tp->t_flags);
430                 if (tp->t_flags & TF_WASCRECOVERY)
431                         ENTER_CONGRECOVERY(tp->t_flags);
432                 tp->snd_nxt = tp->snd_max;
433                 tp->t_flags &= ~TF_PREVVALID;
434                 tp->t_badrxtwin = 0;
435                 break;
436         }
437
438         if (CC_ALGO(tp)->cong_signal != NULL) {
439                 if (th != NULL)
440                         tp->ccv->curack = th->th_ack;
441                 CC_ALGO(tp)->cong_signal(tp->ccv, type);
442         }
443 }
444
445 static void inline
446 cc_post_recovery(struct tcpcb *tp, struct tcphdr *th)
447 {
448         INP_WLOCK_ASSERT(tp->t_inpcb);
449
450         /* XXXLAS: KASSERT that we're in recovery? */
451
452         if (CC_ALGO(tp)->post_recovery != NULL) {
453                 tp->ccv->curack = th->th_ack;
454                 CC_ALGO(tp)->post_recovery(tp->ccv);
455         }
456         /* XXXLAS: EXIT_RECOVERY ? */
457         tp->t_bytes_acked = 0;
458 }
459
460 #ifdef TCP_SIGNATURE
461 static inline int
462 tcp_signature_verify_input(struct mbuf *m, int off0, int tlen, int optlen,
463     struct tcpopt *to, struct tcphdr *th, u_int tcpbflag)
464 {
465         int ret;
466
467         tcp_fields_to_net(th);
468         ret = tcp_signature_verify(m, off0, tlen, optlen, to, th, tcpbflag);
469         tcp_fields_to_host(th);
470         return (ret);
471 }
472 #endif
473
474 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
475 #ifdef INET6
476 #define ND6_HINT(tp) \
477 do { \
478         if ((tp) && (tp)->t_inpcb && \
479             ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
480                 nd6_nud_hint(NULL, NULL, 0); \
481 } while (0)
482 #else
483 #define ND6_HINT(tp)
484 #endif
485
486 /*
487  * Indicate whether this ack should be delayed.  We can delay the ack if
488  *      - there is no delayed ack timer in progress and
489  *      - our last ack wasn't a 0-sized window.  We never want to delay
490  *        the ack that opens up a 0-sized window and
491  *              - delayed acks are enabled or
492  *              - this is a half-synchronized T/TCP connection.
493  *      - the segment size is not larger than the MSS and LRO wasn't used
494  *        for this segment.
495  */
496 #define DELAY_ACK(tp, tlen)                                             \
497         ((!tcp_timer_active(tp, TT_DELACK) &&                           \
498             (tp->t_flags & TF_RXWIN0SENT) == 0) &&                      \
499             (tlen <= tp->t_maxopd) &&                                   \
500             (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
501
502 /*
503  * TCP input handling is split into multiple parts:
504  *   tcp6_input is a thin wrapper around tcp_input for the extended
505  *      ip6_protox[] call format in ip6_input
506  *   tcp_input handles primary segment validation, inpcb lookup and
507  *      SYN processing on listen sockets
508  *   tcp_do_segment processes the ACK and text of the segment for
509  *      establishing, established and closing connections
510  */
511 #ifdef INET6
512 int
513 tcp6_input(struct mbuf **mp, int *offp, int proto)
514 {
515         struct mbuf *m = *mp;
516         struct in6_ifaddr *ia6;
517
518         IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
519
520         /*
521          * draft-itojun-ipv6-tcp-to-anycast
522          * better place to put this in?
523          */
524         ia6 = ip6_getdstifaddr(m);
525         if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
526                 struct ip6_hdr *ip6;
527
528                 ifa_free(&ia6->ia_ifa);
529                 ip6 = mtod(m, struct ip6_hdr *);
530                 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
531                             (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
532                 return IPPROTO_DONE;
533         }
534         if (ia6)
535                 ifa_free(&ia6->ia_ifa);
536
537         tcp_input(m, *offp);
538         return IPPROTO_DONE;
539 }
540 #endif /* INET6 */
541
542 void
543 tcp_input(struct mbuf *m, int off0)
544 {
545         struct tcphdr *th = NULL;
546         struct ip *ip = NULL;
547         struct inpcb *inp = NULL;
548         struct tcpcb *tp = NULL;
549         struct socket *so = NULL;
550         u_char *optp = NULL;
551         int optlen = 0;
552 #ifdef INET
553         int len;
554 #endif
555         int tlen = 0, off;
556         int drop_hdrlen;
557         int thflags;
558         int rstreason = 0;      /* For badport_bandlim accounting purposes */
559 #ifdef TCP_SIGNATURE
560         uint8_t sig_checked = 0;
561 #endif
562         uint8_t iptos = 0;
563         struct m_tag *fwd_tag = NULL;
564 #ifdef INET6
565         struct ip6_hdr *ip6 = NULL;
566         int isipv6;
567 #else
568         const void *ip6 = NULL;
569 #endif /* INET6 */
570         struct tcpopt to;               /* options in this segment */
571         char *s = NULL;                 /* address and port logging */
572         int ti_locked;
573 #define TI_UNLOCKED     1
574 #define TI_WLOCKED      2
575
576 #ifdef TCPDEBUG
577         /*
578          * The size of tcp_saveipgen must be the size of the max ip header,
579          * now IPv6.
580          */
581         u_char tcp_saveipgen[IP6_HDR_LEN];
582         struct tcphdr tcp_savetcp;
583         short ostate = 0;
584 #endif
585
586 #ifdef INET6
587         isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
588 #endif
589
590         to.to_flags = 0;
591         TCPSTAT_INC(tcps_rcvtotal);
592
593 #ifdef INET6
594         if (isipv6) {
595                 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
596
597                 if (m->m_len < (sizeof(*ip6) + sizeof(*th))) {
598                         m = m_pullup(m, sizeof(*ip6) + sizeof(*th));
599                         if (m == NULL) {
600                                 TCPSTAT_INC(tcps_rcvshort);
601                                 return;
602                         }
603                 }
604
605                 ip6 = mtod(m, struct ip6_hdr *);
606                 th = (struct tcphdr *)((caddr_t)ip6 + off0);
607                 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
608                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) {
609                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
610                                 th->th_sum = m->m_pkthdr.csum_data;
611                         else
612                                 th->th_sum = in6_cksum_pseudo(ip6, tlen,
613                                     IPPROTO_TCP, m->m_pkthdr.csum_data);
614                         th->th_sum ^= 0xffff;
615                 } else
616                         th->th_sum = in6_cksum(m, IPPROTO_TCP, off0, tlen);
617                 if (th->th_sum) {
618                         TCPSTAT_INC(tcps_rcvbadsum);
619                         goto drop;
620                 }
621
622                 /*
623                  * Be proactive about unspecified IPv6 address in source.
624                  * As we use all-zero to indicate unbounded/unconnected pcb,
625                  * unspecified IPv6 address can be used to confuse us.
626                  *
627                  * Note that packets with unspecified IPv6 destination is
628                  * already dropped in ip6_input.
629                  */
630                 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
631                         /* XXX stat */
632                         goto drop;
633                 }
634         }
635 #endif
636 #if defined(INET) && defined(INET6)
637         else
638 #endif
639 #ifdef INET
640         {
641                 /*
642                  * Get IP and TCP header together in first mbuf.
643                  * Note: IP leaves IP header in first mbuf.
644                  */
645                 if (off0 > sizeof (struct ip)) {
646                         ip_stripoptions(m);
647                         off0 = sizeof(struct ip);
648                 }
649                 if (m->m_len < sizeof (struct tcpiphdr)) {
650                         if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
651                             == NULL) {
652                                 TCPSTAT_INC(tcps_rcvshort);
653                                 return;
654                         }
655                 }
656                 ip = mtod(m, struct ip *);
657                 th = (struct tcphdr *)((caddr_t)ip + off0);
658                 tlen = ntohs(ip->ip_len) - off0;
659
660                 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
661                         if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
662                                 th->th_sum = m->m_pkthdr.csum_data;
663                         else
664                                 th->th_sum = in_pseudo(ip->ip_src.s_addr,
665                                     ip->ip_dst.s_addr,
666                                     htonl(m->m_pkthdr.csum_data + tlen +
667                                     IPPROTO_TCP));
668                         th->th_sum ^= 0xffff;
669                 } else {
670                         struct ipovly *ipov = (struct ipovly *)ip;
671
672                         /*
673                          * Checksum extended TCP header and data.
674                          */
675                         len = off0 + tlen;
676                         bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
677                         ipov->ih_len = htons(tlen);
678                         th->th_sum = in_cksum(m, len);
679                         /* Reset length for SDT probes. */
680                         ip->ip_len = htons(tlen + off0);
681                 }
682
683                 if (th->th_sum) {
684                         TCPSTAT_INC(tcps_rcvbadsum);
685                         goto drop;
686                 }
687                 /* Re-initialization for later version check */
688                 ip->ip_v = IPVERSION;
689         }
690 #endif /* INET */
691
692 #ifdef INET6
693         if (isipv6)
694                 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
695 #endif
696 #if defined(INET) && defined(INET6)
697         else
698 #endif
699 #ifdef INET
700                 iptos = ip->ip_tos;
701 #endif
702
703         /*
704          * Check that TCP offset makes sense,
705          * pull out TCP options and adjust length.              XXX
706          */
707         off = th->th_off << 2;
708         if (off < sizeof (struct tcphdr) || off > tlen) {
709                 TCPSTAT_INC(tcps_rcvbadoff);
710                 goto drop;
711         }
712         tlen -= off;    /* tlen is used instead of ti->ti_len */
713         if (off > sizeof (struct tcphdr)) {
714 #ifdef INET6
715                 if (isipv6) {
716                         IP6_EXTHDR_CHECK(m, off0, off, );
717                         ip6 = mtod(m, struct ip6_hdr *);
718                         th = (struct tcphdr *)((caddr_t)ip6 + off0);
719                 }
720 #endif
721 #if defined(INET) && defined(INET6)
722                 else
723 #endif
724 #ifdef INET
725                 {
726                         if (m->m_len < sizeof(struct ip) + off) {
727                                 if ((m = m_pullup(m, sizeof (struct ip) + off))
728                                     == NULL) {
729                                         TCPSTAT_INC(tcps_rcvshort);
730                                         return;
731                                 }
732                                 ip = mtod(m, struct ip *);
733                                 th = (struct tcphdr *)((caddr_t)ip + off0);
734                         }
735                 }
736 #endif
737                 optlen = off - sizeof (struct tcphdr);
738                 optp = (u_char *)(th + 1);
739         }
740         thflags = th->th_flags;
741
742         /*
743          * Convert TCP protocol specific fields to host format.
744          */
745         tcp_fields_to_host(th);
746
747         /*
748          * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
749          */
750         drop_hdrlen = off0 + off;
751
752         /*
753          * Locate pcb for segment; if we're likely to add or remove a
754          * connection then first acquire pcbinfo lock.  There are three cases
755          * where we might discover later we need a write lock despite the
756          * flags: ACKs moving a connection out of the syncache, ACKs for a
757          * connection in TIMEWAIT and SYNs not targeting a listening socket.
758          */
759         if ((thflags & (TH_FIN | TH_RST)) != 0) {
760                 INP_INFO_WLOCK(&V_tcbinfo);
761                 ti_locked = TI_WLOCKED;
762         } else
763                 ti_locked = TI_UNLOCKED;
764
765         /*
766          * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
767          */
768         if (
769 #ifdef INET6
770             (isipv6 && (m->m_flags & M_IP6_NEXTHOP))
771 #ifdef INET
772             || (!isipv6 && (m->m_flags & M_IP_NEXTHOP))
773 #endif
774 #endif
775 #if defined(INET) && !defined(INET6)
776             (m->m_flags & M_IP_NEXTHOP)
777 #endif
778             )
779                 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
780
781 findpcb:
782 #ifdef INVARIANTS
783         if (ti_locked == TI_WLOCKED) {
784                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
785         } else {
786                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
787         }
788 #endif
789 #ifdef INET6
790         if (isipv6 && fwd_tag != NULL) {
791                 struct sockaddr_in6 *next_hop6;
792
793                 next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
794                 /*
795                  * Transparently forwarded. Pretend to be the destination.
796                  * Already got one like this?
797                  */
798                 inp = in6_pcblookup_mbuf(&V_tcbinfo,
799                     &ip6->ip6_src, th->th_sport, &ip6->ip6_dst, th->th_dport,
800                     INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif, m);
801                 if (!inp) {
802                         /*
803                          * It's new.  Try to find the ambushing socket.
804                          * Because we've rewritten the destination address,
805                          * any hardware-generated hash is ignored.
806                          */
807                         inp = in6_pcblookup(&V_tcbinfo, &ip6->ip6_src,
808                             th->th_sport, &next_hop6->sin6_addr,
809                             next_hop6->sin6_port ? ntohs(next_hop6->sin6_port) :
810                             th->th_dport, INPLOOKUP_WILDCARD |
811                             INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
812                 }
813         } else if (isipv6) {
814                 inp = in6_pcblookup_mbuf(&V_tcbinfo, &ip6->ip6_src,
815                     th->th_sport, &ip6->ip6_dst, th->th_dport,
816                     INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
817                     m->m_pkthdr.rcvif, m);
818         }
819 #endif /* INET6 */
820 #if defined(INET6) && defined(INET)
821         else
822 #endif
823 #ifdef INET
824         if (fwd_tag != NULL) {
825                 struct sockaddr_in *next_hop;
826
827                 next_hop = (struct sockaddr_in *)(fwd_tag+1);
828                 /*
829                  * Transparently forwarded. Pretend to be the destination.
830                  * already got one like this?
831                  */
832                 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src, th->th_sport,
833                     ip->ip_dst, th->th_dport, INPLOOKUP_WLOCKPCB,
834                     m->m_pkthdr.rcvif, m);
835                 if (!inp) {
836                         /*
837                          * It's new.  Try to find the ambushing socket.
838                          * Because we've rewritten the destination address,
839                          * any hardware-generated hash is ignored.
840                          */
841                         inp = in_pcblookup(&V_tcbinfo, ip->ip_src,
842                             th->th_sport, next_hop->sin_addr,
843                             next_hop->sin_port ? ntohs(next_hop->sin_port) :
844                             th->th_dport, INPLOOKUP_WILDCARD |
845                             INPLOOKUP_WLOCKPCB, m->m_pkthdr.rcvif);
846                 }
847         } else
848                 inp = in_pcblookup_mbuf(&V_tcbinfo, ip->ip_src,
849                     th->th_sport, ip->ip_dst, th->th_dport,
850                     INPLOOKUP_WILDCARD | INPLOOKUP_WLOCKPCB,
851                     m->m_pkthdr.rcvif, m);
852 #endif /* INET */
853
854         /*
855          * If the INPCB does not exist then all data in the incoming
856          * segment is discarded and an appropriate RST is sent back.
857          * XXX MRT Send RST using which routing table?
858          */
859         if (inp == NULL) {
860                 /*
861                  * Log communication attempts to ports that are not
862                  * in use.
863                  */
864                 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
865                     tcp_log_in_vain == 2) {
866                         if ((s = tcp_log_vain(NULL, th, (void *)ip, ip6)))
867                                 log(LOG_INFO, "%s; %s: Connection attempt "
868                                     "to closed port\n", s, __func__);
869                 }
870                 /*
871                  * When blackholing do not respond with a RST but
872                  * completely ignore the segment and drop it.
873                  */
874                 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
875                     V_blackhole == 2)
876                         goto dropunlock;
877
878                 rstreason = BANDLIM_RST_CLOSEDPORT;
879                 goto dropwithreset;
880         }
881         INP_WLOCK_ASSERT(inp);
882         if ((inp->inp_flowtype == M_HASHTYPE_NONE) &&
883             (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE) &&
884             ((inp->inp_socket == NULL) ||
885             (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0)) {
886                 inp->inp_flowid = m->m_pkthdr.flowid;
887                 inp->inp_flowtype = M_HASHTYPE_GET(m);
888         }
889 #ifdef IPSEC
890 #ifdef INET6
891         if (isipv6 && ipsec6_in_reject(m, inp)) {
892                 IPSEC6STAT_INC(ips_in_polvio);
893                 goto dropunlock;
894         } else
895 #endif /* INET6 */
896         if (ipsec4_in_reject(m, inp) != 0) {
897                 IPSECSTAT_INC(ips_in_polvio);
898                 goto dropunlock;
899         }
900 #endif /* IPSEC */
901
902         /*
903          * Check the minimum TTL for socket.
904          */
905         if (inp->inp_ip_minttl != 0) {
906 #ifdef INET6
907                 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
908                         goto dropunlock;
909                 else
910 #endif
911                 if (inp->inp_ip_minttl > ip->ip_ttl)
912                         goto dropunlock;
913         }
914
915         /*
916          * A previous connection in TIMEWAIT state is supposed to catch stray
917          * or duplicate segments arriving late.  If this segment was a
918          * legitimate new connection attempt, the old INPCB gets removed and
919          * we can try again to find a listening socket.
920          *
921          * At this point, due to earlier optimism, we may hold only an inpcb
922          * lock, and not the inpcbinfo write lock.  If so, we need to try to
923          * acquire it, or if that fails, acquire a reference on the inpcb,
924          * drop all locks, acquire a global write lock, and then re-acquire
925          * the inpcb lock.  We may at that point discover that another thread
926          * has tried to free the inpcb, in which case we need to loop back
927          * and try to find a new inpcb to deliver to.
928          *
929          * XXXRW: It may be time to rethink timewait locking.
930          */
931 relocked:
932         if (inp->inp_flags & INP_TIMEWAIT) {
933                 if (ti_locked == TI_UNLOCKED) {
934                         if (INP_INFO_TRY_WLOCK(&V_tcbinfo) == 0) {
935                                 in_pcbref(inp);
936                                 INP_WUNLOCK(inp);
937                                 INP_INFO_WLOCK(&V_tcbinfo);
938                                 ti_locked = TI_WLOCKED;
939                                 INP_WLOCK(inp);
940                                 if (in_pcbrele_wlocked(inp)) {
941                                         inp = NULL;
942                                         goto findpcb;
943                                 }
944                         } else
945                                 ti_locked = TI_WLOCKED;
946                 }
947                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
948
949                 if (thflags & TH_SYN)
950                         tcp_dooptions(&to, optp, optlen, TO_SYN);
951                 /*
952                  * NB: tcp_twcheck unlocks the INP and frees the mbuf.
953                  */
954                 if (tcp_twcheck(inp, &to, th, m, tlen))
955                         goto findpcb;
956                 INP_INFO_WUNLOCK(&V_tcbinfo);
957                 return;
958         }
959         /*
960          * The TCPCB may no longer exist if the connection is winding
961          * down or it is in the CLOSED state.  Either way we drop the
962          * segment and send an appropriate response.
963          */
964         tp = intotcpcb(inp);
965         if (tp == NULL || tp->t_state == TCPS_CLOSED) {
966                 rstreason = BANDLIM_RST_CLOSEDPORT;
967                 goto dropwithreset;
968         }
969
970 #ifdef TCP_OFFLOAD
971         if (tp->t_flags & TF_TOE) {
972                 tcp_offload_input(tp, m);
973                 m = NULL;       /* consumed by the TOE driver */
974                 goto dropunlock;
975         }
976 #endif
977
978         /*
979          * We've identified a valid inpcb, but it could be that we need an
980          * inpcbinfo write lock but don't hold it.  In this case, attempt to
981          * acquire using the same strategy as the TIMEWAIT case above.  If we
982          * relock, we have to jump back to 'relocked' as the connection might
983          * now be in TIMEWAIT.
984          */
985 #ifdef INVARIANTS
986         if ((thflags & (TH_FIN | TH_RST)) != 0)
987                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
988 #endif
989         if (!((tp->t_state == TCPS_ESTABLISHED && (thflags & TH_SYN) == 0) ||
990               (tp->t_state == TCPS_LISTEN && (thflags & TH_SYN) &&
991                !(tp->t_flags & TF_FASTOPEN)))) {
992                 if (ti_locked == TI_UNLOCKED) {
993                         if (INP_INFO_TRY_WLOCK(&V_tcbinfo) == 0) {
994                                 in_pcbref(inp);
995                                 INP_WUNLOCK(inp);
996                                 INP_INFO_WLOCK(&V_tcbinfo);
997                                 ti_locked = TI_WLOCKED;
998                                 INP_WLOCK(inp);
999                                 if (in_pcbrele_wlocked(inp)) {
1000                                         inp = NULL;
1001                                         goto findpcb;
1002                                 }
1003                                 goto relocked;
1004                         } else
1005                                 ti_locked = TI_WLOCKED;
1006                 }
1007                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1008         }
1009
1010 #ifdef MAC
1011         INP_WLOCK_ASSERT(inp);
1012         if (mac_inpcb_check_deliver(inp, m))
1013                 goto dropunlock;
1014 #endif
1015         so = inp->inp_socket;
1016         KASSERT(so != NULL, ("%s: so == NULL", __func__));
1017 #ifdef TCPDEBUG
1018         if (so->so_options & SO_DEBUG) {
1019                 ostate = tp->t_state;
1020 #ifdef INET6
1021                 if (isipv6) {
1022                         bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
1023                 } else
1024 #endif
1025                         bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1026                 tcp_savetcp = *th;
1027         }
1028 #endif /* TCPDEBUG */
1029         /*
1030          * When the socket is accepting connections (the INPCB is in LISTEN
1031          * state) we look into the SYN cache if this is a new connection
1032          * attempt or the completion of a previous one.
1033          */
1034         if (so->so_options & SO_ACCEPTCONN) {
1035                 struct in_conninfo inc;
1036
1037                 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
1038                     "tp not listening", __func__));
1039                 bzero(&inc, sizeof(inc));
1040 #ifdef INET6
1041                 if (isipv6) {
1042                         inc.inc_flags |= INC_ISIPV6;
1043                         inc.inc6_faddr = ip6->ip6_src;
1044                         inc.inc6_laddr = ip6->ip6_dst;
1045                 } else
1046 #endif
1047                 {
1048                         inc.inc_faddr = ip->ip_src;
1049                         inc.inc_laddr = ip->ip_dst;
1050                 }
1051                 inc.inc_fport = th->th_sport;
1052                 inc.inc_lport = th->th_dport;
1053                 inc.inc_fibnum = so->so_fibnum;
1054
1055                 /*
1056                  * Check for an existing connection attempt in syncache if
1057                  * the flag is only ACK.  A successful lookup creates a new
1058                  * socket appended to the listen queue in SYN_RECEIVED state.
1059                  */
1060                 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
1061
1062                         INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1063                         /*
1064                          * Parse the TCP options here because
1065                          * syncookies need access to the reflected
1066                          * timestamp.
1067                          */
1068                         tcp_dooptions(&to, optp, optlen, 0);
1069                         /*
1070                          * NB: syncache_expand() doesn't unlock
1071                          * inp and tcpinfo locks.
1072                          */
1073                         if (!syncache_expand(&inc, &to, th, &so, m)) {
1074                                 /*
1075                                  * No syncache entry or ACK was not
1076                                  * for our SYN/ACK.  Send a RST.
1077                                  * NB: syncache did its own logging
1078                                  * of the failure cause.
1079                                  */
1080                                 rstreason = BANDLIM_RST_OPENPORT;
1081                                 goto dropwithreset;
1082                         }
1083 #ifdef TCP_RFC7413
1084 new_tfo_socket:
1085 #endif
1086                         if (so == NULL) {
1087                                 /*
1088                                  * We completed the 3-way handshake
1089                                  * but could not allocate a socket
1090                                  * either due to memory shortage,
1091                                  * listen queue length limits or
1092                                  * global socket limits.  Send RST
1093                                  * or wait and have the remote end
1094                                  * retransmit the ACK for another
1095                                  * try.
1096                                  */
1097                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1098                                         log(LOG_DEBUG, "%s; %s: Listen socket: "
1099                                             "Socket allocation failed due to "
1100                                             "limits or memory shortage, %s\n",
1101                                             s, __func__,
1102                                             V_tcp_sc_rst_sock_fail ?
1103                                             "sending RST" : "try again");
1104                                 if (V_tcp_sc_rst_sock_fail) {
1105                                         rstreason = BANDLIM_UNLIMITED;
1106                                         goto dropwithreset;
1107                                 } else
1108                                         goto dropunlock;
1109                         }
1110                         /*
1111                          * Socket is created in state SYN_RECEIVED.
1112                          * Unlock the listen socket, lock the newly
1113                          * created socket and update the tp variable.
1114                          */
1115                         INP_WUNLOCK(inp);       /* listen socket */
1116                         inp = sotoinpcb(so);
1117                         INP_WLOCK(inp);         /* new connection */
1118                         tp = intotcpcb(inp);
1119                         KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
1120                             ("%s: ", __func__));
1121 #ifdef TCP_SIGNATURE
1122                         if (sig_checked == 0)  {
1123                                 tcp_dooptions(&to, optp, optlen,
1124                                     (thflags & TH_SYN) ? TO_SYN : 0);
1125                                 if (!tcp_signature_verify_input(m, off0, tlen,
1126                                     optlen, &to, th, tp->t_flags)) {
1127
1128                                         /*
1129                                          * In SYN_SENT state if it receives an
1130                                          * RST, it is allowed for further
1131                                          * processing.
1132                                          */
1133                                         if ((thflags & TH_RST) == 0 ||
1134                                             (tp->t_state == TCPS_SYN_SENT) == 0)
1135                                                 goto dropunlock;
1136                                 }
1137                                 sig_checked = 1;
1138                         }
1139 #endif
1140
1141                         /*
1142                          * Process the segment and the data it
1143                          * contains.  tcp_do_segment() consumes
1144                          * the mbuf chain and unlocks the inpcb.
1145                          */
1146                         tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
1147                             iptos, ti_locked);
1148                         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1149                         return;
1150                 }
1151                 /*
1152                  * Segment flag validation for new connection attempts:
1153                  *
1154                  * Our (SYN|ACK) response was rejected.
1155                  * Check with syncache and remove entry to prevent
1156                  * retransmits.
1157                  *
1158                  * NB: syncache_chkrst does its own logging of failure
1159                  * causes.
1160                  */
1161                 if (thflags & TH_RST) {
1162                         syncache_chkrst(&inc, th);
1163                         goto dropunlock;
1164                 }
1165                 /*
1166                  * We can't do anything without SYN.
1167                  */
1168                 if ((thflags & TH_SYN) == 0) {
1169                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1170                                 log(LOG_DEBUG, "%s; %s: Listen socket: "
1171                                     "SYN is missing, segment ignored\n",
1172                                     s, __func__);
1173                         TCPSTAT_INC(tcps_badsyn);
1174                         goto dropunlock;
1175                 }
1176                 /*
1177                  * (SYN|ACK) is bogus on a listen socket.
1178                  */
1179                 if (thflags & TH_ACK) {
1180                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1181                                 log(LOG_DEBUG, "%s; %s: Listen socket: "
1182                                     "SYN|ACK invalid, segment rejected\n",
1183                                     s, __func__);
1184                         syncache_badack(&inc);  /* XXX: Not needed! */
1185                         TCPSTAT_INC(tcps_badsyn);
1186                         rstreason = BANDLIM_RST_OPENPORT;
1187                         goto dropwithreset;
1188                 }
1189                 /*
1190                  * If the drop_synfin option is enabled, drop all
1191                  * segments with both the SYN and FIN bits set.
1192                  * This prevents e.g. nmap from identifying the
1193                  * TCP/IP stack.
1194                  * XXX: Poor reasoning.  nmap has other methods
1195                  * and is constantly refining its stack detection
1196                  * strategies.
1197                  * XXX: This is a violation of the TCP specification
1198                  * and was used by RFC1644.
1199                  */
1200                 if ((thflags & TH_FIN) && V_drop_synfin) {
1201                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1202                                 log(LOG_DEBUG, "%s; %s: Listen socket: "
1203                                     "SYN|FIN segment ignored (based on "
1204                                     "sysctl setting)\n", s, __func__);
1205                         TCPSTAT_INC(tcps_badsyn);
1206                         goto dropunlock;
1207                 }
1208                 /*
1209                  * Segment's flags are (SYN) or (SYN|FIN).
1210                  *
1211                  * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
1212                  * as they do not affect the state of the TCP FSM.
1213                  * The data pointed to by TH_URG and th_urp is ignored.
1214                  */
1215                 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
1216                     ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
1217                 KASSERT(thflags & (TH_SYN),
1218                     ("%s: Listen socket: TH_SYN not set", __func__));
1219 #ifdef INET6
1220                 /*
1221                  * If deprecated address is forbidden,
1222                  * we do not accept SYN to deprecated interface
1223                  * address to prevent any new inbound connection from
1224                  * getting established.
1225                  * When we do not accept SYN, we send a TCP RST,
1226                  * with deprecated source address (instead of dropping
1227                  * it).  We compromise it as it is much better for peer
1228                  * to send a RST, and RST will be the final packet
1229                  * for the exchange.
1230                  *
1231                  * If we do not forbid deprecated addresses, we accept
1232                  * the SYN packet.  RFC2462 does not suggest dropping
1233                  * SYN in this case.
1234                  * If we decipher RFC2462 5.5.4, it says like this:
1235                  * 1. use of deprecated addr with existing
1236                  *    communication is okay - "SHOULD continue to be
1237                  *    used"
1238                  * 2. use of it with new communication:
1239                  *   (2a) "SHOULD NOT be used if alternate address
1240                  *        with sufficient scope is available"
1241                  *   (2b) nothing mentioned otherwise.
1242                  * Here we fall into (2b) case as we have no choice in
1243                  * our source address selection - we must obey the peer.
1244                  *
1245                  * The wording in RFC2462 is confusing, and there are
1246                  * multiple description text for deprecated address
1247                  * handling - worse, they are not exactly the same.
1248                  * I believe 5.5.4 is the best one, so we follow 5.5.4.
1249                  */
1250                 if (isipv6 && !V_ip6_use_deprecated) {
1251                         struct in6_ifaddr *ia6;
1252
1253                         ia6 = ip6_getdstifaddr(m);
1254                         if (ia6 != NULL &&
1255                             (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1256                                 ifa_free(&ia6->ia_ifa);
1257                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1258                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
1259                                         "Connection attempt to deprecated "
1260                                         "IPv6 address rejected\n",
1261                                         s, __func__);
1262                                 rstreason = BANDLIM_RST_OPENPORT;
1263                                 goto dropwithreset;
1264                         }
1265                         if (ia6)
1266                                 ifa_free(&ia6->ia_ifa);
1267                 }
1268 #endif /* INET6 */
1269                 /*
1270                  * Basic sanity checks on incoming SYN requests:
1271                  *   Don't respond if the destination is a link layer
1272                  *      broadcast according to RFC1122 4.2.3.10, p. 104.
1273                  *   If it is from this socket it must be forged.
1274                  *   Don't respond if the source or destination is a
1275                  *      global or subnet broad- or multicast address.
1276                  *   Note that it is quite possible to receive unicast
1277                  *      link-layer packets with a broadcast IP address. Use
1278                  *      in_broadcast() to find them.
1279                  */
1280                 if (m->m_flags & (M_BCAST|M_MCAST)) {
1281                         if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1282                             log(LOG_DEBUG, "%s; %s: Listen socket: "
1283                                 "Connection attempt from broad- or multicast "
1284                                 "link layer address ignored\n", s, __func__);
1285                         goto dropunlock;
1286                 }
1287 #ifdef INET6
1288                 if (isipv6) {
1289                         if (th->th_dport == th->th_sport &&
1290                             IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
1291                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1292                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
1293                                         "Connection attempt to/from self "
1294                                         "ignored\n", s, __func__);
1295                                 goto dropunlock;
1296                         }
1297                         if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1298                             IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
1299                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1300                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
1301                                         "Connection attempt from/to multicast "
1302                                         "address ignored\n", s, __func__);
1303                                 goto dropunlock;
1304                         }
1305                 }
1306 #endif
1307 #if defined(INET) && defined(INET6)
1308                 else
1309 #endif
1310 #ifdef INET
1311                 {
1312                         if (th->th_dport == th->th_sport &&
1313                             ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1314                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1315                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
1316                                         "Connection attempt from/to self "
1317                                         "ignored\n", s, __func__);
1318                                 goto dropunlock;
1319                         }
1320                         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1321                             IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1322                             ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1323                             in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1324                                 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1325                                     log(LOG_DEBUG, "%s; %s: Listen socket: "
1326                                         "Connection attempt from/to broad- "
1327                                         "or multicast address ignored\n",
1328                                         s, __func__);
1329                                 goto dropunlock;
1330                         }
1331                 }
1332 #endif
1333                 /*
1334                  * SYN appears to be valid.  Create compressed TCP state
1335                  * for syncache.
1336                  */
1337 #ifdef TCPDEBUG
1338                 if (so->so_options & SO_DEBUG)
1339                         tcp_trace(TA_INPUT, ostate, tp,
1340                             (void *)tcp_saveipgen, &tcp_savetcp, 0);
1341 #endif
1342                 tcp_dooptions(&to, optp, optlen, TO_SYN);
1343 #ifdef TCP_RFC7413
1344                 if (syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL))
1345                         goto new_tfo_socket;
1346 #else
1347                 syncache_add(&inc, &to, th, inp, &so, m, NULL, NULL);
1348 #endif
1349                 /*
1350                  * Entry added to syncache and mbuf consumed.
1351                  * Only the listen socket is unlocked by syncache_add().
1352                  */
1353                 if (ti_locked == TI_WLOCKED) {
1354                         INP_INFO_WUNLOCK(&V_tcbinfo);
1355                         ti_locked = TI_UNLOCKED;
1356                 }
1357                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1358                 return;
1359         } else if (tp->t_state == TCPS_LISTEN) {
1360                 /*
1361                  * When a listen socket is torn down the SO_ACCEPTCONN
1362                  * flag is removed first while connections are drained
1363                  * from the accept queue in a unlock/lock cycle of the
1364                  * ACCEPT_LOCK, opening a race condition allowing a SYN
1365                  * attempt go through unhandled.
1366                  */
1367                 goto dropunlock;
1368         }
1369
1370 #ifdef TCP_SIGNATURE
1371         if (sig_checked == 0)  {
1372                 tcp_dooptions(&to, optp, optlen,
1373                     (thflags & TH_SYN) ? TO_SYN : 0);
1374                 if (!tcp_signature_verify_input(m, off0, tlen, optlen, &to,
1375                     th, tp->t_flags)) {
1376
1377                         /*
1378                          * In SYN_SENT state if it receives an RST, it is
1379                          * allowed for further processing.
1380                          */
1381                         if ((thflags & TH_RST) == 0 ||
1382                             (tp->t_state == TCPS_SYN_SENT) == 0)
1383                                 goto dropunlock;
1384                 }
1385                 sig_checked = 1;
1386         }
1387 #endif
1388
1389         TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1390
1391         /*
1392          * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1393          * state.  tcp_do_segment() always consumes the mbuf chain, unlocks
1394          * the inpcb, and unlocks pcbinfo.
1395          */
1396         tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1397         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1398         return;
1399
1400 dropwithreset:
1401         TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1402
1403         if (ti_locked == TI_WLOCKED) {
1404                 INP_INFO_WUNLOCK(&V_tcbinfo);
1405                 ti_locked = TI_UNLOCKED;
1406         }
1407 #ifdef INVARIANTS
1408         else {
1409                 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropwithreset "
1410                     "ti_locked: %d", __func__, ti_locked));
1411                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1412         }
1413 #endif
1414
1415         if (inp != NULL) {
1416                 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1417                 INP_WUNLOCK(inp);
1418         } else
1419                 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1420         m = NULL;       /* mbuf chain got consumed. */
1421         goto drop;
1422
1423 dropunlock:
1424         if (m != NULL)
1425                 TCP_PROBE5(receive, NULL, tp, mtod(m, const char *), tp, th);
1426
1427         if (ti_locked == TI_WLOCKED) {
1428                 INP_INFO_WUNLOCK(&V_tcbinfo);
1429                 ti_locked = TI_UNLOCKED;
1430         }
1431 #ifdef INVARIANTS
1432         else {
1433                 KASSERT(ti_locked == TI_UNLOCKED, ("%s: dropunlock "
1434                     "ti_locked: %d", __func__, ti_locked));
1435                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1436         }
1437 #endif
1438
1439         if (inp != NULL)
1440                 INP_WUNLOCK(inp);
1441
1442 drop:
1443         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1444         if (s != NULL)
1445                 free(s, M_TCPLOG);
1446         if (m != NULL)
1447                 m_freem(m);
1448 }
1449
1450 static void
1451 tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1452     struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1453     int ti_locked)
1454 {
1455         int thflags, acked, ourfinisacked, needoutput = 0, sack_changed;
1456         int rstreason, todrop, win;
1457         u_long tiwin;
1458         char *s;
1459         struct in_conninfo *inc;
1460         struct mbuf *mfree;
1461         struct tcpopt to;
1462         int tfo_syn;
1463
1464 #ifdef TCPDEBUG
1465         /*
1466          * The size of tcp_saveipgen must be the size of the max ip header,
1467          * now IPv6.
1468          */
1469         u_char tcp_saveipgen[IP6_HDR_LEN];
1470         struct tcphdr tcp_savetcp;
1471         short ostate = 0;
1472 #endif
1473         thflags = th->th_flags;
1474         inc = &tp->t_inpcb->inp_inc;
1475         tp->sackhint.last_sack_ack = 0;
1476         sack_changed = 0;
1477
1478         /*
1479          * If this is either a state-changing packet or current state isn't
1480          * established, we require a write lock on tcbinfo.  Otherwise, we
1481          * allow the tcbinfo to be in either alocked or unlocked, as the
1482          * caller may have unnecessarily acquired a write lock due to a race.
1483          */
1484         if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1485             tp->t_state != TCPS_ESTABLISHED) {
1486                 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1487                     "SYN/FIN/RST/!EST", __func__, ti_locked));
1488                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1489         } else {
1490 #ifdef INVARIANTS
1491                 if (ti_locked == TI_WLOCKED)
1492                         INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1493                 else {
1494                         KASSERT(ti_locked == TI_UNLOCKED, ("%s: EST "
1495                             "ti_locked: %d", __func__, ti_locked));
1496                         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1497                 }
1498 #endif
1499         }
1500         INP_WLOCK_ASSERT(tp->t_inpcb);
1501         KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1502             __func__));
1503         KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1504             __func__));
1505
1506         /*
1507          * Segment received on connection.
1508          * Reset idle time and keep-alive timer.
1509          * XXX: This should be done after segment
1510          * validation to ignore broken/spoofed segs.
1511          */
1512         tp->t_rcvtime = ticks;
1513         if (TCPS_HAVEESTABLISHED(tp->t_state))
1514                 tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
1515
1516         /*
1517          * Unscale the window into a 32-bit value.
1518          * For the SYN_SENT state the scale is zero.
1519          */
1520         tiwin = th->th_win << tp->snd_scale;
1521
1522         /*
1523          * TCP ECN processing.
1524          */
1525         if (tp->t_flags & TF_ECN_PERMIT) {
1526                 if (thflags & TH_CWR)
1527                         tp->t_flags &= ~TF_ECN_SND_ECE;
1528                 switch (iptos & IPTOS_ECN_MASK) {
1529                 case IPTOS_ECN_CE:
1530                         tp->t_flags |= TF_ECN_SND_ECE;
1531                         TCPSTAT_INC(tcps_ecn_ce);
1532                         break;
1533                 case IPTOS_ECN_ECT0:
1534                         TCPSTAT_INC(tcps_ecn_ect0);
1535                         break;
1536                 case IPTOS_ECN_ECT1:
1537                         TCPSTAT_INC(tcps_ecn_ect1);
1538                         break;
1539                 }
1540                 /* Congestion experienced. */
1541                 if (thflags & TH_ECE) {
1542                         cc_cong_signal(tp, th, CC_ECN);
1543                 }
1544         }
1545
1546         /*
1547          * Parse options on any incoming segment.
1548          */
1549         tcp_dooptions(&to, (u_char *)(th + 1),
1550             (th->th_off << 2) - sizeof(struct tcphdr),
1551             (thflags & TH_SYN) ? TO_SYN : 0);
1552
1553         /*
1554          * If echoed timestamp is later than the current time,
1555          * fall back to non RFC1323 RTT calculation.  Normalize
1556          * timestamp if syncookies were used when this connection
1557          * was established.
1558          */
1559         if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1560                 to.to_tsecr -= tp->ts_offset;
1561                 if (TSTMP_GT(to.to_tsecr, tcp_ts_getticks()))
1562                         to.to_tsecr = 0;
1563         }
1564         /*
1565          * If timestamps were negotiated during SYN/ACK they should
1566          * appear on every segment during this session and vice versa.
1567          */
1568         if ((tp->t_flags & TF_RCVD_TSTMP) && !(to.to_flags & TOF_TS)) {
1569                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1570                         log(LOG_DEBUG, "%s; %s: Timestamp missing, "
1571                             "no action\n", s, __func__);
1572                         free(s, M_TCPLOG);
1573                 }
1574         }
1575         if (!(tp->t_flags & TF_RCVD_TSTMP) && (to.to_flags & TOF_TS)) {
1576                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
1577                         log(LOG_DEBUG, "%s; %s: Timestamp not expected, "
1578                             "no action\n", s, __func__);
1579                         free(s, M_TCPLOG);
1580                 }
1581         }
1582
1583         /*
1584          * Process options only when we get SYN/ACK back. The SYN case
1585          * for incoming connections is handled in tcp_syncache.
1586          * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1587          * or <SYN,ACK>) segment itself is never scaled.
1588          * XXX this is traditional behavior, may need to be cleaned up.
1589          */
1590         if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1591                 if ((to.to_flags & TOF_SCALE) &&
1592                     (tp->t_flags & TF_REQ_SCALE)) {
1593                         tp->t_flags |= TF_RCVD_SCALE;
1594                         tp->snd_scale = to.to_wscale;
1595                 }
1596                 /*
1597                  * Initial send window.  It will be updated with
1598                  * the next incoming segment to the scaled value.
1599                  */
1600                 tp->snd_wnd = th->th_win;
1601                 if (to.to_flags & TOF_TS) {
1602                         tp->t_flags |= TF_RCVD_TSTMP;
1603                         tp->ts_recent = to.to_tsval;
1604                         tp->ts_recent_age = tcp_ts_getticks();
1605                 }
1606                 if (to.to_flags & TOF_MSS)
1607                         tcp_mss(tp, to.to_mss);
1608                 if ((tp->t_flags & TF_SACK_PERMIT) &&
1609                     (to.to_flags & TOF_SACKPERM) == 0)
1610                         tp->t_flags &= ~TF_SACK_PERMIT;
1611         }
1612
1613         /*
1614          * Header prediction: check for the two common cases
1615          * of a uni-directional data xfer.  If the packet has
1616          * no control flags, is in-sequence, the window didn't
1617          * change and we're not retransmitting, it's a
1618          * candidate.  If the length is zero and the ack moved
1619          * forward, we're the sender side of the xfer.  Just
1620          * free the data acked & wake any higher level process
1621          * that was blocked waiting for space.  If the length
1622          * is non-zero and the ack didn't move, we're the
1623          * receiver side.  If we're getting packets in-order
1624          * (the reassembly queue is empty), add the data to
1625          * the socket buffer and note that we need a delayed ack.
1626          * Make sure that the hidden state-flags are also off.
1627          * Since we check for TCPS_ESTABLISHED first, it can only
1628          * be TH_NEEDSYN.
1629          */
1630         if (tp->t_state == TCPS_ESTABLISHED &&
1631             th->th_seq == tp->rcv_nxt &&
1632             (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1633             tp->snd_nxt == tp->snd_max &&
1634             tiwin && tiwin == tp->snd_wnd && 
1635             ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1636             LIST_EMPTY(&tp->t_segq) &&
1637             ((to.to_flags & TOF_TS) == 0 ||
1638              TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1639
1640                 /*
1641                  * If last ACK falls within this segment's sequence numbers,
1642                  * record the timestamp.
1643                  * NOTE that the test is modified according to the latest
1644                  * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1645                  */
1646                 if ((to.to_flags & TOF_TS) != 0 &&
1647                     SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1648                         tp->ts_recent_age = tcp_ts_getticks();
1649                         tp->ts_recent = to.to_tsval;
1650                 }
1651
1652                 if (tlen == 0) {
1653                         if (SEQ_GT(th->th_ack, tp->snd_una) &&
1654                             SEQ_LEQ(th->th_ack, tp->snd_max) &&
1655                             !IN_RECOVERY(tp->t_flags) &&
1656                             (to.to_flags & TOF_SACK) == 0 &&
1657                             TAILQ_EMPTY(&tp->snd_holes)) {
1658                                 /*
1659                                  * This is a pure ack for outstanding data.
1660                                  */
1661                                 if (ti_locked == TI_WLOCKED)
1662                                         INP_INFO_WUNLOCK(&V_tcbinfo);
1663                                 ti_locked = TI_UNLOCKED;
1664
1665                                 TCPSTAT_INC(tcps_predack);
1666
1667                                 /*
1668                                  * "bad retransmit" recovery.
1669                                  */
1670                                 if (tp->t_rxtshift == 1 &&
1671                                     tp->t_flags & TF_PREVVALID &&
1672                                     (int)(ticks - tp->t_badrxtwin) < 0) {
1673                                         cc_cong_signal(tp, th, CC_RTO_ERR);
1674                                 }
1675
1676                                 /*
1677                                  * Recalculate the transmit timer / rtt.
1678                                  *
1679                                  * Some boxes send broken timestamp replies
1680                                  * during the SYN+ACK phase, ignore
1681                                  * timestamps of 0 or we could calculate a
1682                                  * huge RTT and blow up the retransmit timer.
1683                                  */
1684                                 if ((to.to_flags & TOF_TS) != 0 &&
1685                                     to.to_tsecr) {
1686                                         u_int t;
1687
1688                                         t = tcp_ts_getticks() - to.to_tsecr;
1689                                         if (!tp->t_rttlow || tp->t_rttlow > t)
1690                                                 tp->t_rttlow = t;
1691                                         tcp_xmit_timer(tp,
1692                                             TCP_TS_TO_TICKS(t) + 1);
1693                                 } else if (tp->t_rtttime &&
1694                                     SEQ_GT(th->th_ack, tp->t_rtseq)) {
1695                                         if (!tp->t_rttlow ||
1696                                             tp->t_rttlow > ticks - tp->t_rtttime)
1697                                                 tp->t_rttlow = ticks - tp->t_rtttime;
1698                                         tcp_xmit_timer(tp,
1699                                                         ticks - tp->t_rtttime);
1700                                 }
1701                                 acked = BYTES_THIS_ACK(tp, th);
1702
1703                                 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
1704                                 hhook_run_tcp_est_in(tp, th, &to);
1705
1706                                 TCPSTAT_INC(tcps_rcvackpack);
1707                                 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1708                                 sbdrop(&so->so_snd, acked);
1709                                 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1710                                     SEQ_LEQ(th->th_ack, tp->snd_recover))
1711                                         tp->snd_recover = th->th_ack - 1;
1712                                 
1713                                 /*
1714                                  * Let the congestion control algorithm update
1715                                  * congestion control related information. This
1716                                  * typically means increasing the congestion
1717                                  * window.
1718                                  */
1719                                 cc_ack_received(tp, th, CC_ACK);
1720
1721                                 tp->snd_una = th->th_ack;
1722                                 /*
1723                                  * Pull snd_wl2 up to prevent seq wrap relative
1724                                  * to th_ack.
1725                                  */
1726                                 tp->snd_wl2 = th->th_ack;
1727                                 tp->t_dupacks = 0;
1728                                 m_freem(m);
1729                                 ND6_HINT(tp); /* Some progress has been made. */
1730
1731                                 /*
1732                                  * If all outstanding data are acked, stop
1733                                  * retransmit timer, otherwise restart timer
1734                                  * using current (possibly backed-off) value.
1735                                  * If process is waiting for space,
1736                                  * wakeup/selwakeup/signal.  If data
1737                                  * are ready to send, let tcp_output
1738                                  * decide between more output or persist.
1739                                  */
1740 #ifdef TCPDEBUG
1741                                 if (so->so_options & SO_DEBUG)
1742                                         tcp_trace(TA_INPUT, ostate, tp,
1743                                             (void *)tcp_saveipgen,
1744                                             &tcp_savetcp, 0);
1745 #endif
1746                                 if (tp->snd_una == tp->snd_max)
1747                                         tcp_timer_activate(tp, TT_REXMT, 0);
1748                                 else if (!tcp_timer_active(tp, TT_PERSIST))
1749                                         tcp_timer_activate(tp, TT_REXMT,
1750                                                       tp->t_rxtcur);
1751                                 sowwakeup(so);
1752                                 if (so->so_snd.sb_cc)
1753                                         (void) tcp_output(tp);
1754                                 goto check_delack;
1755                         }
1756                 } else if (th->th_ack == tp->snd_una &&
1757                     tlen <= sbspace(&so->so_rcv)) {
1758                         int newsize = 0;        /* automatic sockbuf scaling */
1759
1760                         /*
1761                          * This is a pure, in-sequence data packet with
1762                          * nothing on the reassembly queue and we have enough
1763                          * buffer space to take it.
1764                          */
1765                         if (ti_locked == TI_WLOCKED)
1766                                 INP_INFO_WUNLOCK(&V_tcbinfo);
1767                         ti_locked = TI_UNLOCKED;
1768
1769                         /* Clean receiver SACK report if present */
1770                         if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1771                                 tcp_clean_sackreport(tp);
1772                         TCPSTAT_INC(tcps_preddat);
1773                         tp->rcv_nxt += tlen;
1774                         /*
1775                          * Pull snd_wl1 up to prevent seq wrap relative to
1776                          * th_seq.
1777                          */
1778                         tp->snd_wl1 = th->th_seq;
1779                         /*
1780                          * Pull rcv_up up to prevent seq wrap relative to
1781                          * rcv_nxt.
1782                          */
1783                         tp->rcv_up = tp->rcv_nxt;
1784                         TCPSTAT_INC(tcps_rcvpack);
1785                         TCPSTAT_ADD(tcps_rcvbyte, tlen);
1786                         ND6_HINT(tp);   /* Some progress has been made */
1787 #ifdef TCPDEBUG
1788                         if (so->so_options & SO_DEBUG)
1789                                 tcp_trace(TA_INPUT, ostate, tp,
1790                                     (void *)tcp_saveipgen, &tcp_savetcp, 0);
1791 #endif
1792                 /*
1793                  * Automatic sizing of receive socket buffer.  Often the send
1794                  * buffer size is not optimally adjusted to the actual network
1795                  * conditions at hand (delay bandwidth product).  Setting the
1796                  * buffer size too small limits throughput on links with high
1797                  * bandwidth and high delay (eg. trans-continental/oceanic links).
1798                  *
1799                  * On the receive side the socket buffer memory is only rarely
1800                  * used to any significant extent.  This allows us to be much
1801                  * more aggressive in scaling the receive socket buffer.  For
1802                  * the case that the buffer space is actually used to a large
1803                  * extent and we run out of kernel memory we can simply drop
1804                  * the new segments; TCP on the sender will just retransmit it
1805                  * later.  Setting the buffer size too big may only consume too
1806                  * much kernel memory if the application doesn't read() from
1807                  * the socket or packet loss or reordering makes use of the
1808                  * reassembly queue.
1809                  *
1810                  * The criteria to step up the receive buffer one notch are:
1811                  *  1. the number of bytes received during the time it takes
1812                  *     one timestamp to be reflected back to us (the RTT);
1813                  *  2. received bytes per RTT is within seven eighth of the
1814                  *     current socket buffer size;
1815                  *  3. receive buffer size has not hit maximal automatic size;
1816                  *
1817                  * This algorithm does one step per RTT at most and only if
1818                  * we receive a bulk stream w/o packet losses or reorderings.
1819                  * Shrinking the buffer during idle times is not necessary as
1820                  * it doesn't consume any memory when idle.
1821                  *
1822                  * TODO: Only step up if the application is actually serving
1823                  * the buffer to better manage the socket buffer resources.
1824                  */
1825                         if (V_tcp_do_autorcvbuf &&
1826                             (to.to_flags & TOF_TS) &&
1827                             to.to_tsecr &&
1828                             (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1829                                 if (TSTMP_GT(to.to_tsecr, tp->rfbuf_ts) &&
1830                                     to.to_tsecr - tp->rfbuf_ts < hz) {
1831                                         if (tp->rfbuf_cnt >
1832                                             (so->so_rcv.sb_hiwat / 8 * 7) &&
1833                                             so->so_rcv.sb_hiwat <
1834                                             V_tcp_autorcvbuf_max) {
1835                                                 newsize =
1836                                                     min(so->so_rcv.sb_hiwat +
1837                                                     V_tcp_autorcvbuf_inc,
1838                                                     V_tcp_autorcvbuf_max);
1839                                         }
1840                                         /* Start over with next RTT. */
1841                                         tp->rfbuf_ts = 0;
1842                                         tp->rfbuf_cnt = 0;
1843                                 } else
1844                                         tp->rfbuf_cnt += tlen;  /* add up */
1845                         }
1846
1847                         /* Add data to socket buffer. */
1848                         SOCKBUF_LOCK(&so->so_rcv);
1849                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1850                                 m_freem(m);
1851                         } else {
1852                                 /*
1853                                  * Set new socket buffer size.
1854                                  * Give up when limit is reached.
1855                                  */
1856                                 if (newsize)
1857                                         if (!sbreserve_locked(&so->so_rcv,
1858                                             newsize, so, NULL))
1859                                                 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1860                                 m_adj(m, drop_hdrlen);  /* delayed header drop */
1861                                 sbappendstream_locked(&so->so_rcv, m);
1862                         }
1863                         /* NB: sorwakeup_locked() does an implicit unlock. */
1864                         sorwakeup_locked(so);
1865                         if (DELAY_ACK(tp, tlen)) {
1866                                 tp->t_flags |= TF_DELACK;
1867                         } else {
1868                                 tp->t_flags |= TF_ACKNOW;
1869                                 tcp_output(tp);
1870                         }
1871                         goto check_delack;
1872                 }
1873         }
1874
1875         /*
1876          * Calculate amount of space in receive window,
1877          * and then do TCP input processing.
1878          * Receive window is amount of space in rcv queue,
1879          * but not less than advertised window.
1880          */
1881         win = sbspace(&so->so_rcv);
1882         if (win < 0)
1883                 win = 0;
1884         tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1885
1886         /* Reset receive buffer auto scaling when not in bulk receive mode. */
1887         tp->rfbuf_ts = 0;
1888         tp->rfbuf_cnt = 0;
1889
1890         switch (tp->t_state) {
1891
1892         /*
1893          * If the state is SYN_RECEIVED:
1894          *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
1895          */
1896         case TCPS_SYN_RECEIVED:
1897                 if ((thflags & TH_ACK) &&
1898                     (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1899                      SEQ_GT(th->th_ack, tp->snd_max))) {
1900                                 rstreason = BANDLIM_RST_OPENPORT;
1901                                 goto dropwithreset;
1902                 }
1903 #ifdef TCP_RFC7413
1904                 if (tp->t_flags & TF_FASTOPEN) {
1905                         /*
1906                          * When a TFO connection is in SYN_RECEIVED, the
1907                          * only valid packets are the initial SYN, a
1908                          * retransmit/copy of the initial SYN (possibly with
1909                          * a subset of the original data), a valid ACK, a
1910                          * FIN, or a RST.
1911                          */
1912                         if ((thflags & (TH_SYN|TH_ACK)) == (TH_SYN|TH_ACK)) {
1913                                 rstreason = BANDLIM_RST_OPENPORT;
1914                                 goto dropwithreset;
1915                         } else if (thflags & TH_SYN) {
1916                                 /* non-initial SYN is ignored */
1917                                 if ((tcp_timer_active(tp, TT_DELACK) || 
1918                                      tcp_timer_active(tp, TT_REXMT)))
1919                                         goto drop;
1920                         } else if (!(thflags & (TH_ACK|TH_FIN|TH_RST))) {
1921                                 goto drop;
1922                         }
1923                 }
1924 #endif
1925                 break;
1926
1927         /*
1928          * If the state is SYN_SENT:
1929          *      if seg contains an ACK, but not for our SYN, drop the input.
1930          *      if seg contains a RST, then drop the connection.
1931          *      if seg does not contain SYN, then drop it.
1932          * Otherwise this is an acceptable SYN segment
1933          *      initialize tp->rcv_nxt and tp->irs
1934          *      if seg contains ack then advance tp->snd_una
1935          *      if seg contains an ECE and ECN support is enabled, the stream
1936          *          is ECN capable.
1937          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1938          *      arrange for segment to be acked (eventually)
1939          *      continue processing rest of data/controls, beginning with URG
1940          */
1941         case TCPS_SYN_SENT:
1942                 if ((thflags & TH_ACK) &&
1943                     (SEQ_LEQ(th->th_ack, tp->iss) ||
1944                      SEQ_GT(th->th_ack, tp->snd_max))) {
1945                         rstreason = BANDLIM_UNLIMITED;
1946                         goto dropwithreset;
1947                 }
1948                 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST)) {
1949                         TCP_PROBE5(connect__refused, NULL, tp,
1950                             mtod(m, const char *), tp, th);
1951                         tp = tcp_drop(tp, ECONNREFUSED);
1952                 }
1953                 if (thflags & TH_RST)
1954                         goto drop;
1955                 if (!(thflags & TH_SYN))
1956                         goto drop;
1957
1958                 tp->irs = th->th_seq;
1959                 tcp_rcvseqinit(tp);
1960                 if (thflags & TH_ACK) {
1961                         TCPSTAT_INC(tcps_connects);
1962                         soisconnected(so);
1963 #ifdef MAC
1964                         mac_socketpeer_set_from_mbuf(m, so);
1965 #endif
1966                         /* Do window scaling on this connection? */
1967                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1968                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1969                                 tp->rcv_scale = tp->request_r_scale;
1970                         }
1971                         tp->rcv_adv += imin(tp->rcv_wnd,
1972                             TCP_MAXWIN << tp->rcv_scale);
1973                         tp->snd_una++;          /* SYN is acked */
1974                         /*
1975                          * If there's data, delay ACK; if there's also a FIN
1976                          * ACKNOW will be turned on later.
1977                          */
1978                         if (DELAY_ACK(tp, tlen) && tlen != 0)
1979                                 tcp_timer_activate(tp, TT_DELACK,
1980                                     tcp_delacktime);
1981                         else
1982                                 tp->t_flags |= TF_ACKNOW;
1983
1984                         if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1985                                 tp->t_flags |= TF_ECN_PERMIT;
1986                                 TCPSTAT_INC(tcps_ecn_shs);
1987                         }
1988                         
1989                         /*
1990                          * Received <SYN,ACK> in SYN_SENT[*] state.
1991                          * Transitions:
1992                          *      SYN_SENT  --> ESTABLISHED
1993                          *      SYN_SENT* --> FIN_WAIT_1
1994                          */
1995                         tp->t_starttime = ticks;
1996                         if (tp->t_flags & TF_NEEDFIN) {
1997                                 tcp_state_change(tp, TCPS_FIN_WAIT_1);
1998                                 tp->t_flags &= ~TF_NEEDFIN;
1999                                 thflags &= ~TH_SYN;
2000                         } else {
2001                                 tcp_state_change(tp, TCPS_ESTABLISHED);
2002                                 TCP_PROBE5(connect__established, NULL, tp,
2003                                     mtod(m, const char *), tp, th);
2004                                 cc_conn_init(tp);
2005                                 tcp_timer_activate(tp, TT_KEEP,
2006                                     TP_KEEPIDLE(tp));
2007                         }
2008                 } else {
2009                         /*
2010                          * Received initial SYN in SYN-SENT[*] state =>
2011                          * simultaneous open.  If segment contains CC option
2012                          * and there is a cached CC, apply TAO test.
2013                          * If it succeeds, connection is * half-synchronized.
2014                          * Otherwise, do 3-way handshake:
2015                          *        SYN-SENT -> SYN-RECEIVED
2016                          *        SYN-SENT* -> SYN-RECEIVED*
2017                          * If there was no CC option, clear cached CC value.
2018                          */
2019                         tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
2020                         tcp_timer_activate(tp, TT_REXMT, 0);
2021                         tcp_state_change(tp, TCPS_SYN_RECEIVED);
2022                 }
2023
2024                 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
2025                     "ti_locked %d", __func__, ti_locked));
2026                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2027                 INP_WLOCK_ASSERT(tp->t_inpcb);
2028
2029                 /*
2030                  * Advance th->th_seq to correspond to first data byte.
2031                  * If data, trim to stay within window,
2032                  * dropping FIN if necessary.
2033                  */
2034                 th->th_seq++;
2035                 if (tlen > tp->rcv_wnd) {
2036                         todrop = tlen - tp->rcv_wnd;
2037                         m_adj(m, -todrop);
2038                         tlen = tp->rcv_wnd;
2039                         thflags &= ~TH_FIN;
2040                         TCPSTAT_INC(tcps_rcvpackafterwin);
2041                         TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2042                 }
2043                 tp->snd_wl1 = th->th_seq - 1;
2044                 tp->rcv_up = th->th_seq;
2045                 /*
2046                  * Client side of transaction: already sent SYN and data.
2047                  * If the remote host used T/TCP to validate the SYN,
2048                  * our data will be ACK'd; if so, enter normal data segment
2049                  * processing in the middle of step 5, ack processing.
2050                  * Otherwise, goto step 6.
2051                  */
2052                 if (thflags & TH_ACK)
2053                         goto process_ACK;
2054
2055                 goto step6;
2056
2057         /*
2058          * If the state is LAST_ACK or CLOSING or TIME_WAIT:
2059          *      do normal processing.
2060          *
2061          * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
2062          */
2063         case TCPS_LAST_ACK:
2064         case TCPS_CLOSING:
2065                 break;  /* continue normal processing */
2066         }
2067
2068         /*
2069          * States other than LISTEN or SYN_SENT.
2070          * First check the RST flag and sequence number since reset segments
2071          * are exempt from the timestamp and connection count tests.  This
2072          * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
2073          * below which allowed reset segments in half the sequence space
2074          * to fall though and be processed (which gives forged reset
2075          * segments with a random sequence number a 50 percent chance of
2076          * killing a connection).
2077          * Then check timestamp, if present.
2078          * Then check the connection count, if present.
2079          * Then check that at least some bytes of segment are within
2080          * receive window.  If segment begins before rcv_nxt,
2081          * drop leading data (and SYN); if nothing left, just ack.
2082          *
2083          *
2084          * If the RST bit is set, check the sequence number to see
2085          * if this is a valid reset segment.
2086          * RFC 793 page 37:
2087          *   In all states except SYN-SENT, all reset (RST) segments
2088          *   are validated by checking their SEQ-fields.  A reset is
2089          *   valid if its sequence number is in the window.
2090          * Note: this does not take into account delayed ACKs, so
2091          *   we should test against last_ack_sent instead of rcv_nxt.
2092          *   The sequence number in the reset segment is normally an
2093          *   echo of our outgoing acknowlegement numbers, but some hosts
2094          *   send a reset with the sequence number at the rightmost edge
2095          *   of our receive window, and we have to handle this case.
2096          * Note 2: Paul Watson's paper "Slipping in the Window" has shown
2097          *   that brute force RST attacks are possible.  To combat this,
2098          *   we use a much stricter check while in the ESTABLISHED state,
2099          *   only accepting RSTs where the sequence number is equal to
2100          *   last_ack_sent.  In all other states (the states in which a
2101          *   RST is more likely), the more permissive check is used.
2102          * If we have multiple segments in flight, the initial reset
2103          * segment sequence numbers will be to the left of last_ack_sent,
2104          * but they will eventually catch up.
2105          * In any case, it never made sense to trim reset segments to
2106          * fit the receive window since RFC 1122 says:
2107          *   4.2.2.12  RST Segment: RFC-793 Section 3.4
2108          *
2109          *    A TCP SHOULD allow a received RST segment to include data.
2110          *
2111          *    DISCUSSION
2112          *         It has been suggested that a RST segment could contain
2113          *         ASCII text that encoded and explained the cause of the
2114          *         RST.  No standard has yet been established for such
2115          *         data.
2116          *
2117          * If the reset segment passes the sequence number test examine
2118          * the state:
2119          *    SYN_RECEIVED STATE:
2120          *      If passive open, return to LISTEN state.
2121          *      If active open, inform user that connection was refused.
2122          *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
2123          *      Inform user that connection was reset, and close tcb.
2124          *    CLOSING, LAST_ACK STATES:
2125          *      Close the tcb.
2126          *    TIME_WAIT STATE:
2127          *      Drop the segment - see Stevens, vol. 2, p. 964 and
2128          *      RFC 1337.
2129          */
2130         if (thflags & TH_RST) {
2131                 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
2132                     SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2133                         switch (tp->t_state) {
2134
2135                         case TCPS_SYN_RECEIVED:
2136                                 so->so_error = ECONNREFUSED;
2137                                 goto close;
2138
2139                         case TCPS_ESTABLISHED:
2140                                 if (V_tcp_insecure_rst == 0 &&
2141                                     !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
2142                                     SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
2143                                     !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
2144                                     SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
2145                                         TCPSTAT_INC(tcps_badrst);
2146                                         goto drop;
2147                                 }
2148                                 /* FALLTHROUGH */
2149                         case TCPS_FIN_WAIT_1:
2150                         case TCPS_FIN_WAIT_2:
2151                         case TCPS_CLOSE_WAIT:
2152                                 so->so_error = ECONNRESET;
2153                         close:
2154                                 KASSERT(ti_locked == TI_WLOCKED,
2155                                     ("tcp_do_segment: TH_RST 1 ti_locked %d",
2156                                     ti_locked));
2157                                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2158
2159                                 tcp_state_change(tp, TCPS_CLOSED);
2160                                 TCPSTAT_INC(tcps_drops);
2161                                 tp = tcp_close(tp);
2162                                 break;
2163
2164                         case TCPS_CLOSING:
2165                         case TCPS_LAST_ACK:
2166                                 KASSERT(ti_locked == TI_WLOCKED,
2167                                     ("tcp_do_segment: TH_RST 2 ti_locked %d",
2168                                     ti_locked));
2169                                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2170
2171                                 tp = tcp_close(tp);
2172                                 break;
2173                         }
2174                 }
2175                 goto drop;
2176         }
2177
2178         /*
2179          * RFC 1323 PAWS: If we have a timestamp reply on this segment
2180          * and it's less than ts_recent, drop it.
2181          */
2182         if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2183             TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2184
2185                 /* Check to see if ts_recent is over 24 days old.  */
2186                 if (tcp_ts_getticks() - tp->ts_recent_age > TCP_PAWS_IDLE) {
2187                         /*
2188                          * Invalidate ts_recent.  If this segment updates
2189                          * ts_recent, the age will be reset later and ts_recent
2190                          * will get a valid value.  If it does not, setting
2191                          * ts_recent to zero will at least satisfy the
2192                          * requirement that zero be placed in the timestamp
2193                          * echo reply when ts_recent isn't valid.  The
2194                          * age isn't reset until we get a valid ts_recent
2195                          * because we don't want out-of-order segments to be
2196                          * dropped when ts_recent is old.
2197                          */
2198                         tp->ts_recent = 0;
2199                 } else {
2200                         TCPSTAT_INC(tcps_rcvduppack);
2201                         TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
2202                         TCPSTAT_INC(tcps_pawsdrop);
2203                         if (tlen)
2204                                 goto dropafterack;
2205                         goto drop;
2206                 }
2207         }
2208
2209         /*
2210          * In the SYN-RECEIVED state, validate that the packet belongs to
2211          * this connection before trimming the data to fit the receive
2212          * window.  Check the sequence number versus IRS since we know
2213          * the sequence numbers haven't wrapped.  This is a partial fix
2214          * for the "LAND" DoS attack.
2215          */
2216         if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2217                 rstreason = BANDLIM_RST_OPENPORT;
2218                 goto dropwithreset;
2219         }
2220
2221         todrop = tp->rcv_nxt - th->th_seq;
2222         if (todrop > 0) {
2223                 if (thflags & TH_SYN) {
2224                         thflags &= ~TH_SYN;
2225                         th->th_seq++;
2226                         if (th->th_urp > 1)
2227                                 th->th_urp--;
2228                         else
2229                                 thflags &= ~TH_URG;
2230                         todrop--;
2231                 }
2232                 /*
2233                  * Following if statement from Stevens, vol. 2, p. 960.
2234                  */
2235                 if (todrop > tlen
2236                     || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2237                         /*
2238                          * Any valid FIN must be to the left of the window.
2239                          * At this point the FIN must be a duplicate or out
2240                          * of sequence; drop it.
2241                          */
2242                         thflags &= ~TH_FIN;
2243
2244                         /*
2245                          * Send an ACK to resynchronize and drop any data.
2246                          * But keep on processing for RST or ACK.
2247                          */
2248                         tp->t_flags |= TF_ACKNOW;
2249                         todrop = tlen;
2250                         TCPSTAT_INC(tcps_rcvduppack);
2251                         TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
2252                 } else {
2253                         TCPSTAT_INC(tcps_rcvpartduppack);
2254                         TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
2255                 }
2256                 drop_hdrlen += todrop;  /* drop from the top afterwards */
2257                 th->th_seq += todrop;
2258                 tlen -= todrop;
2259                 if (th->th_urp > todrop)
2260                         th->th_urp -= todrop;
2261                 else {
2262                         thflags &= ~TH_URG;
2263                         th->th_urp = 0;
2264                 }
2265         }
2266
2267         /*
2268          * If new data are received on a connection after the
2269          * user processes are gone, then RST the other end.
2270          */
2271         if ((so->so_state & SS_NOFDREF) &&
2272             tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2273                 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
2274                     "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
2275                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2276
2277                 if ((s = tcp_log_addrs(inc, th, NULL, NULL))) {
2278                         log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data "
2279                             "after socket was closed, "
2280                             "sending RST and removing tcpcb\n",
2281                             s, __func__, tcpstates[tp->t_state], tlen);
2282                         free(s, M_TCPLOG);
2283                 }
2284                 tp = tcp_close(tp);
2285                 TCPSTAT_INC(tcps_rcvafterclose);
2286                 rstreason = BANDLIM_UNLIMITED;
2287                 goto dropwithreset;
2288         }
2289
2290         /*
2291          * If segment ends after window, drop trailing data
2292          * (and PUSH and FIN); if nothing left, just ACK.
2293          */
2294         todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2295         if (todrop > 0) {
2296                 TCPSTAT_INC(tcps_rcvpackafterwin);
2297                 if (todrop >= tlen) {
2298                         TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
2299                         /*
2300                          * If window is closed can only take segments at
2301                          * window edge, and have to drop data and PUSH from
2302                          * incoming segments.  Continue processing, but
2303                          * remember to ack.  Otherwise, drop segment
2304                          * and ack.
2305                          */
2306                         if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2307                                 tp->t_flags |= TF_ACKNOW;
2308                                 TCPSTAT_INC(tcps_rcvwinprobe);
2309                         } else
2310                                 goto dropafterack;
2311                 } else
2312                         TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
2313                 m_adj(m, -todrop);
2314                 tlen -= todrop;
2315                 thflags &= ~(TH_PUSH|TH_FIN);
2316         }
2317
2318         /*
2319          * If last ACK falls within this segment's sequence numbers,
2320          * record its timestamp.
2321          * NOTE: 
2322          * 1) That the test incorporates suggestions from the latest
2323          *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
2324          * 2) That updating only on newer timestamps interferes with
2325          *    our earlier PAWS tests, so this check should be solely
2326          *    predicated on the sequence space of this segment.
2327          * 3) That we modify the segment boundary check to be 
2328          *        Last.ACK.Sent <= SEG.SEQ + SEG.Len  
2329          *    instead of RFC1323's
2330          *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
2331          *    This modified check allows us to overcome RFC1323's
2332          *    limitations as described in Stevens TCP/IP Illustrated
2333          *    Vol. 2 p.869. In such cases, we can still calculate the
2334          *    RTT correctly when RCV.NXT == Last.ACK.Sent.
2335          */
2336         if ((to.to_flags & TOF_TS) != 0 &&
2337             SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2338             SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2339                 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2340                 tp->ts_recent_age = tcp_ts_getticks();
2341                 tp->ts_recent = to.to_tsval;
2342         }
2343
2344         /*
2345          * If a SYN is in the window, then this is an
2346          * error and we send an RST and drop the connection.
2347          */
2348         if (thflags & TH_SYN) {
2349                 KASSERT(ti_locked == TI_WLOCKED,
2350                     ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
2351                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2352
2353                 tp = tcp_drop(tp, ECONNRESET);
2354                 rstreason = BANDLIM_UNLIMITED;
2355                 goto drop;
2356         }
2357
2358         /*
2359          * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
2360          * flag is on (half-synchronized state), then queue data for
2361          * later processing; else drop segment and return.
2362          */
2363         if ((thflags & TH_ACK) == 0) {
2364                 if (tp->t_state == TCPS_SYN_RECEIVED ||
2365                     (tp->t_flags & TF_NEEDSYN)) {
2366 #ifdef TCP_RFC7413
2367                         if (tp->t_state == TCPS_SYN_RECEIVED &&
2368                             tp->t_flags & TF_FASTOPEN) {
2369                                 tp->snd_wnd = tiwin;
2370                                 cc_conn_init(tp);
2371                         }
2372 #endif
2373                         goto step6;
2374                 } else if (tp->t_flags & TF_ACKNOW)
2375                         goto dropafterack;
2376                 else
2377                         goto drop;
2378         }
2379
2380         /*
2381          * Ack processing.
2382          */
2383         switch (tp->t_state) {
2384
2385         /*
2386          * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2387          * ESTABLISHED state and continue processing.
2388          * The ACK was checked above.
2389          */
2390         case TCPS_SYN_RECEIVED:
2391
2392                 TCPSTAT_INC(tcps_connects);
2393                 soisconnected(so);
2394                 /* Do window scaling? */
2395                 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2396                         (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2397                         tp->rcv_scale = tp->request_r_scale;
2398                         tp->snd_wnd = tiwin;
2399                 }
2400                 /*
2401                  * Make transitions:
2402                  *      SYN-RECEIVED  -> ESTABLISHED
2403                  *      SYN-RECEIVED* -> FIN-WAIT-1
2404                  */
2405                 tp->t_starttime = ticks;
2406                 if (tp->t_flags & TF_NEEDFIN) {
2407                         tcp_state_change(tp, TCPS_FIN_WAIT_1);
2408                         tp->t_flags &= ~TF_NEEDFIN;
2409                 } else {
2410                         tcp_state_change(tp, TCPS_ESTABLISHED);
2411                         TCP_PROBE5(accept__established, NULL, tp,
2412                             mtod(m, const char *), tp, th);
2413 #ifdef TCP_RFC7413
2414                         if (tp->t_tfo_pending) {
2415                                 tcp_fastopen_decrement_counter(tp->t_tfo_pending);
2416                                 tp->t_tfo_pending = NULL;
2417
2418                                 /*
2419                                  * Account for the ACK of our SYN prior to
2420                                  * regular ACK processing below.
2421                                  */ 
2422                                 tp->snd_una++;
2423                         }
2424                         /*
2425                          * TFO connections call cc_conn_init() during SYN
2426                          * processing.  Calling it again here for such
2427                          * connections is not harmless as it would undo the
2428                          * snd_cwnd reduction that occurs when a TFO SYN|ACK
2429                          * is retransmitted.
2430                          */
2431                         if (!(tp->t_flags & TF_FASTOPEN))
2432 #endif
2433                                 cc_conn_init(tp);
2434                         tcp_timer_activate(tp, TT_KEEP, TP_KEEPIDLE(tp));
2435                 }
2436                 /*
2437                  * If segment contains data or ACK, will call tcp_reass()
2438                  * later; if not, do so now to pass queued data to user.
2439                  */
2440                 if (tlen == 0 && (thflags & TH_FIN) == 0)
2441                         (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2442                             (struct mbuf *)0);
2443                 tp->snd_wl1 = th->th_seq - 1;
2444                 /* FALLTHROUGH */
2445
2446         /*
2447          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2448          * ACKs.  If the ack is in the range
2449          *      tp->snd_una < th->th_ack <= tp->snd_max
2450          * then advance tp->snd_una to th->th_ack and drop
2451          * data from the retransmission queue.  If this ACK reflects
2452          * more up to date window information we update our window information.
2453          */
2454         case TCPS_ESTABLISHED:
2455         case TCPS_FIN_WAIT_1:
2456         case TCPS_FIN_WAIT_2:
2457         case TCPS_CLOSE_WAIT:
2458         case TCPS_CLOSING:
2459         case TCPS_LAST_ACK:
2460                 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2461                         TCPSTAT_INC(tcps_rcvacktoomuch);
2462                         goto dropafterack;
2463                 }
2464                 if ((tp->t_flags & TF_SACK_PERMIT) &&
2465                     ((to.to_flags & TOF_SACK) ||
2466                      !TAILQ_EMPTY(&tp->snd_holes)))
2467                         sack_changed = tcp_sack_doack(tp, &to, th->th_ack);
2468                 else
2469                         /*
2470                          * Reset the value so that previous (valid) value
2471                          * from the last ack with SACK doesn't get used.
2472                          */
2473                         tp->sackhint.sacked_bytes = 0;
2474
2475                 /* Run HHOOK_TCP_ESTABLISHED_IN helper hooks. */
2476                 hhook_run_tcp_est_in(tp, th, &to);
2477
2478                 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2479                         if (tlen == 0 &&
2480                             (tiwin == tp->snd_wnd ||
2481                             (tp->t_flags & TF_SACK_PERMIT))) {
2482                                 TCPSTAT_INC(tcps_rcvdupack);
2483                                 /*
2484                                  * If we have outstanding data (other than
2485                                  * a window probe), this is a completely
2486                                  * duplicate ack (ie, window info didn't
2487                                  * change), the ack is the biggest we've
2488                                  * seen and we've seen exactly our rexmt
2489                                  * threshhold of them, assume a packet
2490                                  * has been dropped and retransmit it.
2491                                  * Kludge snd_nxt & the congestion
2492                                  * window so we send only this one
2493                                  * packet.
2494                                  *
2495                                  * We know we're losing at the current
2496                                  * window size so do congestion avoidance
2497                                  * (set ssthresh to half the current window
2498                                  * and pull our congestion window back to
2499                                  * the new ssthresh).
2500                                  *
2501                                  * Dup acks mean that packets have left the
2502                                  * network (they're now cached at the receiver)
2503                                  * so bump cwnd by the amount in the receiver
2504                                  * to keep a constant cwnd packets in the
2505                                  * network.
2506                                  *
2507                                  * When using TCP ECN, notify the peer that
2508                                  * we reduced the cwnd.
2509                                  */
2510                                 /*
2511                                  * Following 2 kinds of acks should not affect
2512                                  * dupack counting:
2513                                  * 1) Old acks
2514                                  * 2) Acks with SACK but without any new SACK
2515                                  * information in them. These could result from
2516                                  * any anomaly in the network like a switch
2517                                  * duplicating packets or a possible DoS attack.
2518                                  */
2519                                 if (th->th_ack != tp->snd_una ||
2520                                     ((tp->t_flags & TF_SACK_PERMIT) &&
2521                                     !sack_changed))
2522                                         break;
2523                                 else if (!tcp_timer_active(tp, TT_REXMT))
2524                                         tp->t_dupacks = 0;
2525                                 else if (++tp->t_dupacks > tcprexmtthresh ||
2526                                      IN_FASTRECOVERY(tp->t_flags)) {
2527                                         cc_ack_received(tp, th, CC_DUPACK);
2528                                         if ((tp->t_flags & TF_SACK_PERMIT) &&
2529                                             IN_FASTRECOVERY(tp->t_flags)) {
2530                                                 int awnd;
2531                                                 
2532                                                 /*
2533                                                  * Compute the amount of data in flight first.
2534                                                  * We can inject new data into the pipe iff 
2535                                                  * we have less than 1/2 the original window's
2536                                                  * worth of data in flight.
2537                                                  */
2538                                                 if (V_tcp_do_rfc6675_pipe)
2539                                                         awnd = tcp_compute_pipe(tp);
2540                                                 else
2541                                                         awnd = (tp->snd_nxt - tp->snd_fack) +
2542                                                                 tp->sackhint.sack_bytes_rexmit;
2543
2544                                                 if (awnd < tp->snd_ssthresh) {
2545                                                         tp->snd_cwnd += tp->t_maxseg;
2546                                                         if (tp->snd_cwnd > tp->snd_ssthresh)
2547                                                                 tp->snd_cwnd = tp->snd_ssthresh;
2548                                                 }
2549                                         } else
2550                                                 tp->snd_cwnd += tp->t_maxseg;
2551                                         if ((thflags & TH_FIN) &&
2552                                             (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2553                                                 /* 
2554                                                  * If its a fin we need to process
2555                                                  * it to avoid a race where both
2556                                                  * sides enter FIN-WAIT and send FIN|ACK
2557                                                  * at the same time.
2558                                                  */
2559                                                 break;
2560                                         }
2561                                         (void) tcp_output(tp);
2562                                         goto drop;
2563                                 } else if (tp->t_dupacks == tcprexmtthresh) {
2564                                         tcp_seq onxt = tp->snd_nxt;
2565
2566                                         /*
2567                                          * If we're doing sack, check to
2568                                          * see if we're already in sack
2569                                          * recovery. If we're not doing sack,
2570                                          * check to see if we're in newreno
2571                                          * recovery.
2572                                          */
2573                                         if (tp->t_flags & TF_SACK_PERMIT) {
2574                                                 if (IN_FASTRECOVERY(tp->t_flags)) {
2575                                                         tp->t_dupacks = 0;
2576                                                         break;
2577                                                 }
2578                                         } else {
2579                                                 if (SEQ_LEQ(th->th_ack,
2580                                                     tp->snd_recover)) {
2581                                                         tp->t_dupacks = 0;
2582                                                         break;
2583                                                 }
2584                                         }
2585                                         /* Congestion signal before ack. */
2586                                         cc_cong_signal(tp, th, CC_NDUPACK);
2587                                         cc_ack_received(tp, th, CC_DUPACK);
2588                                         tcp_timer_activate(tp, TT_REXMT, 0);
2589                                         tp->t_rtttime = 0;
2590                                         if (tp->t_flags & TF_SACK_PERMIT) {
2591                                                 TCPSTAT_INC(
2592                                                     tcps_sack_recovery_episode);
2593                                                 tp->sack_newdata = tp->snd_nxt;
2594                                                 tp->snd_cwnd = tp->t_maxseg;
2595                                                 (void) tcp_output(tp);
2596                                                 goto drop;
2597                                         }
2598                                         tp->snd_nxt = th->th_ack;
2599                                         tp->snd_cwnd = tp->t_maxseg;
2600                                         if ((thflags & TH_FIN) &&
2601                                             (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2602                                                 /* 
2603                                                  * If its a fin we need to process
2604                                                  * it to avoid a race where both
2605                                                  * sides enter FIN-WAIT and send FIN|ACK
2606                                                  * at the same time.
2607                                                  */
2608                                                 break;
2609                                         }
2610                                         (void) tcp_output(tp);
2611                                         KASSERT(tp->snd_limited <= 2,
2612                                             ("%s: tp->snd_limited too big",
2613                                             __func__));
2614                                         tp->snd_cwnd = tp->snd_ssthresh +
2615                                              tp->t_maxseg *
2616                                              (tp->t_dupacks - tp->snd_limited);
2617                                         if (SEQ_GT(onxt, tp->snd_nxt))
2618                                                 tp->snd_nxt = onxt;
2619                                         goto drop;
2620                                 } else if (V_tcp_do_rfc3042) {
2621                                         /*
2622                                          * Process first and second duplicate
2623                                          * ACKs. Each indicates a segment
2624                                          * leaving the network, creating room
2625                                          * for more. Make sure we can send a
2626                                          * packet on reception of each duplicate
2627                                          * ACK by increasing snd_cwnd by one
2628                                          * segment. Restore the original
2629                                          * snd_cwnd after packet transmission.
2630                                          */
2631                                         cc_ack_received(tp, th, CC_DUPACK);
2632                                         u_long oldcwnd = tp->snd_cwnd;
2633                                         tcp_seq oldsndmax = tp->snd_max;
2634                                         u_int sent;
2635                                         int avail;
2636
2637                                         KASSERT(tp->t_dupacks == 1 ||
2638                                             tp->t_dupacks == 2,
2639                                             ("%s: dupacks not 1 or 2",
2640                                             __func__));
2641                                         if (tp->t_dupacks == 1)
2642                                                 tp->snd_limited = 0;
2643                                         tp->snd_cwnd =
2644                                             (tp->snd_nxt - tp->snd_una) +
2645                                             (tp->t_dupacks - tp->snd_limited) *
2646                                             tp->t_maxseg;
2647                                         if ((thflags & TH_FIN) &&
2648                                             (TCPS_HAVERCVDFIN(tp->t_state) == 0)) {
2649                                                 /* 
2650                                                  * If its a fin we need to process
2651                                                  * it to avoid a race where both
2652                                                  * sides enter FIN-WAIT and send FIN|ACK
2653                                                  * at the same time.
2654                                                  */
2655                                                 break;
2656                                         }
2657                                         /*
2658                                          * Only call tcp_output when there
2659                                          * is new data available to be sent.
2660                                          * Otherwise we would send pure ACKs.
2661                                          */
2662                                         SOCKBUF_LOCK(&so->so_snd);
2663                                         avail = so->so_snd.sb_cc -
2664                                             (tp->snd_nxt - tp->snd_una);
2665                                         SOCKBUF_UNLOCK(&so->so_snd);
2666                                         if (avail > 0)
2667                                                 (void) tcp_output(tp);
2668                                         sent = tp->snd_max - oldsndmax;
2669                                         if (sent > tp->t_maxseg) {
2670                                                 KASSERT((tp->t_dupacks == 2 &&
2671                                                     tp->snd_limited == 0) ||
2672                                                    (sent == tp->t_maxseg + 1 &&
2673                                                     tp->t_flags & TF_SENTFIN),
2674                                                     ("%s: sent too much",
2675                                                     __func__));
2676                                                 tp->snd_limited = 2;
2677                                         } else if (sent > 0)
2678                                                 ++tp->snd_limited;
2679                                         tp->snd_cwnd = oldcwnd;
2680                                         goto drop;
2681                                 }
2682                         }
2683                         break;
2684                 } else {
2685                         /*
2686                          * This ack is advancing the left edge, reset the
2687                          * counter.
2688                          */
2689                         tp->t_dupacks = 0;
2690                         /*
2691                          * If this ack also has new SACK info, increment the
2692                          * counter as per rfc6675.
2693                          */
2694                         if ((tp->t_flags & TF_SACK_PERMIT) && sack_changed)
2695                                 tp->t_dupacks++;
2696                 }
2697
2698                 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2699                     ("%s: th_ack <= snd_una", __func__));
2700
2701                 /*
2702                  * If the congestion window was inflated to account
2703                  * for the other side's cached packets, retract it.
2704                  */
2705                 if (IN_FASTRECOVERY(tp->t_flags)) {
2706                         if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2707                                 if (tp->t_flags & TF_SACK_PERMIT)
2708                                         tcp_sack_partialack(tp, th);
2709                                 else
2710                                         tcp_newreno_partial_ack(tp, th);
2711                         } else
2712                                 cc_post_recovery(tp, th);
2713                 }
2714                 /*
2715                  * If we reach this point, ACK is not a duplicate,
2716                  *     i.e., it ACKs something we sent.
2717                  */
2718                 if (tp->t_flags & TF_NEEDSYN) {
2719                         /*
2720                          * T/TCP: Connection was half-synchronized, and our
2721                          * SYN has been ACK'd (so connection is now fully
2722                          * synchronized).  Go to non-starred state,
2723                          * increment snd_una for ACK of SYN, and check if
2724                          * we can do window scaling.
2725                          */
2726                         tp->t_flags &= ~TF_NEEDSYN;
2727                         tp->snd_una++;
2728                         /* Do window scaling? */
2729                         if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2730                                 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2731                                 tp->rcv_scale = tp->request_r_scale;
2732                                 /* Send window already scaled. */
2733                         }
2734                 }
2735
2736 process_ACK:
2737                 INP_WLOCK_ASSERT(tp->t_inpcb);
2738
2739                 acked = BYTES_THIS_ACK(tp, th);
2740                 KASSERT(acked >= 0, ("%s: acked unexepectedly negative "
2741                     "(tp->snd_una=%u, th->th_ack=%u, tp=%p, m=%p)", __func__,
2742                     tp->snd_una, th->th_ack, tp, m));
2743                 TCPSTAT_INC(tcps_rcvackpack);
2744                 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2745
2746                 /*
2747                  * If we just performed our first retransmit, and the ACK
2748                  * arrives within our recovery window, then it was a mistake
2749                  * to do the retransmit in the first place.  Recover our
2750                  * original cwnd and ssthresh, and proceed to transmit where
2751                  * we left off.
2752                  */
2753                 if (tp->t_rxtshift == 1 && tp->t_flags & TF_PREVVALID &&
2754                     (int)(ticks - tp->t_badrxtwin) < 0)
2755                         cc_cong_signal(tp, th, CC_RTO_ERR);
2756
2757                 /*
2758                  * If we have a timestamp reply, update smoothed
2759                  * round trip time.  If no timestamp is present but
2760                  * transmit timer is running and timed sequence
2761                  * number was acked, update smoothed round trip time.
2762                  * Since we now have an rtt measurement, cancel the
2763                  * timer backoff (cf., Phil Karn's retransmit alg.).
2764                  * Recompute the initial retransmit timer.
2765                  *
2766                  * Some boxes send broken timestamp replies
2767                  * during the SYN+ACK phase, ignore
2768                  * timestamps of 0 or we could calculate a
2769                  * huge RTT and blow up the retransmit timer.
2770                  */
2771                 if ((to.to_flags & TOF_TS) != 0 && to.to_tsecr) {
2772                         u_int t;
2773
2774                         t = tcp_ts_getticks() - to.to_tsecr;
2775                         if (!tp->t_rttlow || tp->t_rttlow > t)
2776                                 tp->t_rttlow = t;
2777                         tcp_xmit_timer(tp, TCP_TS_TO_TICKS(t) + 1);
2778                 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2779                         if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2780                                 tp->t_rttlow = ticks - tp->t_rtttime;
2781                         tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2782                 }
2783
2784                 /*
2785                  * If all outstanding data is acked, stop retransmit
2786                  * timer and remember to restart (more output or persist).
2787                  * If there is more data to be acked, restart retransmit
2788                  * timer, using current (possibly backed-off) value.
2789                  */
2790                 if (th->th_ack == tp->snd_max) {
2791                         tcp_timer_activate(tp, TT_REXMT, 0);
2792                         needoutput = 1;
2793                 } else if (!tcp_timer_active(tp, TT_PERSIST))
2794                         tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2795
2796                 /*
2797                  * If no data (only SYN) was ACK'd,
2798                  *    skip rest of ACK processing.
2799                  */
2800                 if (acked == 0)
2801                         goto step6;
2802
2803                 /*
2804                  * Let the congestion control algorithm update congestion
2805                  * control related information. This typically means increasing
2806                  * the congestion window.
2807                  */
2808                 cc_ack_received(tp, th, CC_ACK);
2809
2810                 SOCKBUF_LOCK(&so->so_snd);
2811                 if (acked > so->so_snd.sb_cc) {
2812                         if (tp->snd_wnd >= so->so_snd.sb_cc)
2813                                 tp->snd_wnd -= so->so_snd.sb_cc;
2814                         else
2815                                 tp->snd_wnd = 0;
2816                         mfree = sbcut_locked(&so->so_snd,
2817                             (int)so->so_snd.sb_cc);
2818                         ourfinisacked = 1;
2819                 } else {
2820                         mfree = sbcut_locked(&so->so_snd, acked);
2821                         if (tp->snd_wnd >= (u_long) acked)
2822                                 tp->snd_wnd -= acked;
2823                         else
2824                                 tp->snd_wnd = 0;
2825                         ourfinisacked = 0;
2826                 }
2827                 /* NB: sowwakeup_locked() does an implicit unlock. */
2828                 sowwakeup_locked(so);
2829                 m_freem(mfree);
2830                 /* Detect una wraparound. */
2831                 if (!IN_RECOVERY(tp->t_flags) &&
2832                     SEQ_GT(tp->snd_una, tp->snd_recover) &&
2833                     SEQ_LEQ(th->th_ack, tp->snd_recover))
2834                         tp->snd_recover = th->th_ack - 1;
2835                 /* XXXLAS: Can this be moved up into cc_post_recovery? */
2836                 if (IN_RECOVERY(tp->t_flags) &&
2837                     SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2838                         EXIT_RECOVERY(tp->t_flags);
2839                 }
2840                 tp->snd_una = th->th_ack;
2841                 if (tp->t_flags & TF_SACK_PERMIT) {
2842                         if (SEQ_GT(tp->snd_una, tp->snd_recover))
2843                                 tp->snd_recover = tp->snd_una;
2844                 }
2845                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2846                         tp->snd_nxt = tp->snd_una;
2847
2848                 switch (tp->t_state) {
2849
2850                 /*
2851                  * In FIN_WAIT_1 STATE in addition to the processing
2852                  * for the ESTABLISHED state if our FIN is now acknowledged
2853                  * then enter FIN_WAIT_2.
2854                  */
2855                 case TCPS_FIN_WAIT_1:
2856                         if (ourfinisacked) {
2857                                 /*
2858                                  * If we can't receive any more
2859                                  * data, then closing user can proceed.
2860                                  * Starting the timer is contrary to the
2861                                  * specification, but if we don't get a FIN
2862                                  * we'll hang forever.
2863                                  *
2864                                  * XXXjl:
2865                                  * we should release the tp also, and use a
2866                                  * compressed state.
2867                                  */
2868                                 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2869                                         soisdisconnected(so);
2870                                         tcp_timer_activate(tp, TT_2MSL,
2871                                             (tcp_fast_finwait2_recycle ?
2872                                             tcp_finwait2_timeout :
2873                                             TP_MAXIDLE(tp)));
2874                                 }
2875                                 tcp_state_change(tp, TCPS_FIN_WAIT_2);
2876                         }
2877                         break;
2878
2879                 /*
2880                  * In CLOSING STATE in addition to the processing for
2881                  * the ESTABLISHED state if the ACK acknowledges our FIN
2882                  * then enter the TIME-WAIT state, otherwise ignore
2883                  * the segment.
2884                  */
2885                 case TCPS_CLOSING:
2886                         if (ourfinisacked) {
2887                                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2888                                 tcp_twstart(tp);
2889                                 INP_INFO_WUNLOCK(&V_tcbinfo);
2890                                 m_freem(m);
2891                                 return;
2892                         }
2893                         break;
2894
2895                 /*
2896                  * In LAST_ACK, we may still be waiting for data to drain
2897                  * and/or to be acked, as well as for the ack of our FIN.
2898                  * If our FIN is now acknowledged, delete the TCB,
2899                  * enter the closed state and return.
2900                  */
2901                 case TCPS_LAST_ACK:
2902                         if (ourfinisacked) {
2903                                 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2904                                 tp = tcp_close(tp);
2905                                 goto drop;
2906                         }
2907                         break;
2908                 }
2909         }
2910
2911 step6:
2912         INP_WLOCK_ASSERT(tp->t_inpcb);
2913
2914         /*
2915          * Update window information.
2916          * Don't look at window if no ACK: TAC's send garbage on first SYN.
2917          */
2918         if ((thflags & TH_ACK) &&
2919             (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2920             (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2921              (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2922                 /* keep track of pure window updates */
2923                 if (tlen == 0 &&
2924                     tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2925                         TCPSTAT_INC(tcps_rcvwinupd);
2926                 tp->snd_wnd = tiwin;
2927                 tp->snd_wl1 = th->th_seq;
2928                 tp->snd_wl2 = th->th_ack;
2929                 if (tp->snd_wnd > tp->max_sndwnd)
2930                         tp->max_sndwnd = tp->snd_wnd;
2931                 needoutput = 1;
2932         }
2933
2934         /*
2935          * Process segments with URG.
2936          */
2937         if ((thflags & TH_URG) && th->th_urp &&
2938             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2939                 /*
2940                  * This is a kludge, but if we receive and accept
2941                  * random urgent pointers, we'll crash in
2942                  * soreceive.  It's hard to imagine someone
2943                  * actually wanting to send this much urgent data.
2944                  */
2945                 SOCKBUF_LOCK(&so->so_rcv);
2946                 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2947                         th->th_urp = 0;                 /* XXX */
2948                         thflags &= ~TH_URG;             /* XXX */
2949                         SOCKBUF_UNLOCK(&so->so_rcv);    /* XXX */
2950                         goto dodata;                    /* XXX */
2951                 }
2952                 /*
2953                  * If this segment advances the known urgent pointer,
2954                  * then mark the data stream.  This should not happen
2955                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2956                  * a FIN has been received from the remote side.
2957                  * In these states we ignore the URG.
2958                  *
2959                  * According to RFC961 (Assigned Protocols),
2960                  * the urgent pointer points to the last octet
2961                  * of urgent data.  We continue, however,
2962                  * to consider it to indicate the first octet
2963                  * of data past the urgent section as the original
2964                  * spec states (in one of two places).
2965                  */
2966                 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2967                         tp->rcv_up = th->th_seq + th->th_urp;
2968                         so->so_oobmark = so->so_rcv.sb_cc +
2969                             (tp->rcv_up - tp->rcv_nxt) - 1;
2970                         if (so->so_oobmark == 0)
2971                                 so->so_rcv.sb_state |= SBS_RCVATMARK;
2972                         sohasoutofband(so);
2973                         tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2974                 }
2975                 SOCKBUF_UNLOCK(&so->so_rcv);
2976                 /*
2977                  * Remove out of band data so doesn't get presented to user.
2978                  * This can happen independent of advancing the URG pointer,
2979                  * but if two URG's are pending at once, some out-of-band
2980                  * data may creep in... ick.
2981                  */
2982                 if (th->th_urp <= (u_long)tlen &&
2983                     !(so->so_options & SO_OOBINLINE)) {
2984                         /* hdr drop is delayed */
2985                         tcp_pulloutofband(so, th, m, drop_hdrlen);
2986                 }
2987         } else {
2988                 /*
2989                  * If no out of band data is expected,
2990                  * pull receive urgent pointer along
2991                  * with the receive window.
2992                  */
2993                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2994                         tp->rcv_up = tp->rcv_nxt;
2995         }
2996 dodata:                                                 /* XXX */
2997         INP_WLOCK_ASSERT(tp->t_inpcb);
2998
2999         /*
3000          * Process the segment text, merging it into the TCP sequencing queue,
3001          * and arranging for acknowledgment of receipt if necessary.
3002          * This process logically involves adjusting tp->rcv_wnd as data
3003          * is presented to the user (this happens in tcp_usrreq.c,
3004          * case PRU_RCVD).  If a FIN has already been received on this
3005          * connection then we just ignore the text.
3006          */
3007         tfo_syn = ((tp->t_state == TCPS_SYN_RECEIVED) &&
3008                    (tp->t_flags & TF_FASTOPEN));
3009         if ((tlen || (thflags & TH_FIN) || tfo_syn) &&
3010             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3011                 tcp_seq save_start = th->th_seq;
3012
3013                 m_adj(m, drop_hdrlen);  /* delayed header drop */
3014                 /*
3015                  * Insert segment which includes th into TCP reassembly queue
3016                  * with control block tp.  Set thflags to whether reassembly now
3017                  * includes a segment with FIN.  This handles the common case
3018                  * inline (segment is the next to be received on an established
3019                  * connection, and the queue is empty), avoiding linkage into
3020                  * and removal from the queue and repetition of various
3021                  * conversions.
3022                  * Set DELACK for segments received in order, but ack
3023                  * immediately when segments are out of order (so
3024                  * fast retransmit can work).
3025                  */
3026                 if (th->th_seq == tp->rcv_nxt &&
3027                     LIST_EMPTY(&tp->t_segq) &&
3028                     (TCPS_HAVEESTABLISHED(tp->t_state) ||
3029                      tfo_syn)) {
3030                         if (DELAY_ACK(tp, tlen) || tfo_syn)
3031                                 tp->t_flags |= TF_DELACK;
3032                         else
3033                                 tp->t_flags |= TF_ACKNOW;
3034                         tp->rcv_nxt += tlen;
3035                         thflags = th->th_flags & TH_FIN;
3036                         TCPSTAT_INC(tcps_rcvpack);
3037                         TCPSTAT_ADD(tcps_rcvbyte, tlen);
3038                         ND6_HINT(tp);
3039                         SOCKBUF_LOCK(&so->so_rcv);
3040                         if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
3041                                 m_freem(m);
3042                         else
3043                                 sbappendstream_locked(&so->so_rcv, m);
3044                         /* NB: sorwakeup_locked() does an implicit unlock. */
3045                         sorwakeup_locked(so);
3046                 } else {
3047                         /*
3048                          * XXX: Due to the header drop above "th" is
3049                          * theoretically invalid by now.  Fortunately
3050                          * m_adj() doesn't actually frees any mbufs
3051                          * when trimming from the head.
3052                          */
3053                         thflags = tcp_reass(tp, th, &tlen, m);
3054                         tp->t_flags |= TF_ACKNOW;
3055                 }
3056                 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
3057                         tcp_update_sack_list(tp, save_start, save_start + tlen);
3058 #if 0
3059                 /*
3060                  * Note the amount of data that peer has sent into
3061                  * our window, in order to estimate the sender's
3062                  * buffer size.
3063                  * XXX: Unused.
3064                  */
3065                 if (SEQ_GT(tp->rcv_adv, tp->rcv_nxt))
3066                         len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
3067                 else
3068                         len = so->so_rcv.sb_hiwat;
3069 #endif
3070         } else {
3071                 m_freem(m);
3072                 thflags &= ~TH_FIN;
3073         }
3074
3075         /*
3076          * If FIN is received ACK the FIN and let the user know
3077          * that the connection is closing.
3078          */
3079         if (thflags & TH_FIN) {
3080                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
3081                         socantrcvmore(so);
3082                         /*
3083                          * If connection is half-synchronized
3084                          * (ie NEEDSYN flag on) then delay ACK,
3085                          * so it may be piggybacked when SYN is sent.
3086                          * Otherwise, since we received a FIN then no
3087                          * more input can be expected, send ACK now.
3088                          */
3089                         if (tp->t_flags & TF_NEEDSYN)
3090                                 tp->t_flags |= TF_DELACK;
3091                         else
3092                                 tp->t_flags |= TF_ACKNOW;
3093                         tp->rcv_nxt++;
3094                 }
3095                 switch (tp->t_state) {
3096
3097                 /*
3098                  * In SYN_RECEIVED and ESTABLISHED STATES
3099                  * enter the CLOSE_WAIT state.
3100                  */
3101                 case TCPS_SYN_RECEIVED:
3102                         tp->t_starttime = ticks;
3103                         /* FALLTHROUGH */
3104                 case TCPS_ESTABLISHED:
3105                         tcp_state_change(tp, TCPS_CLOSE_WAIT);
3106                         break;
3107
3108                 /*
3109                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
3110                  * enter the CLOSING state.
3111                  */
3112                 case TCPS_FIN_WAIT_1:
3113                         tcp_state_change(tp, TCPS_CLOSING);
3114                         break;
3115
3116                 /*
3117                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
3118                  * starting the time-wait timer, turning off the other
3119                  * standard timers.
3120                  */
3121                 case TCPS_FIN_WAIT_2:
3122                         INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
3123                         KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
3124                             "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
3125                             ti_locked));
3126
3127                         tcp_twstart(tp);
3128                         INP_INFO_WUNLOCK(&V_tcbinfo);
3129                         return;
3130                 }
3131         }
3132         if (ti_locked == TI_WLOCKED)
3133                 INP_INFO_WUNLOCK(&V_tcbinfo);
3134         ti_locked = TI_UNLOCKED;
3135
3136 #ifdef TCPDEBUG
3137         if (so->so_options & SO_DEBUG)
3138                 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3139                           &tcp_savetcp, 0);
3140 #endif
3141
3142         /*
3143          * Return any desired output.
3144          */
3145         if (needoutput || (tp->t_flags & TF_ACKNOW))
3146                 (void) tcp_output(tp);
3147
3148 check_delack:
3149         KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
3150             __func__, ti_locked));
3151         INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3152         INP_WLOCK_ASSERT(tp->t_inpcb);
3153
3154         if (tp->t_flags & TF_DELACK) {
3155                 tp->t_flags &= ~TF_DELACK;
3156                 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
3157         }
3158         INP_WUNLOCK(tp->t_inpcb);
3159         return;
3160
3161 dropafterack:
3162         /*
3163          * Generate an ACK dropping incoming segment if it occupies
3164          * sequence space, where the ACK reflects our state.
3165          *
3166          * We can now skip the test for the RST flag since all
3167          * paths to this code happen after packets containing
3168          * RST have been dropped.
3169          *
3170          * In the SYN-RECEIVED state, don't send an ACK unless the
3171          * segment we received passes the SYN-RECEIVED ACK test.
3172          * If it fails send a RST.  This breaks the loop in the
3173          * "LAND" DoS attack, and also prevents an ACK storm
3174          * between two listening ports that have been sent forged
3175          * SYN segments, each with the source address of the other.
3176          */
3177         if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3178             (SEQ_GT(tp->snd_una, th->th_ack) ||
3179              SEQ_GT(th->th_ack, tp->snd_max)) ) {
3180                 rstreason = BANDLIM_RST_OPENPORT;
3181                 goto dropwithreset;
3182         }
3183 #ifdef TCPDEBUG
3184         if (so->so_options & SO_DEBUG)
3185                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3186                           &tcp_savetcp, 0);
3187 #endif
3188         if (ti_locked == TI_WLOCKED)
3189                 INP_INFO_WUNLOCK(&V_tcbinfo);
3190         ti_locked = TI_UNLOCKED;
3191
3192         tp->t_flags |= TF_ACKNOW;
3193         (void) tcp_output(tp);
3194         INP_WUNLOCK(tp->t_inpcb);
3195         m_freem(m);
3196         return;
3197
3198 dropwithreset:
3199         if (ti_locked == TI_WLOCKED)
3200                 INP_INFO_WUNLOCK(&V_tcbinfo);
3201         ti_locked = TI_UNLOCKED;
3202
3203         if (tp != NULL) {
3204                 tcp_dropwithreset(m, th, tp, tlen, rstreason);
3205                 INP_WUNLOCK(tp->t_inpcb);
3206         } else
3207                 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
3208         return;
3209
3210 drop:
3211         if (ti_locked == TI_WLOCKED) {
3212                 INP_INFO_WUNLOCK(&V_tcbinfo);
3213                 ti_locked = TI_UNLOCKED;
3214         }
3215 #ifdef INVARIANTS
3216         else
3217                 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
3218 #endif
3219
3220         /*
3221          * Drop space held by incoming segment and return.
3222          */
3223 #ifdef TCPDEBUG
3224         if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3225                 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3226                           &tcp_savetcp, 0);
3227 #endif
3228         if (tp != NULL)
3229                 INP_WUNLOCK(tp->t_inpcb);
3230         m_freem(m);
3231 }
3232
3233 /*
3234  * Issue RST and make ACK acceptable to originator of segment.
3235  * The mbuf must still include the original packet header.
3236  * tp may be NULL.
3237  */
3238 static void
3239 tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
3240     int tlen, int rstreason)
3241 {
3242 #ifdef INET
3243         struct ip *ip;
3244 #endif
3245 #ifdef INET6
3246         struct ip6_hdr *ip6;
3247 #endif
3248
3249         if (tp != NULL) {
3250                 INP_WLOCK_ASSERT(tp->t_inpcb);
3251         }
3252
3253         /* Don't bother if destination was broadcast/multicast. */
3254         if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3255                 goto drop;
3256 #ifdef INET6
3257         if (mtod(m, struct ip *)->ip_v == 6) {
3258                 ip6 = mtod(m, struct ip6_hdr *);
3259                 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3260                     IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3261                         goto drop;
3262                 /* IPv6 anycast check is done at tcp6_input() */
3263         }
3264 #endif
3265 #if defined(INET) && defined(INET6)
3266         else
3267 #endif
3268 #ifdef INET
3269         {
3270                 ip = mtod(m, struct ip *);
3271                 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3272                     IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3273                     ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3274                     in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3275                         goto drop;
3276         }
3277 #endif
3278
3279         /* Perform bandwidth limiting. */
3280         if (badport_bandlim(rstreason) < 0)
3281                 goto drop;
3282
3283         /* tcp_respond consumes the mbuf chain. */
3284         if (th->th_flags & TH_ACK) {
3285                 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
3286                     th->th_ack, TH_RST);
3287         } else {
3288                 if (th->th_flags & TH_SYN)
3289                         tlen++;
3290                 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3291                     (tcp_seq)0, TH_RST|TH_ACK);
3292         }
3293         return;
3294 drop:
3295         m_freem(m);
3296 }
3297
3298 /*
3299  * Parse TCP options and place in tcpopt.
3300  */
3301 static void
3302 tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
3303 {
3304         int opt, optlen;
3305
3306         to->to_flags = 0;
3307         for (; cnt > 0; cnt -= optlen, cp += optlen) {
3308                 opt = cp[0];
3309                 if (opt == TCPOPT_EOL)
3310                         break;
3311                 if (opt == TCPOPT_NOP)
3312                         optlen = 1;
3313                 else {
3314                         if (cnt < 2)
3315                                 break;
3316                         optlen = cp[1];
3317                         if (optlen < 2 || optlen > cnt)
3318                                 break;
3319                 }
3320                 switch (opt) {
3321                 case TCPOPT_MAXSEG:
3322                         if (optlen != TCPOLEN_MAXSEG)
3323                                 continue;
3324                         if (!(flags & TO_SYN))
3325                                 continue;
3326                         to->to_flags |= TOF_MSS;
3327                         bcopy((char *)cp + 2,
3328                             (char *)&to->to_mss, sizeof(to->to_mss));
3329                         to->to_mss = ntohs(to->to_mss);
3330                         break;
3331                 case TCPOPT_WINDOW:
3332                         if (optlen != TCPOLEN_WINDOW)
3333                                 continue;
3334                         if (!(flags & TO_SYN))
3335                                 continue;
3336                         to->to_flags |= TOF_SCALE;
3337                         to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
3338                         break;
3339                 case TCPOPT_TIMESTAMP:
3340                         if (optlen != TCPOLEN_TIMESTAMP)
3341                                 continue;
3342                         to->to_flags |= TOF_TS;
3343                         bcopy((char *)cp + 2,
3344                             (char *)&to->to_tsval, sizeof(to->to_tsval));
3345                         to->to_tsval = ntohl(to->to_tsval);
3346                         bcopy((char *)cp + 6,
3347                             (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3348                         to->to_tsecr = ntohl(to->to_tsecr);
3349                         break;
3350 #ifdef TCP_SIGNATURE
3351                 /*
3352                  * XXX In order to reply to a host which has set the
3353                  * TCP_SIGNATURE option in its initial SYN, we have to
3354                  * record the fact that the option was observed here
3355                  * for the syncache code to perform the correct response.
3356                  */
3357                 case TCPOPT_SIGNATURE:
3358                         if (optlen != TCPOLEN_SIGNATURE)
3359                                 continue;
3360                         to->to_flags |= TOF_SIGNATURE;
3361                         to->to_signature = cp + 2;
3362                         break;
3363 #endif
3364                 case TCPOPT_SACK_PERMITTED:
3365                         if (optlen != TCPOLEN_SACK_PERMITTED)
3366                                 continue;
3367                         if (!(flags & TO_SYN))
3368                                 continue;
3369                         if (!V_tcp_do_sack)
3370                                 continue;
3371                         to->to_flags |= TOF_SACKPERM;
3372                         break;
3373                 case TCPOPT_SACK:
3374                         if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3375                                 continue;
3376                         if (flags & TO_SYN)
3377                                 continue;
3378                         to->to_flags |= TOF_SACK;
3379                         to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3380                         to->to_sacks = cp + 2;
3381                         TCPSTAT_INC(tcps_sack_rcv_blocks);
3382                         break;
3383 #ifdef TCP_RFC7413
3384                 case TCPOPT_FAST_OPEN:
3385                         if ((optlen != TCPOLEN_FAST_OPEN_EMPTY) &&
3386                             (optlen < TCPOLEN_FAST_OPEN_MIN) &&
3387                             (optlen > TCPOLEN_FAST_OPEN_MAX))
3388                                 continue;
3389                         if (!(flags & TO_SYN))
3390                                 continue;
3391                         if (!V_tcp_fastopen_enabled)
3392                                 continue;
3393                         to->to_flags |= TOF_FASTOPEN;
3394                         to->to_tfo_len = optlen - 2;
3395                         to->to_tfo_cookie = to->to_tfo_len ? cp + 2 : NULL;
3396                         break;
3397 #endif
3398                 default:
3399                         continue;
3400                 }
3401         }
3402 }
3403
3404 /*
3405  * Pull out of band byte out of a segment so
3406  * it doesn't appear in the user's data queue.
3407  * It is still reflected in the segment length for
3408  * sequencing purposes.
3409  */
3410 static void
3411 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
3412     int off)
3413 {
3414         int cnt = off + th->th_urp - 1;
3415
3416         while (cnt >= 0) {
3417                 if (m->m_len > cnt) {
3418                         char *cp = mtod(m, caddr_t) + cnt;
3419                         struct tcpcb *tp = sototcpcb(so);
3420
3421                         INP_WLOCK_ASSERT(tp->t_inpcb);
3422
3423                         tp->t_iobc = *cp;
3424                         tp->t_oobflags |= TCPOOB_HAVEDATA;
3425                         bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3426                         m->m_len--;
3427                         if (m->m_flags & M_PKTHDR)
3428                                 m->m_pkthdr.len--;
3429                         return;
3430                 }
3431                 cnt -= m->m_len;
3432                 m = m->m_next;
3433                 if (m == NULL)
3434                         break;
3435         }
3436         panic("tcp_pulloutofband");
3437 }
3438
3439 /*
3440  * Collect new round-trip time estimate
3441  * and update averages and current timeout.
3442  */
3443 static void
3444 tcp_xmit_timer(struct tcpcb *tp, int rtt)
3445 {
3446         int delta;
3447
3448         INP_WLOCK_ASSERT(tp->t_inpcb);
3449
3450         TCPSTAT_INC(tcps_rttupdated);
3451         tp->t_rttupdated++;
3452         if (tp->t_srtt != 0) {
3453                 /*
3454                  * srtt is stored as fixed point with 5 bits after the
3455                  * binary point (i.e., scaled by 8).  The following magic
3456                  * is equivalent to the smoothing algorithm in rfc793 with
3457                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3458                  * point).  Adjust rtt to origin 0.
3459                  */
3460                 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3461                         - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3462
3463                 if ((tp->t_srtt += delta) <= 0)
3464                         tp->t_srtt = 1;
3465
3466                 /*
3467                  * We accumulate a smoothed rtt variance (actually, a
3468                  * smoothed mean difference), then set the retransmit
3469                  * timer to smoothed rtt + 4 times the smoothed variance.
3470                  * rttvar is stored as fixed point with 4 bits after the
3471                  * binary point (scaled by 16).  The following is
3472                  * equivalent to rfc793 smoothing with an alpha of .75
3473                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
3474                  * rfc793's wired-in beta.
3475                  */
3476                 if (delta < 0)
3477                         delta = -delta;
3478                 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3479                 if ((tp->t_rttvar += delta) <= 0)
3480                         tp->t_rttvar = 1;
3481                 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3482                     tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3483         } else {
3484                 /*
3485                  * No rtt measurement yet - use the unsmoothed rtt.
3486                  * Set the variance to half the rtt (so our first
3487                  * retransmit happens at 3*rtt).
3488                  */
3489                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3490                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3491                 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3492         }
3493         tp->t_rtttime = 0;
3494         tp->t_rxtshift = 0;
3495
3496         /*
3497          * the retransmit should happen at rtt + 4 * rttvar.
3498          * Because of the way we do the smoothing, srtt and rttvar
3499          * will each average +1/2 tick of bias.  When we compute
3500          * the retransmit timer, we want 1/2 tick of rounding and
3501          * 1 extra tick because of +-1/2 tick uncertainty in the
3502          * firing of the timer.  The bias will give us exactly the
3503          * 1.5 tick we need.  But, because the bias is
3504          * statistical, we have to test that we don't drop below
3505          * the minimum feasible timer (which is 2 ticks).
3506          */
3507         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3508                       max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3509
3510         /*
3511          * We received an ack for a packet that wasn't retransmitted;
3512          * it is probably safe to discard any error indications we've
3513          * received recently.  This isn't quite right, but close enough
3514          * for now (a route might have failed after we sent a segment,
3515          * and the return path might not be symmetrical).
3516          */
3517         tp->t_softerror = 0;
3518 }
3519
3520 /*
3521  * Determine a reasonable value for maxseg size.
3522  * If the route is known, check route for mtu.
3523  * If none, use an mss that can be handled on the outgoing interface
3524  * without forcing IP to fragment.  If no route is found, route has no mtu,
3525  * or the destination isn't local, use a default, hopefully conservative
3526  * size (usually 512 or the default IP max size, but no more than the mtu
3527  * of the interface), as we can't discover anything about intervening
3528  * gateways or networks.  We also initialize the congestion/slow start
3529  * window to be a single segment if the destination isn't local.
3530  * While looking at the routing entry, we also initialize other path-dependent
3531  * parameters from pre-set or cached values in the routing entry.
3532  *
3533  * Also take into account the space needed for options that we
3534  * send regularly.  Make maxseg shorter by that amount to assure
3535  * that we can send maxseg amount of data even when the options
3536  * are present.  Store the upper limit of the length of options plus
3537  * data in maxopd.
3538  *
3539  * NOTE that this routine is only called when we process an incoming
3540  * segment, or an ICMP need fragmentation datagram. Outgoing SYN/ACK MSS
3541  * settings are handled in tcp_mssopt().
3542  */
3543 void
3544 tcp_mss_update(struct tcpcb *tp, int offer, int mtuoffer,
3545     struct hc_metrics_lite *metricptr, struct tcp_ifcap *cap)
3546 {
3547         int mss = 0;
3548         u_long maxmtu = 0;
3549         struct inpcb *inp = tp->t_inpcb;
3550         struct hc_metrics_lite metrics;
3551         int origoffer;
3552 #ifdef INET6
3553         int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3554         size_t min_protoh = isipv6 ?
3555                             sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3556                             sizeof (struct tcpiphdr);
3557 #else
3558         const size_t min_protoh = sizeof(struct tcpiphdr);
3559 #endif
3560
3561         INP_WLOCK_ASSERT(tp->t_inpcb);
3562
3563         if (mtuoffer != -1) {
3564                 KASSERT(offer == -1, ("%s: conflict", __func__));
3565                 offer = mtuoffer - min_protoh;
3566         }
3567         origoffer = offer;
3568
3569         /* Initialize. */
3570 #ifdef INET6
3571         if (isipv6) {
3572                 maxmtu = tcp_maxmtu6(&inp->inp_inc, cap);
3573                 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3574         }
3575 #endif
3576 #if defined(INET) && defined(INET6)
3577         else
3578 #endif
3579 #ifdef INET
3580         {
3581                 maxmtu = tcp_maxmtu(&inp->inp_inc, cap);
3582                 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3583         }
3584 #endif
3585
3586         /*
3587          * No route to sender, stay with default mss and return.
3588          */
3589         if (maxmtu == 0) {
3590                 /*
3591                  * In case we return early we need to initialize metrics
3592                  * to a defined state as tcp_hc_get() would do for us
3593                  * if there was no cache hit.
3594                  */
3595                 if (metricptr != NULL)
3596                         bzero(metricptr, sizeof(struct hc_metrics_lite));
3597                 return;
3598         }
3599
3600         /* What have we got? */
3601         switch (offer) {
3602                 case 0:
3603                         /*
3604                          * Offer == 0 means that there was no MSS on the SYN
3605                          * segment, in this case we use tcp_mssdflt as
3606                          * already assigned to t_maxopd above.
3607                          */
3608                         offer = tp->t_maxopd;
3609                         break;
3610
3611                 case -1:
3612                         /*
3613                          * Offer == -1 means that we didn't receive SYN yet.
3614                          */
3615                         /* FALLTHROUGH */
3616
3617                 default:
3618                         /*
3619                          * Prevent DoS attack with too small MSS. Round up
3620                          * to at least minmss.
3621                          */
3622                         offer = max(offer, V_tcp_minmss);
3623         }
3624
3625         /*
3626          * rmx information is now retrieved from tcp_hostcache.
3627          */
3628         tcp_hc_get(&inp->inp_inc, &metrics);
3629         if (metricptr != NULL)
3630                 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3631
3632         /*
3633          * If there's a discovered mtu int tcp hostcache, use it
3634          * else, use the link mtu.
3635          */
3636         if (metrics.rmx_mtu)
3637                 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3638         else {
3639 #ifdef INET6
3640                 if (isipv6) {
3641                         mss = maxmtu - min_protoh;
3642                         if (!V_path_mtu_discovery &&
3643                             !in6_localaddr(&inp->in6p_faddr))
3644                                 mss = min(mss, V_tcp_v6mssdflt);
3645                 }
3646 #endif
3647 #if defined(INET) && defined(INET6)
3648                 else
3649 #endif
3650 #ifdef INET
3651                 {
3652                         mss = maxmtu - min_protoh;
3653                         if (!V_path_mtu_discovery &&
3654                             !in_localaddr(inp->inp_faddr))
3655                                 mss = min(mss, V_tcp_mssdflt);
3656                 }
3657 #endif
3658                 /*
3659                  * XXX - The above conditional (mss = maxmtu - min_protoh)
3660                  * probably violates the TCP spec.
3661                  * The problem is that, since we don't know the
3662                  * other end's MSS, we are supposed to use a conservative
3663                  * default.  But, if we do that, then MTU discovery will
3664                  * never actually take place, because the conservative
3665                  * default is much less than the MTUs typically seen
3666                  * on the Internet today.  For the moment, we'll sweep
3667                  * this under the carpet.
3668                  *
3669                  * The conservative default might not actually be a problem
3670                  * if the only case this occurs is when sending an initial
3671                  * SYN with options and data to a host we've never talked
3672                  * to before.  Then, they will reply with an MSS value which
3673                  * will get recorded and the new parameters should get
3674                  * recomputed.  For Further Study.
3675                  */
3676         }
3677         mss = min(mss, offer);
3678
3679         /*
3680          * Sanity check: make sure that maxopd will be large
3681          * enough to allow some data on segments even if the
3682          * all the option space is used (40bytes).  Otherwise
3683          * funny things may happen in tcp_output.
3684          */
3685         mss = max(mss, 64);
3686
3687         /*
3688          * maxopd stores the maximum length of data AND options
3689          * in a segment; maxseg is the amount of data in a normal
3690          * segment.  We need to store this value (maxopd) apart
3691          * from maxseg, because now every segment carries options
3692          * and thus we normally have somewhat less data in segments.
3693          */
3694         tp->t_maxopd = mss;
3695
3696         /*
3697          * origoffer==-1 indicates that no segments were received yet.
3698          * In this case we just guess.
3699          */
3700         if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3701             (origoffer == -1 ||
3702              (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3703                 mss -= TCPOLEN_TSTAMP_APPA;
3704
3705         tp->t_maxseg = mss;
3706 }
3707
3708 void
3709 tcp_mss(struct tcpcb *tp, int offer)
3710 {
3711         int mss;
3712         u_long bufsize;
3713         struct inpcb *inp;
3714         struct socket *so;
3715         struct hc_metrics_lite metrics;
3716         struct tcp_ifcap cap;
3717
3718         KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3719
3720         bzero(&cap, sizeof(cap));
3721         tcp_mss_update(tp, offer, -1, &metrics, &cap);
3722
3723         mss = tp->t_maxseg;
3724         inp = tp->t_inpcb;
3725
3726         /*
3727          * If there's a pipesize, change the socket buffer to that size,
3728          * don't change if sb_hiwat is different than default (then it
3729          * has been changed on purpose with setsockopt).
3730          * Make the socket buffers an integral number of mss units;
3731          * if the mss is larger than the socket buffer, decrease the mss.
3732          */
3733         so = inp->inp_socket;
3734         SOCKBUF_LOCK(&so->so_snd);
3735         if ((so->so_snd.sb_hiwat == V_tcp_sendspace) && metrics.rmx_sendpipe)
3736                 bufsize = metrics.rmx_sendpipe;
3737         else
3738                 bufsize = so->so_snd.sb_hiwat;
3739         if (bufsize < mss)
3740                 mss = bufsize;
3741         else {
3742                 bufsize = roundup(bufsize, mss);
3743                 if (bufsize > sb_max)
3744                         bufsize = sb_max;
3745                 if (bufsize > so->so_snd.sb_hiwat)
3746                         (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3747         }
3748         SOCKBUF_UNLOCK(&so->so_snd);
3749         tp->t_maxseg = mss;
3750
3751         SOCKBUF_LOCK(&so->so_rcv);
3752         if ((so->so_rcv.sb_hiwat == V_tcp_recvspace) && metrics.rmx_recvpipe)
3753                 bufsize = metrics.rmx_recvpipe;
3754         else
3755                 bufsize = so->so_rcv.sb_hiwat;
3756         if (bufsize > mss) {
3757                 bufsize = roundup(bufsize, mss);
3758                 if (bufsize > sb_max)
3759                         bufsize = sb_max;
3760                 if (bufsize > so->so_rcv.sb_hiwat)
3761                         (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3762         }
3763         SOCKBUF_UNLOCK(&so->so_rcv);
3764
3765         /* Check the interface for TSO capabilities. */
3766         if (cap.ifcap & CSUM_TSO) {
3767                 tp->t_flags |= TF_TSO;
3768                 tp->t_tsomax = cap.tsomax;
3769                 tp->t_tsomaxsegcount = cap.tsomaxsegcount;
3770                 tp->t_tsomaxsegsize = cap.tsomaxsegsize;
3771         }
3772 }
3773
3774 /*
3775  * Determine the MSS option to send on an outgoing SYN.
3776  */
3777 int
3778 tcp_mssopt(struct in_conninfo *inc)
3779 {
3780         int mss = 0;
3781         u_long maxmtu = 0;
3782         u_long thcmtu = 0;
3783         size_t min_protoh;
3784
3785         KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3786
3787 #ifdef INET6
3788         if (inc->inc_flags & INC_ISIPV6) {
3789                 mss = V_tcp_v6mssdflt;
3790                 maxmtu = tcp_maxmtu6(inc, NULL);
3791                 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3792         }
3793 #endif
3794 #if defined(INET) && defined(INET6)
3795         else
3796 #endif
3797 #ifdef INET
3798         {
3799                 mss = V_tcp_mssdflt;
3800                 maxmtu = tcp_maxmtu(inc, NULL);
3801                 min_protoh = sizeof(struct tcpiphdr);
3802         }
3803 #endif
3804 #if defined(INET6) || defined(INET)
3805         thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3806 #endif
3807
3808         if (maxmtu && thcmtu)
3809                 mss = min(maxmtu, thcmtu) - min_protoh;
3810         else if (maxmtu || thcmtu)
3811                 mss = max(maxmtu, thcmtu) - min_protoh;
3812
3813         return (mss);
3814 }
3815
3816
3817 /*
3818  * On a partial ack arrives, force the retransmission of the
3819  * next unacknowledged segment.  Do not clear tp->t_dupacks.
3820  * By setting snd_nxt to ti_ack, this forces retransmission timer to
3821  * be started again.
3822  */
3823 static void
3824 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3825 {
3826         tcp_seq onxt = tp->snd_nxt;
3827         u_long  ocwnd = tp->snd_cwnd;
3828
3829         INP_WLOCK_ASSERT(tp->t_inpcb);
3830
3831         tcp_timer_activate(tp, TT_REXMT, 0);
3832         tp->t_rtttime = 0;
3833         tp->snd_nxt = th->th_ack;
3834         /*
3835          * Set snd_cwnd to one segment beyond acknowledged offset.
3836          * (tp->snd_una has not yet been updated when this function is called.)
3837          */
3838         tp->snd_cwnd = tp->t_maxseg + BYTES_THIS_ACK(tp, th);
3839         tp->t_flags |= TF_ACKNOW;
3840         (void) tcp_output(tp);
3841         tp->snd_cwnd = ocwnd;
3842         if (SEQ_GT(onxt, tp->snd_nxt))
3843                 tp->snd_nxt = onxt;
3844         /*
3845          * Partial window deflation.  Relies on fact that tp->snd_una
3846          * not updated yet.
3847          */
3848         if (tp->snd_cwnd > BYTES_THIS_ACK(tp, th))
3849                 tp->snd_cwnd -= BYTES_THIS_ACK(tp, th);
3850         else
3851                 tp->snd_cwnd = 0;
3852         tp->snd_cwnd += tp->t_maxseg;
3853 }
3854
3855 int
3856 tcp_compute_pipe(struct tcpcb *tp)
3857 {
3858         return (tp->snd_max - tp->snd_una +
3859                 tp->sackhint.sack_bytes_rexmit -
3860                 tp->sackhint.sacked_bytes);
3861 }