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