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