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