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