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