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