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