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