]> git.saurik.com Git - apple/xnu.git/blame - bsd/netinet/tcp_input.c
xnu-4570.41.2.tar.gz
[apple/xnu.git] / bsd / netinet / tcp_input.c
CommitLineData
1c79356b 1/*
5ba3f43e 2 * Copyright (c) 2000-2017 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
39037602 5 *
2d21ac55
A
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
39037602 14 *
2d21ac55
A
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
39037602 17 *
2d21ac55
A
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
39037602 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
27 */
28/*
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
9bccf70c 61 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.16 2001/08/22 00:59:12 silby Exp $
1c79356b 62 */
2d21ac55
A
63/*
64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
67 * Version 2.0.
68 */
1c79356b
A
69
70#include <sys/param.h>
71#include <sys/systm.h>
72#include <sys/kernel.h>
73#include <sys/sysctl.h>
74#include <sys/malloc.h>
75#include <sys/mbuf.h>
76#include <sys/proc.h> /* for proc0 declaration */
77#include <sys/protosw.h>
78#include <sys/socket.h>
79#include <sys/socketvar.h>
80#include <sys/syslog.h>
316670eb 81#include <sys/mcache.h>
5ba3f43e 82#if !CONFIG_EMBEDDED
39236c6e 83#include <sys/kasl.h>
5ba3f43e
A
84#endif
85#include <sys/kauth.h>
1c79356b
A
86#include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
87
b0d623f7
A
88#include <machine/endian.h>
89
1c79356b 90#include <net/if.h>
d12e1678 91#include <net/if_types.h>
1c79356b 92#include <net/route.h>
6d2010ae 93#include <net/ntstat.h>
39236c6e 94#include <net/dlil.h>
1c79356b
A
95
96#include <netinet/in.h>
97#include <netinet/in_systm.h>
98#include <netinet/ip.h>
39037602 99#include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
1c79356b 100#include <netinet/in_var.h>
9bccf70c 101#include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
1c79356b 102#include <netinet/in_pcb.h>
9bccf70c 103#include <netinet/ip_var.h>
6d2010ae 104#include <mach/sdt.h>
1c79356b
A
105#if INET6
106#include <netinet/ip6.h>
107#include <netinet/icmp6.h>
108#include <netinet6/nd6.h>
109#include <netinet6/ip6_var.h>
110#include <netinet6/in6_pcb.h>
111#endif
112#include <netinet/tcp.h>
3e170ce0 113#include <netinet/tcp_cache.h>
1c79356b
A
114#include <netinet/tcp_fsm.h>
115#include <netinet/tcp_seq.h>
116#include <netinet/tcp_timer.h>
117#include <netinet/tcp_var.h>
6d2010ae 118#include <netinet/tcp_cc.h>
39236c6e 119#include <dev/random/randomdev.h>
6d2010ae 120#include <kern/zalloc.h>
9bccf70c
A
121#if INET6
122#include <netinet6/tcp6_var.h>
123#endif
1c79356b
A
124#include <netinet/tcpip.h>
125#if TCPDEBUG
126#include <netinet/tcp_debug.h>
9bccf70c 127u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
1c79356b
A
128struct tcphdr tcp_savetcp;
129#endif /* TCPDEBUG */
130
131#if IPSEC
132#include <netinet6/ipsec.h>
9bccf70c
A
133#if INET6
134#include <netinet6/ipsec6.h>
135#endif
1c79356b
A
136#include <netkey/key.h>
137#endif /*IPSEC*/
138
2d21ac55
A
139#if CONFIG_MACF_NET || CONFIG_MACF_SOCKET
140#include <security/mac_framework.h>
141#endif /* CONFIG_MACF_NET || CONFIG_MACF_SOCKET */
142
1c79356b 143#include <sys/kdebug.h>
316670eb 144#include <netinet/lro_ext.h>
39236c6e
A
145#if MPTCP
146#include <netinet/mptcp_var.h>
147#include <netinet/mptcp.h>
39037602 148#include <netinet/mptcp_opt.h>
39236c6e 149#endif /* MPTCP */
1c79356b 150
3e170ce0
A
151#include <corecrypto/ccaes.h>
152
1c79356b
A
153#define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
154#define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
155#define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
156#define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
157
ecc0ceb4
A
158#define TCP_RTT_HISTORY_EXPIRE_TIME (60 * TCP_RETRANSHZ)
159#define TCP_RECV_THROTTLE_WIN (5 * TCP_RETRANSHZ)
39037602 160#define TCP_STRETCHACK_ENABLE_PKTCNT 2000
ecc0ceb4 161
1c79356b 162struct tcpstat tcpstat;
1c79356b 163
9bccf70c 164static int log_in_vain = 0;
3e170ce0
A
165SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain,
166 CTLFLAG_RW | CTLFLAG_LOCKED, &log_in_vain, 0,
167 "Log all incoming TCP connections");
9bccf70c
A
168
169static int blackhole = 0;
3e170ce0
A
170SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole,
171 CTLFLAG_RW | CTLFLAG_LOCKED, &blackhole, 0,
172 "Do not send RST when dropping refused connections");
1c79356b 173
5ba3f43e
A
174SYSCTL_SKMEM_TCP_INT(OID_AUTO, delayed_ack,
175 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_delack_enabled, 3,
9bccf70c
A
176 "Delay ACK to try and piggyback it onto a data packet");
177
5ba3f43e
A
178SYSCTL_SKMEM_TCP_INT(OID_AUTO, tcp_lq_overflow,
179 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_lq_overflow, 1,
9bccf70c
A
180 "Listen Queue Overflow");
181
5ba3f43e
A
182SYSCTL_SKMEM_TCP_INT(OID_AUTO, recvbg, CTLFLAG_RW | CTLFLAG_LOCKED,
183 int, tcp_recv_bg, 0, "Receive background");
6d2010ae 184
9bccf70c 185#if TCP_DROP_SYNFIN
5ba3f43e
A
186SYSCTL_SKMEM_TCP_INT(OID_AUTO, drop_synfin,
187 CTLFLAG_RW | CTLFLAG_LOCKED, static int, drop_synfin, 1,
3e170ce0 188 "Drop TCP packets with SYN+FIN set");
9bccf70c 189#endif
1c79356b 190
2d21ac55 191SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW|CTLFLAG_LOCKED, 0,
e5568f75
A
192 "TCP Segment Reassembly Queue");
193
e5568f75 194static int tcp_reass_overflows = 0;
3e170ce0
A
195SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows,
196 CTLFLAG_RD | CTLFLAG_LOCKED, &tcp_reass_overflows, 0,
e5568f75
A
197 "Global number of TCP Segment Reassembly Queue Overflows");
198
199
5ba3f43e
A
200SYSCTL_SKMEM_TCP_INT(OID_AUTO, slowlink_wsize, CTLFLAG_RW | CTLFLAG_LOCKED,
201 __private_extern__ int, slowlink_wsize, 8192,
202 "Maximum advertised window size for slowlink");
d12e1678 203
5ba3f43e
A
204SYSCTL_SKMEM_TCP_INT(OID_AUTO, maxseg_unacked,
205 CTLFLAG_RW | CTLFLAG_LOCKED, int, maxseg_unacked, 8,
3e170ce0 206 "Maximum number of outstanding segments left unacked");
2d21ac55 207
5ba3f43e
A
208SYSCTL_SKMEM_TCP_INT(OID_AUTO, rfc3465, CTLFLAG_RW | CTLFLAG_LOCKED,
209 int, tcp_do_rfc3465, 1, "");
b0d623f7 210
5ba3f43e
A
211SYSCTL_SKMEM_TCP_INT(OID_AUTO, rfc3465_lim2,
212 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_do_rfc3465_lim2, 1,
3e170ce0 213 "Appropriate bytes counting w/ L=2*SMSS");
6d2010ae 214
3e170ce0 215int rtt_samples_per_slot = 20;
6d2010ae 216
3e170ce0
A
217int tcp_acc_iaj_high_thresh = ACC_IAJ_HIGH_THRESH;
218u_int32_t tcp_autorcvbuf_inc_shift = 3;
5ba3f43e
A
219SYSCTL_SKMEM_TCP_INT(OID_AUTO, recv_allowed_iaj,
220 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_allowed_iaj, ALLOWED_IAJ,
3e170ce0
A
221 "Allowed inter-packet arrival jiter");
222#if (DEVELOPMENT || DEBUG)
223SYSCTL_INT(_net_inet_tcp, OID_AUTO, acc_iaj_high_thresh,
224 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_acc_iaj_high_thresh, 0,
225 "Used in calculating maximum accumulated IAJ");
226
227SYSCTL_INT(_net_inet_tcp, OID_AUTO, autorcvbufincshift,
228 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_autorcvbuf_inc_shift, 0,
229 "Shift for increment in receive socket buffer size");
230#endif /* (DEVELOPMENT || DEBUG) */
6d2010ae 231
5ba3f43e
A
232SYSCTL_SKMEM_TCP_INT(OID_AUTO, doautorcvbuf,
233 CTLFLAG_RW | CTLFLAG_LOCKED, u_int32_t, tcp_do_autorcvbuf, 1,
3e170ce0 234 "Enable automatic socket buffer tuning");
316670eb 235
5ba3f43e
A
236SYSCTL_SKMEM_TCP_INT(OID_AUTO, autorcvbufmax,
237 CTLFLAG_RW | CTLFLAG_LOCKED, u_int32_t, tcp_autorcvbuf_max, 512 * 1024,
3e170ce0 238 "Maximum receive socket buffer size");
316670eb 239
39037602
A
240u_int32_t tcp_autorcvbuf_max_ca = 512 * 1024;
241#if (DEBUG || DEVELOPMENT)
242SYSCTL_INT(_net_inet_tcp, OID_AUTO, autorcvbufmaxca,
243 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_autorcvbuf_max_ca, 0,
244 "Maximum receive socket buffer size");
245#endif /* (DEBUG || DEVELOPMENT) */
246
5ba3f43e
A
247#if CONFIG_EMBEDDED
248int sw_lro = 1;
249#else
39236c6e 250int sw_lro = 0;
5ba3f43e 251#endif /* !CONFIG_EMBEDDED */
316670eb
A
252SYSCTL_INT(_net_inet_tcp, OID_AUTO, lro, CTLFLAG_RW | CTLFLAG_LOCKED,
253 &sw_lro, 0, "Used to coalesce TCP packets");
254
255int lrodebug = 0;
3e170ce0
A
256SYSCTL_INT(_net_inet_tcp, OID_AUTO, lrodbg,
257 CTLFLAG_RW | CTLFLAG_LOCKED, &lrodebug, 0,
258 "Used to debug SW LRO");
316670eb 259
39236c6e 260int lro_start = 4;
3e170ce0
A
261SYSCTL_INT(_net_inet_tcp, OID_AUTO, lro_startcnt,
262 CTLFLAG_RW | CTLFLAG_LOCKED, &lro_start, 0,
263 "Segments for starting LRO computed as power of 2");
316670eb 264
39236c6e 265int limited_txmt = 1;
39236c6e 266int early_rexmt = 1;
39236c6e 267int sack_ackadv = 1;
3e170ce0
A
268int tcp_dsack_enable = 1;
269
270#if (DEVELOPMENT || DEBUG)
271SYSCTL_INT(_net_inet_tcp, OID_AUTO, limited_transmit,
272 CTLFLAG_RW | CTLFLAG_LOCKED, &limited_txmt, 0,
273 "Enable limited transmit");
274
275SYSCTL_INT(_net_inet_tcp, OID_AUTO, early_rexmt,
276 CTLFLAG_RW | CTLFLAG_LOCKED, &early_rexmt, 0,
277 "Enable Early Retransmit");
278
279SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack_ackadv,
280 CTLFLAG_RW | CTLFLAG_LOCKED, &sack_ackadv, 0,
281 "Use SACK with cumulative ack advancement as a dupack");
282
283SYSCTL_INT(_net_inet_tcp, OID_AUTO, dsack_enable,
284 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_dsack_enable, 0,
285 "use DSACK TCP option to report duplicate segments");
5ba3f43e 286
3e170ce0 287#endif /* (DEVELOPMENT || DEBUG) */
5ba3f43e
A
288int tcp_disable_access_to_stats = 1;
289SYSCTL_INT(_net_inet_tcp, OID_AUTO, disable_access_to_stats,
290 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_disable_access_to_stats, 0,
291 "Disable access to tcpstat");
292
39236c6e 293
2d21ac55 294extern int tcp_TCPTV_MIN;
6d2010ae
A
295extern int tcp_acc_iaj_high;
296extern int tcp_acc_iaj_react_limit;
6d2010ae 297
39236c6e 298int tcprexmtthresh = 3;
d12e1678 299
b0d623f7 300u_int32_t tcp_now;
6d2010ae
A
301struct timeval tcp_uptime; /* uptime when tcp_now was last updated */
302lck_spin_t *tcp_uptime_lock; /* Used to sychronize updates to tcp_now */
2d21ac55 303
1c79356b
A
304struct inpcbhead tcb;
305#define tcb6 tcb /* for KAME src sync over BSD*'s */
306struct inpcbinfo tcbinfo;
307
6d2010ae 308static void tcp_dooptions(struct tcpcb *, u_char *, int, struct tcphdr *,
3e170ce0
A
309 struct tcpopt *);
310static void tcp_finalize_options(struct tcpcb *, struct tcpopt *, unsigned int);
311static void tcp_pulloutofband(struct socket *,
312 struct tcphdr *, struct mbuf *, int);
39236c6e
A
313static int tcp_reass(struct tcpcb *, struct tcphdr *, int *, struct mbuf *,
314 struct ifnet *);
3e170ce0 315static void tcp_xmit_timer(struct tcpcb *, int, u_int32_t, tcp_seq);
2d21ac55 316static inline unsigned int tcp_maxmtu(struct rtentry *);
39037602 317static inline int tcp_stretch_ack_enable(struct tcpcb *tp, int thflags);
39236c6e 318static inline void tcp_adaptive_rwtimo_check(struct tcpcb *, int);
6d2010ae
A
319
320#if TRAFFIC_MGT
fe8ab488 321static inline void update_iaj_state(struct tcpcb *tp, uint32_t tlen,
3e170ce0 322 int reset_size);
39236c6e
A
323void compute_iaj(struct tcpcb *tp, int nlropkts, int lro_delay_factor);
324static void compute_iaj_meat(struct tcpcb *tp, uint32_t cur_iaj);
6d2010ae
A
325#endif /* TRAFFIC_MGT */
326
2d21ac55
A
327#if INET6
328static inline unsigned int tcp_maxmtu6(struct rtentry *);
329#endif
1c79356b 330
5ba3f43e
A
331unsigned int get_maxmtu(struct rtentry *);
332
39037602
A
333static void tcp_sbrcv_grow(struct tcpcb *tp, struct sockbuf *sb,
334 struct tcpopt *to, u_int32_t tlen, u_int32_t rcvbuf_max);
316670eb
A
335void tcp_sbrcv_trim(struct tcpcb *tp, struct sockbuf *sb);
336static void tcp_sbsnd_trim(struct sockbuf *sbsnd);
337static inline void tcp_sbrcv_tstmp_check(struct tcpcb *tp);
338static inline void tcp_sbrcv_reserve(struct tcpcb *tp, struct sockbuf *sb,
39037602 339 u_int32_t newsize, u_int32_t idealsize, u_int32_t rcvbuf_max);
39236c6e 340static void tcp_bad_rexmt_restore_state(struct tcpcb *tp, struct tcphdr *th);
39037602 341static void tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to,
3e170ce0 342 struct tcphdr *th);
fe8ab488
A
343static void tcp_early_rexmt_check(struct tcpcb *tp, struct tcphdr *th);
344static void tcp_bad_rexmt_check(struct tcpcb *tp, struct tcphdr *th,
3e170ce0 345 struct tcpopt *to);
39236c6e 346/*
39037602
A
347 * Constants used for resizing receive socket buffer
348 * when timestamps are not supported
39236c6e 349 */
316670eb
A
350#define TCPTV_RCVNOTS_QUANTUM 100
351#define TCP_RCVNOTS_BYTELEVEL 204800
39236c6e 352
39037602
A
353/*
354 * Constants used for limiting early retransmits
39236c6e
A
355 * to 10 per minute.
356 */
357#define TCP_EARLY_REXMT_WIN (60 * TCP_RETRANSHZ) /* 60 seconds */
358#define TCP_EARLY_REXMT_LIMIT 10
9bccf70c 359
3e170ce0 360extern void ipfwsyslog( int level, const char *format,...);
91447636
A
361extern int fw_verbose;
362
2d21ac55 363#if IPFIREWALL
39236c6e
A
364extern void ipfw_stealth_stats_incr_tcp(void);
365
91447636
A
366#define log_in_vain_log( a ) { \
367 if ( (log_in_vain == 3 ) && (fw_verbose == 2)) { /* Apple logging, log to ipfw.log */ \
368 ipfwsyslog a ; \
39236c6e
A
369 } else if ( (log_in_vain == 4 ) && (fw_verbose == 2)) { \
370 ipfw_stealth_stats_incr_tcp(); \
91447636
A
371 } \
372 else log a ; \
373}
2d21ac55
A
374#else
375#define log_in_vain_log( a ) { log a; }
376#endif
377
6d2010ae
A
378int tcp_rcvunackwin = TCPTV_UNACKWIN;
379int tcp_maxrcvidle = TCPTV_MAXRCVIDLE;
5ba3f43e
A
380SYSCTL_SKMEM_TCP_INT(OID_AUTO, rcvsspktcnt, CTLFLAG_RW | CTLFLAG_LOCKED,
381 int, tcp_rcvsspktcnt, TCP_RCV_SS_PKTCOUNT, "packets to be seen before receiver stretches acks");
91447636 382
39236c6e
A
383#define DELAY_ACK(tp, th) \
384 (CC_ALGO(tp)->delay_ack != NULL && CC_ALGO(tp)->delay_ack(tp, th))
91447636 385
2d21ac55 386static int tcp_dropdropablreq(struct socket *head);
8ad349bb 387static void tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th);
6d2010ae 388static void update_base_rtt(struct tcpcb *tp, uint32_t rtt);
6d2010ae
A
389void tcp_set_background_cc(struct socket *so);
390void tcp_set_foreground_cc(struct socket *so);
391static void tcp_set_new_cc(struct socket *so, uint16_t cc_index);
316670eb 392static void tcp_bwmeas_check(struct tcpcb *tp);
6d2010ae
A
393
394#if TRAFFIC_MGT
395void
396reset_acc_iaj(struct tcpcb *tp)
397{
398 tp->acc_iaj = 0;
316670eb 399 CLEAR_IAJ_STATE(tp);
6d2010ae
A
400}
401
402static inline void
403update_iaj_state(struct tcpcb *tp, uint32_t size, int rst_size)
404{
405 if (rst_size > 0)
406 tp->iaj_size = 0;
407 if (tp->iaj_size == 0 || size >= tp->iaj_size) {
408 tp->iaj_size = size;
409 tp->iaj_rcv_ts = tcp_now;
410 tp->iaj_small_pkt = 0;
411 }
412}
413
39037602
A
414/* For every 32 bit unsigned integer(v), this function will find the
415 * largest integer n such that (n*n <= v). This takes at most 16 iterations
416 * irrespective of the value of v and does not involve multiplications.
6d2010ae
A
417 */
418static inline int
39037602
A
419isqrt(unsigned int val)
420{
6d2010ae
A
421 unsigned int sqrt_cache[11] = {0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100};
422 unsigned int temp, g=0, b=0x8000, bshft=15;
423 if ( val <= 100) {
424 for (g = 0; g <= 10; ++g) {
425 if (sqrt_cache[g] > val) {
426 g--;
427 break;
428 } else if (sqrt_cache[g] == val) {
429 break;
430 }
431 }
432 } else {
433 do {
434 temp = (((g << 1) + b) << (bshft--));
435 if (val >= temp) {
436 g += b;
437 val -= temp;
438 }
439 b >>= 1;
440 } while ( b > 0 && val > 0);
441 }
442 return(g);
39037602 443}
6d2010ae 444
39037602 445/*
39236c6e
A
446* With LRO, roughly estimate the inter arrival time between
447* each sub coalesced packet as an average. Count the delay
448* cur_iaj to be the delay between the last packet received
449* and the first packet of the LRO stream. Due to round off errors
39037602 450* cur_iaj may be the same as lro_delay_factor. Averaging has
39236c6e
A
451* round off errors too. lro_delay_factor may be close to 0
452* in steady state leading to lower values fed to compute_iaj_meat.
453*/
6d2010ae 454void
39236c6e 455compute_iaj(struct tcpcb *tp, int nlropkts, int lro_delay_factor)
6d2010ae 456{
39236c6e
A
457 uint32_t cur_iaj = tcp_now - tp->iaj_rcv_ts;
458 uint32_t timediff = 0;
459
460 if (cur_iaj >= lro_delay_factor) {
461 cur_iaj = cur_iaj - lro_delay_factor;
462 }
463
464 compute_iaj_meat(tp, cur_iaj);
39037602 465
39236c6e
A
466 if (nlropkts <= 1)
467 return;
468
469 nlropkts--;
39037602 470
39236c6e
A
471 timediff = lro_delay_factor/nlropkts;
472
39037602 473 while (nlropkts > 0)
39236c6e 474 {
39037602 475 compute_iaj_meat(tp, timediff);
39236c6e
A
476 nlropkts--;
477 }
478}
479
480static
481void compute_iaj_meat(struct tcpcb *tp, uint32_t cur_iaj)
482{
39037602 483 /* When accumulated IAJ reaches MAX_ACC_IAJ in milliseconds,
39236c6e 484 * throttle the receive window to a minimum of MIN_IAJ_WIN packets
6d2010ae
A
485 */
486#define MAX_ACC_IAJ (tcp_acc_iaj_high_thresh + tcp_acc_iaj_react_limit)
39236c6e
A
487#define IAJ_DIV_SHIFT 4
488#define IAJ_ROUNDUP_CONST (1 << (IAJ_DIV_SHIFT - 1))
6d2010ae
A
489
490 uint32_t allowed_iaj, acc_iaj = 0;
6d2010ae
A
491
492 uint32_t mean, temp;
493 int32_t cur_iaj_dev;
39236c6e 494
39037602
A
495 cur_iaj_dev = (cur_iaj - tp->avg_iaj);
496
497 /* Allow a jitter of "allowed_iaj" milliseconds. Some connections
498 * may have a constant jitter more than that. We detect this by
39236c6e 499 * using standard deviation.
6d2010ae
A
500 */
501 allowed_iaj = tp->avg_iaj + tp->std_dev_iaj;
502 if (allowed_iaj < tcp_allowed_iaj)
503 allowed_iaj = tcp_allowed_iaj;
504
39037602
A
505 /* Initially when the connection starts, the senders congestion
506 * window is small. During this period we avoid throttling a
507 * connection because we do not have a good starting point for
508 * allowed_iaj. IAJ_IGNORE_PKTCNT is used to quietly gloss over
39236c6e 509 * the first few packets.
6d2010ae
A
510 */
511 if (tp->iaj_pktcnt > IAJ_IGNORE_PKTCNT) {
512 if ( cur_iaj <= allowed_iaj ) {
513 if (tp->acc_iaj >= 2)
514 acc_iaj = tp->acc_iaj - 2;
515 else
516 acc_iaj = 0;
39037602 517
6d2010ae
A
518 } else {
519 acc_iaj = tp->acc_iaj + (cur_iaj - allowed_iaj);
520 }
521
522 if (acc_iaj > MAX_ACC_IAJ)
523 acc_iaj = MAX_ACC_IAJ;
524 tp->acc_iaj = acc_iaj;
525 }
526
527 /* Compute weighted average where the history has a weight of
39037602 528 * 15 out of 16 and the current value has a weight of 1 out of 16.
6d2010ae 529 * This will make the short-term measurements have more weight.
39236c6e 530 *
39037602 531 * The addition of 8 will help to round-up the value
39236c6e 532 * instead of round-down
6d2010ae 533 */
39037602 534 tp->avg_iaj = (((tp->avg_iaj << IAJ_DIV_SHIFT) - tp->avg_iaj)
39236c6e 535 + cur_iaj + IAJ_ROUNDUP_CONST) >> IAJ_DIV_SHIFT;
6d2010ae
A
536
537 /* Compute Root-mean-square of deviation where mean is a weighted
39037602 538 * average as described above.
6d2010ae
A
539 */
540 temp = tp->std_dev_iaj * tp->std_dev_iaj;
39037602
A
541 mean = (((temp << IAJ_DIV_SHIFT) - temp)
542 + (cur_iaj_dev * cur_iaj_dev)
39236c6e 543 + IAJ_ROUNDUP_CONST) >> IAJ_DIV_SHIFT;
39037602 544
6d2010ae
A
545 tp->std_dev_iaj = isqrt(mean);
546
39037602 547 DTRACE_TCP3(iaj, struct tcpcb *, tp, uint32_t, cur_iaj,
39236c6e 548 uint32_t, allowed_iaj);
6d2010ae
A
549
550 return;
551}
552#endif /* TRAFFIC_MGT */
9bccf70c 553
39037602 554/* Check if enough amount of data has been acknowledged since
316670eb
A
555 * bw measurement was started
556 */
557static void
558tcp_bwmeas_check(struct tcpcb *tp)
559{
560 int32_t bw_meas_bytes;
561 uint32_t bw, bytes, elapsed_time;
5ba3f43e
A
562
563 if (SEQ_LEQ(tp->snd_una, tp->t_bwmeas->bw_start))
564 return;
565
316670eb 566 bw_meas_bytes = tp->snd_una - tp->t_bwmeas->bw_start;
5ba3f43e 567 if ((tp->t_flagsext & TF_BWMEAS_INPROGRESS) &&
316670eb
A
568 bw_meas_bytes >= (int32_t)(tp->t_bwmeas->bw_size)) {
569 bytes = bw_meas_bytes;
570 elapsed_time = tcp_now - tp->t_bwmeas->bw_ts;
571 if (elapsed_time > 0) {
572 bw = bytes / elapsed_time;
573 if ( bw > 0) {
574 if (tp->t_bwmeas->bw_sndbw > 0) {
39037602 575 tp->t_bwmeas->bw_sndbw =
5ba3f43e
A
576 (((tp->t_bwmeas->bw_sndbw << 3)
577 - tp->t_bwmeas->bw_sndbw)
578 + bw) >> 3;
316670eb
A
579 } else {
580 tp->t_bwmeas->bw_sndbw = bw;
581 }
5ba3f43e
A
582
583 /* Store the maximum value */
584 if (tp->t_bwmeas->bw_sndbw_max == 0) {
585 tp->t_bwmeas->bw_sndbw_max =
586 tp->t_bwmeas->bw_sndbw;
587 } else {
588 tp->t_bwmeas->bw_sndbw_max =
589 max(tp->t_bwmeas->bw_sndbw,
590 tp->t_bwmeas->bw_sndbw_max);
591 }
316670eb
A
592 }
593 }
594 tp->t_flagsext &= ~(TF_BWMEAS_INPROGRESS);
595 }
596}
597
9bccf70c 598static int
39236c6e
A
599tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m,
600 struct ifnet *ifp)
1c79356b 601{
9bccf70c
A
602 struct tseg_qent *q;
603 struct tseg_qent *p = NULL;
604 struct tseg_qent *nq;
8ad349bb 605 struct tseg_qent *te = NULL;
39236c6e
A
606 struct inpcb *inp = tp->t_inpcb;
607 struct socket *so = inp->inp_socket;
608 int flags = 0;
91447636 609 int dowakeup = 0;
39236c6e
A
610 struct mbuf *oodata = NULL;
611 int copy_oodata = 0;
fe8ab488 612 u_int16_t qlimit;
39236c6e
A
613 boolean_t cell = IFNET_IS_CELLULAR(ifp);
614 boolean_t wifi = (!cell && IFNET_IS_WIFI(ifp));
fe8ab488 615 boolean_t wired = (!wifi && IFNET_IS_WIRED(ifp));
3e170ce0 616 boolean_t dsack_set = FALSE;
1c79356b
A
617
618 /*
619 * Call with th==0 after become established to
620 * force pre-ESTABLISHED data up to user socket.
621 */
8ad349bb 622 if (th == NULL)
1c79356b 623 goto present;
39037602 624
fe8ab488 625 /*
39037602
A
626 * If the reassembly queue already has entries or if we are going
627 * to add a new one, then the connection has reached a loss state.
6d2010ae
A
628 * Reset the stretch-ack algorithm at this point.
629 */
fe8ab488 630 tcp_reset_stretch_ack(tp);
6d2010ae
A
631
632#if TRAFFIC_MGT
633 if (tp->acc_iaj > 0)
634 reset_acc_iaj(tp);
39037602 635#endif /* TRAFFIC_MGT */
1c79356b 636
e5568f75
A
637 /*
638 * Limit the number of segments in the reassembly queue to prevent
639 * holding on to too many segments (and thus running out of mbufs).
640 * Make sure to let the missing segment through which caused this
641 * queue. Always keep one global queue entry spare to be able to
642 * process the missing segment.
643 */
fe8ab488 644 qlimit = min(max(100, so->so_rcv.sb_hiwat >> 10),
39037602 645 (TCP_AUTORCVBUF_MAX(ifp) >> 10));
e5568f75 646 if (th->th_seq != tp->rcv_nxt &&
fe8ab488 647 (tp->t_reassqlen + 1) >= qlimit) {
e5568f75
A
648 tcp_reass_overflows++;
649 tcpstat.tcps_rcvmemdrop++;
650 m_freem(m);
2d21ac55 651 *tlenp = 0;
e5568f75
A
652 return (0);
653 }
654
9bccf70c 655 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
fe8ab488 656 te = (struct tseg_qent *) zalloc(tcp_reass_zone);
9bccf70c 657 if (te == NULL) {
1c79356b
A
658 tcpstat.tcps_rcvmemdrop++;
659 m_freem(m);
660 return (0);
661 }
fe8ab488 662 tp->t_reassqlen++;
1c79356b
A
663
664 /*
665 * Find a segment which begins after this one does.
666 */
9bccf70c
A
667 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
668 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
1c79356b 669 break;
9bccf70c
A
670 p = q;
671 }
1c79356b
A
672
673 /*
674 * If there is a preceding segment, it may provide some of
675 * our data already. If so, drop the data from the incoming
676 * segment. If it provides all of our data, drop us.
677 */
678 if (p != NULL) {
3e170ce0 679 int i;
1c79356b 680 /* conversion to int (in i) handles seq wraparound */
9bccf70c 681 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
1c79356b 682 if (i > 0) {
3e170ce0
A
683 if (TCP_DSACK_ENABLED(tp) && i > 1) {
684 /*
685 * Note duplicate data sequnce numbers
686 * to report in DSACK option
687 */
688 tp->t_dsack_lseq = th->th_seq;
689 tp->t_dsack_rseq = th->th_seq +
690 min(i, *tlenp);
691
692 /*
693 * Report only the first part of partial/
694 * non-contiguous duplicate sequence space
695 */
696 dsack_set = TRUE;
697 }
9bccf70c 698 if (i >= *tlenp) {
1c79356b 699 tcpstat.tcps_rcvduppack++;
9bccf70c 700 tcpstat.tcps_rcvdupbyte += *tlenp;
6d2010ae 701 if (nstat_collect) {
fe8ab488
A
702 nstat_route_rx(inp->inp_route.ro_rt,
703 1, *tlenp,
704 NSTAT_RX_FLAG_DUPLICATE);
705 INP_ADD_STAT(inp, cell, wifi, wired,
706 rxpackets, 1);
707 INP_ADD_STAT(inp, cell, wifi, wired,
708 rxbytes, *tlenp);
6d2010ae 709 tp->t_stat.rxduplicatebytes += *tlenp;
5ba3f43e 710 inp_set_activity_bitmap(inp);
6d2010ae 711 }
1c79356b 712 m_freem(m);
6d2010ae 713 zfree(tcp_reass_zone, te);
39236c6e 714 te = NULL;
fe8ab488 715 tp->t_reassqlen--;
1c79356b
A
716 /*
717 * Try to present any queued data
718 * at the left window edge to the user.
719 * This is needed after the 3-WHS
720 * completes.
721 */
39236c6e 722 goto present;
1c79356b
A
723 }
724 m_adj(m, i);
9bccf70c 725 *tlenp -= i;
1c79356b
A
726 th->th_seq += i;
727 }
728 }
4bd07ac2 729 tp->t_rcvoopack++;
1c79356b 730 tcpstat.tcps_rcvoopack++;
9bccf70c 731 tcpstat.tcps_rcvoobyte += *tlenp;
6d2010ae 732 if (nstat_collect) {
fe8ab488
A
733 nstat_route_rx(inp->inp_route.ro_rt, 1, *tlenp,
734 NSTAT_RX_FLAG_OUT_OF_ORDER);
735 INP_ADD_STAT(inp, cell, wifi, wired, rxpackets, 1);
736 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes, *tlenp);
6d2010ae 737 tp->t_stat.rxoutoforderbytes += *tlenp;
5ba3f43e 738 inp_set_activity_bitmap(inp);
6d2010ae 739 }
1c79356b
A
740
741 /*
742 * While we overlap succeeding segments trim them or,
743 * if they are completely covered, dequeue them.
744 */
745 while (q) {
3e170ce0 746 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
1c79356b
A
747 if (i <= 0)
748 break;
3e170ce0
A
749
750 /*
751 * Report only the first part of partial/non-contiguous
752 * duplicate segment in dsack option. The variable
753 * dsack_set will be true if a previous entry has some of
754 * the duplicate sequence space.
755 */
756 if (TCP_DSACK_ENABLED(tp) && i > 1 && !dsack_set) {
757 if (tp->t_dsack_lseq == 0) {
758 tp->t_dsack_lseq = q->tqe_th->th_seq;
759 tp->t_dsack_rseq =
760 tp->t_dsack_lseq + min(i, q->tqe_len);
761 } else {
762 /*
763 * this segment overlaps data in multple
764 * entries in the reassembly queue, move
765 * the right sequence number further.
766 */
767 tp->t_dsack_rseq =
768 tp->t_dsack_rseq + min(i, q->tqe_len);
769 }
770 }
9bccf70c
A
771 if (i < q->tqe_len) {
772 q->tqe_th->th_seq += i;
773 q->tqe_len -= i;
774 m_adj(q->tqe_m, i);
1c79356b
A
775 break;
776 }
9bccf70c
A
777
778 nq = LIST_NEXT(q, tqe_q);
779 LIST_REMOVE(q, tqe_q);
780 m_freem(q->tqe_m);
6d2010ae 781 zfree(tcp_reass_zone, q);
fe8ab488 782 tp->t_reassqlen--;
1c79356b
A
783 q = nq;
784 }
785
9bccf70c
A
786 /* Insert the new segment queue entry into place. */
787 te->tqe_m = m;
788 te->tqe_th = th;
789 te->tqe_len = *tlenp;
1c79356b 790
1c79356b 791 if (p == NULL) {
9bccf70c 792 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
1c79356b 793 } else {
9bccf70c 794 LIST_INSERT_AFTER(p, te, tqe_q);
1c79356b
A
795 }
796
39037602 797 /*
39236c6e 798 * New out-of-order data exists, and is pointed to by
39037602
A
799 * queue entry te. Set copy_oodata to 1 so out-of-order data
800 * can be copied off to sockbuf after in-order data
39236c6e
A
801 * is copied off.
802 */
803 if (!(so->so_state & SS_CANTRCVMORE))
804 copy_oodata = 1;
805
1c79356b
A
806present:
807 /*
808 * Present data to user, advancing rcv_nxt through
809 * completed sequence space.
810 */
811 if (!TCPS_HAVEESTABLISHED(tp->t_state))
812 return (0);
9bccf70c 813 q = LIST_FIRST(&tp->t_segq);
316670eb
A
814 if (!q || q->tqe_th->th_seq != tp->rcv_nxt) {
815 /* Stop using LRO once out of order packets arrive */
816 if (tp->t_flagsext & TF_LRO_OFFLOADED) {
39236c6e 817 tcp_lro_remove_state(inp->inp_laddr, inp->inp_faddr,
316670eb 818 th->th_dport, th->th_sport);
39037602 819 tp->t_flagsext &= ~TF_LRO_OFFLOADED;
316670eb 820 }
39236c6e
A
821
822 /*
39037602 823 * continue processing if out-of-order data
39236c6e
A
824 * can be delivered
825 */
826 if (q && (so->so_flags & SOF_ENABLE_MSGS))
827 goto msg_unordered_delivery;
828
1c79356b 829 return (0);
fe8ab488
A
830 }
831
39037602
A
832 /*
833 * If there is already another thread doing reassembly for this
834 * connection, it is better to let it finish the job --
835 * (radar 16316196)
836 */
837 if (tp->t_flagsext & TF_REASS_INPROG)
838 return (0);
839
840 tp->t_flagsext |= TF_REASS_INPROG;
fe8ab488
A
841 /* lost packet was recovered, so ooo data can be returned */
842 tcpstat.tcps_recovered_pkts++;
843
1c79356b 844 do {
9bccf70c
A
845 tp->rcv_nxt += q->tqe_len;
846 flags = q->tqe_th->th_flags & TH_FIN;
9bccf70c 847 LIST_REMOVE(q, tqe_q);
39236c6e 848 if (so->so_state & SS_CANTRCVMORE) {
9bccf70c 849 m_freem(q->tqe_m);
39236c6e 850 } else {
6d2010ae 851 so_recv_data_stat(so, q->tqe_m, 0); /* XXXX */
39236c6e 852 if (so->so_flags & SOF_ENABLE_MSGS) {
39037602
A
853 /*
854 * Append the inorder data as a message to the
855 * receive socket buffer. Also check to see if
856 * the data we are about to deliver is the same
857 * data that we wanted to pass up to the user
858 * out of order. If so, reset copy_oodata --
39236c6e
A
859 * the received data filled a gap, and
860 * is now in order!
861 */
862 if (q == te)
863 copy_oodata = 0;
864 }
39037602 865 if (sbappendstream_rcvdemux(so, q->tqe_m,
39236c6e 866 q->tqe_th->th_seq - (tp->irs + 1), 0))
91447636 867 dowakeup = 1;
39037602
A
868 if (tp->t_flagsext & TF_LRO_OFFLOADED) {
869 tcp_update_lro_seq(tp->rcv_nxt,
39236c6e
A
870 inp->inp_laddr, inp->inp_faddr,
871 th->th_dport, th->th_sport);
316670eb 872 }
91447636 873 }
6d2010ae 874 zfree(tcp_reass_zone, q);
fe8ab488 875 tp->t_reassqlen--;
39037602 876 q = LIST_FIRST(&tp->t_segq);
9bccf70c 877 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
39037602 878 tp->t_flagsext &= ~TF_REASS_INPROG;
9bccf70c 879
1c79356b 880#if INET6
39236c6e 881 if ((inp->inp_vflag & INP_IPV6) != 0) {
39037602 882
9bccf70c 883 KERNEL_DEBUG(DBG_LAYER_BEG,
39236c6e
A
884 ((inp->inp_fport << 16) | inp->inp_lport),
885 (((inp->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
886 (inp->in6p_faddr.s6_addr16[0] & 0xffff)),
9bccf70c
A
887 0,0,0);
888 }
889 else
1c79356b 890#endif
9bccf70c
A
891 {
892 KERNEL_DEBUG(DBG_LAYER_BEG,
39236c6e
A
893 ((inp->inp_fport << 16) | inp->inp_lport),
894 (((inp->inp_laddr.s_addr & 0xffff) << 16) |
895 (inp->inp_faddr.s_addr & 0xffff)),
9bccf70c 896 0,0,0);
91447636 897 }
39236c6e
A
898
899msg_unordered_delivery:
900 /* Deliver out-of-order data as a message */
901 if (te && (so->so_flags & SOF_ENABLE_MSGS) && copy_oodata && te->tqe_len) {
39037602
A
902 /*
903 * make a copy of the mbuf to be delivered up to
39236c6e
A
904 * the user, and add it to the sockbuf
905 */
906 oodata = m_copym(te->tqe_m, 0, M_COPYALL, M_DONTWAIT);
907 if (oodata != NULL) {
39037602 908 if (sbappendmsgstream_rcv(&so->so_rcv, oodata,
39236c6e
A
909 te->tqe_th->th_seq - (tp->irs + 1), 1)) {
910 dowakeup = 1;
911 tcpstat.tcps_msg_unopkts++;
912 } else {
913 tcpstat.tcps_msg_unoappendfail++;
914 }
915 }
916 }
917
91447636
A
918 if (dowakeup)
919 sorwakeup(so); /* done with socket lock held */
1c79356b
A
920 return (flags);
921}
922
2d21ac55 923/*
3e170ce0
A
924 * Reduce congestion window -- used when ECN is seen or when a tail loss
925 * probe recovers the last packet.
2d21ac55
A
926 */
927static void
928tcp_reduce_congestion_window(
316670eb 929 struct tcpcb *tp)
2d21ac55 930{
6d2010ae
A
931 /*
932 * If the current tcp cc module has
933 * defined a hook for tasks to run
934 * before entering FR, call it
935 */
936 if (CC_ALGO(tp)->pre_fr != NULL)
316670eb 937 CC_ALGO(tp)->pre_fr(tp);
2d21ac55 938 ENTER_FASTRECOVERY(tp);
3e170ce0
A
939 if (tp->t_flags & TF_SENTFIN)
940 tp->snd_recover = tp->snd_max - 1;
941 else
942 tp->snd_recover = tp->snd_max;
2d21ac55 943 tp->t_timer[TCPT_REXMT] = 0;
fe8ab488 944 tp->t_timer[TCPT_PTO] = 0;
2d21ac55 945 tp->t_rtttime = 0;
3e170ce0
A
946 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
947 tcp_cc_adjust_nonvalidated_cwnd(tp);
948 } else {
949 tp->snd_cwnd = tp->snd_ssthresh +
950 tp->t_maxseg * tcprexmtthresh;
951 }
2d21ac55
A
952}
953
39236c6e 954/*
3e170ce0
A
955 * This function is called upon reception of data on a socket. It's purpose is
956 * to handle the adaptive keepalive timers that monitor whether the connection
957 * is making progress. First the adaptive read-timer, second the TFO probe-timer.
958 *
959 * The application wants to get an event if there is a stall during read.
960 * Set the initial keepalive timeout to be equal to twice RTO.
961 *
962 * If the outgoing interface is in marginal conditions, we need to
963 * enable read probes for that too.
39236c6e
A
964 */
965static inline void
3e170ce0 966tcp_adaptive_rwtimo_check(struct tcpcb *tp, int tlen)
39236c6e 967{
3e170ce0
A
968 struct ifnet *outifp = tp->t_inpcb->inp_last_outifp;
969
970 if ((tp->t_adaptive_rtimo > 0 ||
971 (outifp != NULL &&
972 (outifp->if_eflags & IFEF_PROBE_CONNECTIVITY)))
973 && tlen > 0 &&
974 tp->t_state == TCPS_ESTABLISHED) {
975 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
39236c6e
A
976 (TCP_REXMTVAL(tp) << 1));
977 tp->t_flagsext |= TF_DETECT_READSTALL;
978 tp->t_rtimo_probes = 0;
979 }
980}
981
982inline void
983tcp_keepalive_reset(struct tcpcb *tp)
984{
39037602 985 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
39236c6e
A
986 TCP_CONN_KEEPIDLE(tp));
987 tp->t_flagsext &= ~(TF_DETECT_READSTALL);
988 tp->t_rtimo_probes = 0;
989}
9bccf70c 990
1c79356b
A
991/*
992 * TCP input routine, follows pages 65-76 of the
993 * protocol specification dated September, 1981 very closely.
994 */
995#if INET6
996int
6d2010ae 997tcp6_input(struct mbuf **mp, int *offp, int proto)
1c79356b 998{
6d2010ae 999#pragma unused(proto)
39037602 1000 struct mbuf *m = *mp;
39236c6e
A
1001 uint32_t ia6_flags;
1002 struct ifnet *ifp = m->m_pkthdr.rcvif;
9bccf70c 1003
91447636 1004 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), return IPPROTO_DONE);
9bccf70c 1005
316670eb
A
1006 /* Expect 32-bit aligned data pointer on strict-align platforms */
1007 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
1008
9bccf70c
A
1009 /*
1010 * draft-itojun-ipv6-tcp-to-anycast
1011 * better place to put this in?
1012 */
39236c6e
A
1013 if (ip6_getdstifaddr_info(m, NULL, &ia6_flags) == 0) {
1014 if (ia6_flags & IN6_IFF_ANYCAST) {
6d2010ae 1015 struct ip6_hdr *ip6;
9bccf70c 1016
6d2010ae
A
1017 ip6 = mtod(m, struct ip6_hdr *);
1018 icmp6_error(m, ICMP6_DST_UNREACH,
1019 ICMP6_DST_UNREACH_ADDR,
9bccf70c 1020 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
39236c6e
A
1021
1022 IF_TCP_STATINC(ifp, icmp6unreach);
1023
6d2010ae
A
1024 return (IPPROTO_DONE);
1025 }
9bccf70c
A
1026 }
1027
1028 tcp_input(m, *offp);
6d2010ae 1029 return (IPPROTO_DONE);
1c79356b
A
1030}
1031#endif
1032
316670eb 1033/* Depending on the usage of mbuf space in the system, this function
39037602 1034 * will return true or false. This is used to determine if a socket
316670eb
A
1035 * buffer can take more memory from the system for auto-tuning or not.
1036 */
1037u_int8_t
1038tcp_cansbgrow(struct sockbuf *sb)
1039{
1040 /* Calculate the host level space limit in terms of MSIZE buffers.
1041 * We can use a maximum of half of the available mbuf space for
39037602 1042 * socket buffers.
316670eb
A
1043 */
1044 u_int32_t mblim = ((nmbclusters >> 1) << (MCLSHIFT - MSIZESHIFT));
1045
1046 /* Calculate per sb limit in terms of bytes. We optimize this limit
1047 * for upto 16 socket buffers.
1048 */
1049
1050 u_int32_t sbspacelim = ((nmbclusters >> 4) << MCLSHIFT);
1051
1052 if ((total_sbmb_cnt < mblim) &&
1053 (sb->sb_hiwat < sbspacelim)) {
1054 return(1);
fe8ab488
A
1055 } else {
1056 OSIncrementAtomic64(&sbmb_limreached);
316670eb
A
1057 }
1058 return(0);
1059}
1060
39236c6e
A
1061static void
1062tcp_sbrcv_reserve(struct tcpcb *tp, struct sockbuf *sbrcv,
39037602 1063 u_int32_t newsize, u_int32_t idealsize, u_int32_t rcvbuf_max)
39236c6e 1064{
316670eb 1065 /* newsize should not exceed max */
39037602 1066 newsize = min(newsize, rcvbuf_max);
316670eb 1067
39037602
A
1068 /* The receive window scale negotiated at the
1069 * beginning of the connection will also set a
316670eb
A
1070 * limit on the socket buffer size
1071 */
1072 newsize = min(newsize, TCP_MAXWIN << tp->rcv_scale);
1073
1074 /* Set new socket buffer size */
1075 if (newsize > sbrcv->sb_hiwat &&
1076 (sbreserve(sbrcv, newsize) == 1)) {
39037602
A
1077 sbrcv->sb_idealsize = min(max(sbrcv->sb_idealsize,
1078 (idealsize != 0) ? idealsize : newsize), rcvbuf_max);
316670eb 1079
39037602
A
1080 /* Again check the limit set by the advertised
1081 * window scale
316670eb 1082 */
39037602 1083 sbrcv->sb_idealsize = min(sbrcv->sb_idealsize,
316670eb
A
1084 TCP_MAXWIN << tp->rcv_scale);
1085 }
1086}
1087
39037602 1088/*
316670eb
A
1089 * This function is used to grow a receive socket buffer. It
1090 * will take into account system-level memory usage and the
1091 * bandwidth available on the link to make a decision.
1092 */
1093static void
39037602
A
1094tcp_sbrcv_grow(struct tcpcb *tp, struct sockbuf *sbrcv,
1095 struct tcpopt *to, u_int32_t pktlen, u_int32_t rcvbuf_max)
3e170ce0
A
1096{
1097 struct socket *so = sbrcv->sb_so;
39037602 1098
39236c6e
A
1099 /*
1100 * Do not grow the receive socket buffer if
1101 * - auto resizing is disabled, globally or on this socket
fe8ab488 1102 * - the high water mark already reached the maximum
39037602 1103 * - the stream is in background and receive side is being
39236c6e
A
1104 * throttled
1105 * - if there are segments in reassembly queue indicating loss,
39037602 1106 * do not need to increase recv window during recovery as more
fe8ab488
A
1107 * data is not going to be sent. A duplicate ack sent during
1108 * recovery should not change the receive window
39236c6e 1109 */
316670eb
A
1110 if (tcp_do_autorcvbuf == 0 ||
1111 (sbrcv->sb_flags & SB_AUTOSIZE) == 0 ||
1112 tcp_cansbgrow(sbrcv) == 0 ||
39037602 1113 sbrcv->sb_hiwat >= rcvbuf_max ||
39236c6e 1114 (tp->t_flagsext & TF_RECV_THROTTLE) ||
3e170ce0 1115 (so->so_flags1 & SOF1_EXTEND_BK_IDLE_WANTED) ||
39236c6e 1116 !LIST_EMPTY(&tp->t_segq)) {
316670eb
A
1117 /* Can not resize the socket buffer, just return */
1118 goto out;
1119 }
1120
1121 if (TSTMP_GT(tcp_now,
1122 tp->rfbuf_ts + TCPTV_RCVBUFIDLE)) {
1123 /* If there has been an idle period in the
1124 * connection, just restart the measurement
1125 */
1126 goto out;
1127 }
1128
39236c6e 1129 if (!TSTMP_SUPPORTED(tp)) {
316670eb
A
1130 /*
1131 * Timestamp option is not supported on this connection.
1132 * If the connection reached a state to indicate that
1133 * the receive socket buffer needs to grow, increase
fe8ab488
A
1134 * the high water mark.
1135 */
39037602 1136 if (TSTMP_GEQ(tcp_now,
316670eb
A
1137 tp->rfbuf_ts + TCPTV_RCVNOTS_QUANTUM)) {
1138 if (tp->rfbuf_cnt >= TCP_RCVNOTS_BYTELEVEL) {
1139 tcp_sbrcv_reserve(tp, sbrcv,
39037602
A
1140 tcp_autorcvbuf_max, 0,
1141 tcp_autorcvbuf_max);
316670eb
A
1142 }
1143 goto out;
1144 } else {
1145 tp->rfbuf_cnt += pktlen;
1146 return;
fe8ab488 1147 }
316670eb 1148 } else if (to->to_tsecr != 0) {
fe8ab488
A
1149 /*
1150 * If the timestamp shows that one RTT has
316670eb
A
1151 * completed, we can stop counting the
1152 * bytes. Here we consider increasing
fe8ab488
A
1153 * the socket buffer if the bandwidth measured in
1154 * last rtt, is more than half of sb_hiwat, this will
1155 * help to scale the buffer according to the bandwidth
1156 * on the link.
316670eb
A
1157 */
1158 if (TSTMP_GEQ(to->to_tsecr, tp->rfbuf_ts)) {
fe8ab488
A
1159 if (tp->rfbuf_cnt > (sbrcv->sb_hiwat -
1160 (sbrcv->sb_hiwat >> 1))) {
1161 int32_t rcvbuf_inc, min_incr;
316670eb 1162 /*
fe8ab488
A
1163 * Increment the receive window by a
1164 * multiple of maximum sized segments.
39037602 1165 * This will prevent a connection from
fe8ab488
A
1166 * sending smaller segments on wire if it
1167 * is limited by the receive window.
316670eb 1168 *
fe8ab488 1169 * Set the ideal size based on current
39037602 1170 * bandwidth measurements. We set the
fe8ab488
A
1171 * ideal size on receive socket buffer to
1172 * be twice the bandwidth delay product.
1173 */
1174 rcvbuf_inc = (tp->rfbuf_cnt << 1)
1175 - sbrcv->sb_hiwat;
1176
1177 /*
1178 * Make the increment equal to 8 segments
1179 * at least
316670eb 1180 */
fe8ab488
A
1181 min_incr = tp->t_maxseg << tcp_autorcvbuf_inc_shift;
1182 if (rcvbuf_inc < min_incr)
39037602 1183 rcvbuf_inc = min_incr;
fe8ab488 1184
39037602 1185 rcvbuf_inc =
fe8ab488 1186 (rcvbuf_inc / tp->t_maxseg) * tp->t_maxseg;
316670eb 1187 tcp_sbrcv_reserve(tp, sbrcv,
39037602
A
1188 sbrcv->sb_hiwat + rcvbuf_inc,
1189 (tp->rfbuf_cnt * 2), rcvbuf_max);
316670eb 1190 }
5ba3f43e
A
1191 /* Measure instantaneous receive bandwidth */
1192 if (tp->t_bwmeas != NULL && tp->rfbuf_cnt > 0 &&
1193 TSTMP_GT(tcp_now, tp->rfbuf_ts)) {
1194 u_int32_t rcv_bw;
1195 rcv_bw = tp->rfbuf_cnt /
1196 (int)(tcp_now - tp->rfbuf_ts);
1197 if (tp->t_bwmeas->bw_rcvbw_max == 0) {
1198 tp->t_bwmeas->bw_rcvbw_max = rcv_bw;
1199 } else {
1200 tp->t_bwmeas->bw_rcvbw_max = max(
1201 tp->t_bwmeas->bw_rcvbw_max, rcv_bw);
1202 }
1203 }
316670eb
A
1204 goto out;
1205 } else {
1206 tp->rfbuf_cnt += pktlen;
1207 return;
1208 }
1209 }
1210out:
1211 /* Restart the measurement */
1212 tp->rfbuf_ts = 0;
1213 tp->rfbuf_cnt = 0;
1214 return;
1215}
1216
1217/* This function will trim the excess space added to the socket buffer
1218 * to help a slow-reading app. The ideal-size of a socket buffer depends
39037602 1219 * on the link bandwidth or it is set by an application and we aim to
316670eb
A
1220 * reach that size.
1221 */
1222void
39037602
A
1223tcp_sbrcv_trim(struct tcpcb *tp, struct sockbuf *sbrcv)
1224{
316670eb
A
1225 if (tcp_do_autorcvbuf == 1 && sbrcv->sb_idealsize > 0 &&
1226 sbrcv->sb_hiwat > sbrcv->sb_idealsize) {
1227 int32_t trim;
1228 /* compute the difference between ideal and current sizes */
1229 u_int32_t diff = sbrcv->sb_hiwat - sbrcv->sb_idealsize;
1230
1231 /* Compute the maximum advertised window for
1232 * this connection.
1233 */
1234 u_int32_t advwin = tp->rcv_adv - tp->rcv_nxt;
39037602 1235
316670eb
A
1236 /* How much can we trim the receive socket buffer?
1237 * 1. it can not be trimmed beyond the max rcv win advertised
39037602 1238 * 2. if possible, leave 1/16 of bandwidth*delay to
316670eb
A
1239 * avoid closing the win completely
1240 */
1241 u_int32_t leave = max(advwin, (sbrcv->sb_idealsize >> 4));
1242
1243 /* Sometimes leave can be zero, in that case leave at least
1244 * a few segments worth of space.
1245 */
1246 if (leave == 0)
1247 leave = tp->t_maxseg << tcp_autorcvbuf_inc_shift;
39037602 1248
316670eb
A
1249 trim = sbrcv->sb_hiwat - (sbrcv->sb_cc + leave);
1250 trim = imin(trim, (int32_t)diff);
1251
1252 if (trim > 0)
1253 sbreserve(sbrcv, (sbrcv->sb_hiwat - trim));
1254 }
1255}
1256
1257/* We may need to trim the send socket buffer size for two reasons:
1258 * 1. if the rtt seen on the connection is climbing up, we do not
1259 * want to fill the buffers any more.
1260 * 2. if the congestion win on the socket backed off, there is no need
1261 * to hold more mbufs for that connection than what the cwnd will allow.
1262 */
1263void
39037602
A
1264tcp_sbsnd_trim(struct sockbuf *sbsnd)
1265{
1266 if (tcp_do_autosendbuf == 1 &&
1267 ((sbsnd->sb_flags & (SB_AUTOSIZE | SB_TRIM)) ==
316670eb
A
1268 (SB_AUTOSIZE | SB_TRIM)) &&
1269 (sbsnd->sb_idealsize > 0) &&
1270 (sbsnd->sb_hiwat > sbsnd->sb_idealsize)) {
1271 u_int32_t trim = 0;
1272 if (sbsnd->sb_cc <= sbsnd->sb_idealsize) {
1273 trim = sbsnd->sb_hiwat - sbsnd->sb_idealsize;
1274 } else {
1275 trim = sbsnd->sb_hiwat - sbsnd->sb_cc;
1276 }
1277 sbreserve(sbsnd, (sbsnd->sb_hiwat - trim));
1278 }
1279 if (sbsnd->sb_hiwat <= sbsnd->sb_idealsize)
1280 sbsnd->sb_flags &= ~(SB_TRIM);
1281}
1282
39037602 1283/*
316670eb
A
1284 * If timestamp option was not negotiated on this connection
1285 * and this connection is on the receiving side of a stream
1286 * then we can not measure the delay on the link accurately.
1287 * Instead of enabling automatic receive socket buffer
1288 * resizing, just give more space to the receive socket buffer.
1289 */
39037602
A
1290static inline void
1291tcp_sbrcv_tstmp_check(struct tcpcb *tp)
1292{
316670eb
A
1293 struct socket *so = tp->t_inpcb->inp_socket;
1294 u_int32_t newsize = 2 * tcp_recvspace;
1295 struct sockbuf *sbrcv = &so->so_rcv;
1296
1297 if ((tp->t_flags & (TF_REQ_TSTMP | TF_RCVD_TSTMP)) !=
1298 (TF_REQ_TSTMP | TF_RCVD_TSTMP) &&
1299 (sbrcv->sb_flags & SB_AUTOSIZE) != 0) {
39037602 1300 tcp_sbrcv_reserve(tp, sbrcv, newsize, 0, newsize);
316670eb
A
1301 }
1302}
1303
39037602
A
1304/* A receiver will evaluate the flow of packets on a connection
1305 * to see if it can reduce ack traffic. The receiver will start
6d2010ae
A
1306 * stretching acks if all of the following conditions are met:
1307 * 1. tcp_delack_enabled is set to 3
1308 * 2. If the bytes received in the last 100ms is greater than a threshold
1309 * defined by maxseg_unacked
1310 * 3. If the connection has not been idle for tcp_maxrcvidle period.
39037602 1311 * 4. If the connection has seen enough packets to let the slow-start
6d2010ae
A
1312 * finish after connection establishment or after some packet loss.
1313 *
1314 * The receiver will stop stretching acks if there is congestion/reordering
39037602
A
1315 * as indicated by packets on reassembly queue or an ECN. If the delayed-ack
1316 * timer fires while stretching acks, it means that the packet flow has gone
6d2010ae 1317 * below the threshold defined by maxseg_unacked and the receiver will stop
39037602
A
1318 * stretching acks. The receiver gets no indication when slow-start is completed
1319 * or when the connection reaches an idle state. That is why we use
1320 * tcp_rcvsspktcnt to cover slow-start and tcp_maxrcvidle to identify idle
6d2010ae
A
1321 * state.
1322 */
39236c6e 1323static inline int
39037602 1324tcp_stretch_ack_enable(struct tcpcb *tp, int thflags)
39236c6e 1325{
39037602
A
1326 if (tp->rcv_by_unackwin >= (maxseg_unacked * tp->t_maxseg) &&
1327 TSTMP_GEQ(tp->rcv_unackwin, tcp_now))
1328 tp->t_flags |= TF_STREAMING_ON;
1329 else
1330 tp->t_flags &= ~TF_STREAMING_ON;
1331
1332 /* If there has been an idle time, reset streaming detection */
1333 if (TSTMP_GT(tcp_now, tp->rcv_unackwin + tcp_maxrcvidle))
1334 tp->t_flags &= ~TF_STREAMING_ON;
1335
1336 /*
1337 * If there are flags other than TH_ACK set, reset streaming
1338 * detection
1339 */
1340 if (thflags & ~TH_ACK)
1341 tp->t_flags &= ~TF_STREAMING_ON;
1342
1343 if (tp->t_flagsext & TF_DISABLE_STRETCHACK) {
1344 if (tp->rcv_nostrack_pkts >= TCP_STRETCHACK_ENABLE_PKTCNT) {
1345 tp->t_flagsext &= ~TF_DISABLE_STRETCHACK;
1346 tp->rcv_nostrack_pkts = 0;
1347 tp->rcv_nostrack_ts = 0;
1348 } else {
1349 tp->rcv_nostrack_pkts++;
1350 }
1351 }
1352
fe8ab488 1353 if (!(tp->t_flagsext & (TF_NOSTRETCHACK|TF_DISABLE_STRETCHACK)) &&
39037602
A
1354 (tp->t_flags & TF_STREAMING_ON) &&
1355 (!(tp->t_flagsext & TF_RCVUNACK_WAITSS) ||
1356 (tp->rcv_waitforss >= tcp_rcvsspktcnt))) {
6d2010ae
A
1357 return(1);
1358 }
39037602 1359
6d2010ae
A
1360 return(0);
1361}
1362
fe8ab488
A
1363/*
1364 * Reset the state related to stretch-ack algorithm. This will make
6d2010ae 1365 * the receiver generate an ack every other packet. The receiver
39037602 1366 * will start re-evaluating the rate at which packets come to decide
6d2010ae
A
1367 * if it can benefit by lowering the ack traffic.
1368 */
1369void
1370tcp_reset_stretch_ack(struct tcpcb *tp)
1371{
39037602 1372 tp->t_flags &= ~(TF_STRETCHACK|TF_STREAMING_ON);
6d2010ae
A
1373 tp->rcv_by_unackwin = 0;
1374 tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
fe8ab488
A
1375
1376 /*
1377 * When there is packet loss or packet re-ordering or CWR due to
1378 * ECN, the sender's congestion window is reduced. In these states,
1379 * generate an ack for every other packet for some time to allow
39037602 1380 * the sender's congestion window to grow.
fe8ab488
A
1381 */
1382 tp->t_flagsext |= TF_RCVUNACK_WAITSS;
1383 tp->rcv_waitforss = 0;
6d2010ae
A
1384}
1385
39236c6e 1386/*
39037602 1387 * The last packet was a retransmission, check if this ack
39236c6e 1388 * indicates that the retransmission was spurious.
39037602 1389 *
39236c6e
A
1390 * If the connection supports timestamps, we could use it to
1391 * detect if the last retransmit was not needed. Otherwise,
39037602 1392 * we check if the ACK arrived within RTT/2 window, then it
39236c6e
A
1393 * was a mistake to do the retransmit in the first place.
1394 *
39037602
A
1395 * This function will return 1 if it is a spurious retransmit,
1396 * 0 otherwise.
39236c6e 1397 */
fe8ab488 1398int
39037602 1399tcp_detect_bad_rexmt(struct tcpcb *tp, struct tcphdr *th,
fe8ab488 1400 struct tcpopt *to, u_int32_t rxtime)
39236c6e
A
1401{
1402 int32_t tdiff, bad_rexmt_win;
39236c6e
A
1403 bad_rexmt_win = (tp->t_srtt >> (TCP_RTT_SHIFT + 1));
1404
fe8ab488 1405 /* If the ack has ECN CE bit, then cwnd has to be adjusted */
3e170ce0 1406 if (TCP_ECN_ENABLED(tp) && (th->th_flags & TH_ECE))
fe8ab488
A
1407 return (0);
1408 if (TSTMP_SUPPORTED(tp)) {
1409 if (rxtime > 0 && (to->to_flags & TOF_TS)
39037602 1410 && to->to_tsecr != 0
fe8ab488
A
1411 && TSTMP_LT(to->to_tsecr, rxtime))
1412 return (1);
1413 } else {
39037602 1414 if ((tp->t_rxtshift == 1
fe8ab488
A
1415 || (tp->t_flagsext & TF_SENT_TLPROBE))
1416 && rxtime > 0) {
1417 tdiff = (int32_t)(tcp_now - rxtime);
1418 if (tdiff < bad_rexmt_win)
1419 return(1);
1420 }
39236c6e
A
1421 }
1422 return(0);
1423}
1424
1425
1426/*
1427 * Restore congestion window state if a spurious timeout
1428 * was detected.
1429 */
1430static void
1431tcp_bad_rexmt_restore_state(struct tcpcb *tp, struct tcphdr *th)
1432{
1433 if (TSTMP_SUPPORTED(tp)) {
1434 u_int32_t fsize, acked;
1435 fsize = tp->snd_max - th->th_ack;
1436 acked = BYTES_ACKED(th, tp);
1437
1438 /*
1439 * Implement bad retransmit recovery as
1440 * described in RFC 4015.
1441 */
1442 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1443
1444 /* Initialize cwnd to the initial window */
1445 if (CC_ALGO(tp)->cwnd_init != NULL)
1446 CC_ALGO(tp)->cwnd_init(tp);
1447
1448 tp->snd_cwnd = fsize + min(acked, tp->snd_cwnd);
39037602 1449
39236c6e
A
1450 } else {
1451 tp->snd_cwnd = tp->snd_cwnd_prev;
1452 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1453 if (tp->t_flags & TF_WASFRECOVERY)
1454 ENTER_FASTRECOVERY(tp);
3e170ce0
A
1455
1456 /* Do not use the loss flight size in this case */
1457 tp->t_lossflightsize = 0;
39236c6e 1458 }
fe8ab488 1459 tp->snd_cwnd = max(tp->snd_cwnd, TCP_CC_CWND_INIT_BYTES);
39236c6e
A
1460 tp->snd_recover = tp->snd_recover_prev;
1461 tp->snd_nxt = tp->snd_max;
39236c6e
A
1462
1463 /* Fix send socket buffer to reflect the change in cwnd */
1464 tcp_bad_rexmt_fix_sndbuf(tp);
1465
1466 /*
39037602 1467 * This RTT might reflect the extra delay induced
39236c6e
A
1468 * by the network. Skip using this sample for RTO
1469 * calculation and mark the connection so we can
1470 * recompute RTT when the next eligible sample is
1471 * found.
1472 */
1473 tp->t_flagsext |= TF_RECOMPUTE_RTT;
1474 tp->t_badrexmt_time = tcp_now;
1475 tp->t_rtttime = 0;
1476}
1477
fe8ab488
A
1478/*
1479 * If the previous packet was sent in retransmission timer, and it was
1480 * not needed, then restore the congestion window to the state before that
1481 * transmission.
1482 *
1483 * If the last packet was sent in tail loss probe timeout, check if that
1484 * recovered the last packet. If so, that will indicate a real loss and
1485 * the congestion window needs to be lowered.
1486 */
1487static void
1488tcp_bad_rexmt_check(struct tcpcb *tp, struct tcphdr *th, struct tcpopt *to)
1489{
1490 if (tp->t_rxtshift > 0 &&
1491 tcp_detect_bad_rexmt(tp, th, to, tp->t_rxtstart)) {
1492 ++tcpstat.tcps_sndrexmitbad;
1493 tcp_bad_rexmt_restore_state(tp, th);
1494 tcp_ccdbg_trace(tp, th, TCP_CC_BAD_REXMT_RECOVERY);
1495 } else if ((tp->t_flagsext & TF_SENT_TLPROBE)
1496 && tp->t_tlphighrxt > 0
1497 && SEQ_GEQ(th->th_ack, tp->t_tlphighrxt)
1498 && !tcp_detect_bad_rexmt(tp, th, to, tp->t_tlpstart)) {
3e170ce0
A
1499 /*
1500 * check DSACK information also to make sure that
1501 * the TLP was indeed needed
1502 */
1503 if (tcp_rxtseg_dsack_for_tlp(tp)) {
1504 /*
1505 * received a DSACK to indicate that TLP was
1506 * not needed
1507 */
1508 tcp_rxtseg_clean(tp);
1509 goto out;
1510 }
1511
fe8ab488 1512 /*
39037602 1513 * The tail loss probe recovered the last packet and
fe8ab488
A
1514 * we need to adjust the congestion window to take
1515 * this loss into account.
1516 */
1517 ++tcpstat.tcps_tlp_recoverlastpkt;
1518 if (!IN_FASTRECOVERY(tp)) {
1519 tcp_reduce_congestion_window(tp);
1520 EXIT_FASTRECOVERY(tp);
1521 }
1522 tcp_ccdbg_trace(tp, th, TCP_CC_TLP_RECOVER_LASTPACKET);
3e170ce0
A
1523 } else if (tcp_rxtseg_detect_bad_rexmt(tp, th->th_ack)) {
1524 /*
1525 * All of the retransmitted segments were duplicated, this
1526 * can be an indication of bad fast retransmit.
1527 */
1528 tcpstat.tcps_dsack_badrexmt++;
1529 tcp_bad_rexmt_restore_state(tp, th);
1530 tcp_ccdbg_trace(tp, th, TCP_CC_DSACK_BAD_REXMT);
1531 tcp_rxtseg_clean(tp);
fe8ab488 1532 }
3e170ce0 1533out:
fe8ab488
A
1534 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1535 tp->t_tlphighrxt = 0;
1536 tp->t_tlpstart = 0;
1537
1538 /*
1539 * check if the latest ack was for a segment sent during PMTU
1540 * blackhole detection. If the timestamp on the ack is before
1541 * PMTU blackhole detection, then revert the size of the max
1542 * segment to previous size.
1543 */
1544 if (tp->t_rxtshift > 0 && (tp->t_flags & TF_BLACKHOLE) &&
1545 tp->t_pmtud_start_ts > 0 && TSTMP_SUPPORTED(tp)) {
39037602 1546 if ((to->to_flags & TOF_TS) && to->to_tsecr != 0
fe8ab488
A
1547 && TSTMP_LT(to->to_tsecr, tp->t_pmtud_start_ts)) {
1548 tcp_pmtud_revert_segment_size(tp);
1549 }
1550 }
1551 if (tp->t_pmtud_start_ts > 0)
1552 tp->t_pmtud_start_ts = 0;
1553}
1554
1555/*
1556 * Check if early retransmit can be attempted according to RFC 5827.
1557 *
1558 * If packet reordering is detected on a connection, fast recovery will
1559 * be delayed until it is clear that the packet was lost and not reordered.
1560 * But reordering detection is done only when SACK is enabled.
1561 *
1562 * On connections that do not support SACK, there is a limit on the number
1563 * of early retransmits that can be done per minute. This limit is needed
1564 * to make sure that too many packets are not retransmitted when there is
1565 * packet reordering.
1566 */
1567static void
1568tcp_early_rexmt_check (struct tcpcb *tp, struct tcphdr *th)
1569{
1570 u_int32_t obytes, snd_off;
1571 int32_t snd_len;
1572 struct socket *so = tp->t_inpcb->inp_socket;
1573
1574 if (early_rexmt && (SACK_ENABLED(tp) ||
1575 tp->t_early_rexmt_count < TCP_EARLY_REXMT_LIMIT) &&
1576 SEQ_GT(tp->snd_max, tp->snd_una) &&
39037602
A
1577 (tp->t_dupacks == 1 ||
1578 (SACK_ENABLED(tp) &&
fe8ab488
A
1579 !TAILQ_EMPTY(&tp->snd_holes)))) {
1580 /*
39037602 1581 * If there are only a few outstanding
fe8ab488
A
1582 * segments on the connection, we might need
1583 * to lower the retransmit threshold. This
39037602 1584 * will allow us to do Early Retransmit as
fe8ab488
A
1585 * described in RFC 5827.
1586 */
39037602 1587 if (SACK_ENABLED(tp) &&
fe8ab488
A
1588 !TAILQ_EMPTY(&tp->snd_holes)) {
1589 obytes = (tp->snd_max - tp->snd_fack) +
1590 tp->sackhint.sack_bytes_rexmit;
1591 } else {
39037602 1592 obytes = (tp->snd_max - tp->snd_una);
fe8ab488
A
1593 }
1594
1595 /*
39037602 1596 * In order to lower retransmit threshold the
fe8ab488 1597 * following two conditions must be met.
39037602 1598 * 1. the amount of outstanding data is less
fe8ab488 1599 * than 4*SMSS bytes
39037602
A
1600 * 2. there is no unsent data ready for
1601 * transmission or the advertised window
fe8ab488
A
1602 * will limit sending new segments.
1603 */
1604 snd_off = tp->snd_max - tp->snd_una;
1605 snd_len = min(so->so_snd.sb_cc, tp->snd_wnd) - snd_off;
39037602 1606 if (obytes < (tp->t_maxseg << 2) &&
fe8ab488
A
1607 snd_len <= 0) {
1608 u_int32_t osegs;
1609
1610 osegs = obytes / tp->t_maxseg;
1611 if ((osegs * tp->t_maxseg) < obytes)
1612 osegs++;
1613
39037602
A
1614 /*
1615 * Since the connection might have already
fe8ab488
A
1616 * received some dupacks, we add them to
1617 * to the outstanding segments count to get
1618 * the correct retransmit threshold.
1619 *
39037602 1620 * By checking for early retransmit after
fe8ab488 1621 * receiving some duplicate acks when SACK
39037602
A
1622 * is supported, the connection will
1623 * enter fast recovery even if multiple
fe8ab488
A
1624 * segments are lost in the same window.
1625 */
1626 osegs += tp->t_dupacks;
1627 if (osegs < 4) {
39037602 1628 tp->t_rexmtthresh =
fe8ab488
A
1629 ((osegs - 1) > 1) ? (osegs - 1) : 1;
1630 tp->t_rexmtthresh =
1631 min(tp->t_rexmtthresh, tcprexmtthresh);
1632 tp->t_rexmtthresh =
1633 max(tp->t_rexmtthresh, tp->t_dupacks);
1634
1635 if (tp->t_early_rexmt_count == 0)
1636 tp->t_early_rexmt_win = tcp_now;
1637
1638 if (tp->t_flagsext & TF_SENT_TLPROBE) {
1639 tcpstat.tcps_tlp_recovery++;
1640 tcp_ccdbg_trace(tp, th,
1641 TCP_CC_TLP_RECOVERY);
1642 } else {
1643 tcpstat.tcps_early_rexmt++;
1644 tp->t_early_rexmt_count++;
1645 tcp_ccdbg_trace(tp, th,
1646 TCP_CC_EARLY_RETRANSMIT);
1647 }
1648 }
1649 }
1650 }
1651
1652 /*
1653 * If we ever sent a TLP probe, the acknowledgement will trigger
1654 * early retransmit because the value of snd_fack will be close
1655 * to snd_max. This will take care of adjustments to the
1656 * congestion window. So we can reset TF_SENT_PROBE flag.
1657 */
1658 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1659 tp->t_tlphighrxt = 0;
1660 tp->t_tlpstart = 0;
1661}
1662
3e170ce0 1663static boolean_t
39037602 1664tcp_tfo_syn(struct tcpcb *tp, struct tcpopt *to)
3e170ce0
A
1665{
1666 u_char out[CCAES_BLOCK_SIZE];
1667 unsigned char len;
1668
1669 if (!(to->to_flags & (TOF_TFO | TOF_TFOREQ)) ||
1670 !(tcp_fastopen & TCP_FASTOPEN_SERVER))
1671 return (FALSE);
1672
1673 if ((to->to_flags & TOF_TFOREQ)) {
1674 tp->t_tfo_flags |= TFO_F_OFFER_COOKIE;
1675
1676 tp->t_tfo_stats |= TFO_S_COOKIEREQ_RECV;
1677 tcpstat.tcps_tfo_cookie_req_rcv++;
1678 return (FALSE);
1679 }
1680
1681 /* Ok, then it must be an offered cookie. We need to check that ... */
1682 tcp_tfo_gen_cookie(tp->t_inpcb, out, sizeof(out));
1683
1684 len = *to->to_tfo - TCPOLEN_FASTOPEN_REQ;
1685 to->to_tfo++;
1686 if (memcmp(out, to->to_tfo, len)) {
1687 /* Cookies are different! Let's return and offer a new cookie */
1688 tp->t_tfo_flags |= TFO_F_OFFER_COOKIE;
1689
1690 tp->t_tfo_stats |= TFO_S_COOKIE_INVALID;
1691 tcpstat.tcps_tfo_cookie_invalid++;
1692 return (FALSE);
1693 }
1694
1695 if (OSIncrementAtomic(&tcp_tfo_halfcnt) >= tcp_tfo_backlog) {
1696 /* Need to decrement again as we just increased it... */
1697 OSDecrementAtomic(&tcp_tfo_halfcnt);
1698 return (FALSE);
1699 }
1700
1701 tp->t_tfo_flags |= TFO_F_COOKIE_VALID;
1702
1703 tp->t_tfo_stats |= TFO_S_SYNDATA_RCV;
1704 tcpstat.tcps_tfo_syn_data_rcv++;
1705
1706 return (TRUE);
1707}
1708
1709static void
39037602 1710tcp_tfo_synack(struct tcpcb *tp, struct tcpopt *to)
3e170ce0
A
1711{
1712 if (to->to_flags & TOF_TFO) {
1713 unsigned char len = *to->to_tfo - TCPOLEN_FASTOPEN_REQ;
1714
1715 /*
1716 * If this happens, things have gone terribly wrong. len should
4bd07ac2 1717 * have been checked in tcp_dooptions.
3e170ce0
A
1718 */
1719 VERIFY(len <= TFO_COOKIE_LEN_MAX);
1720
1721 to->to_tfo++;
1722
1723 tcp_cache_set_cookie(tp, to->to_tfo, len);
1724 tcp_heuristic_tfo_success(tp);
1725
1726 tp->t_tfo_stats |= TFO_S_COOKIE_RCV;
1727 tcpstat.tcps_tfo_cookie_rcv++;
39037602
A
1728 if (tp->t_tfo_flags & TFO_F_COOKIE_SENT) {
1729 tcpstat.tcps_tfo_cookie_wrong++;
1730 tp->t_tfo_stats |= TFO_S_COOKIE_WRONG;
1731 }
3e170ce0
A
1732 } else {
1733 /*
1734 * Thus, no cookie in the response, but we either asked for one
1735 * or sent SYN+DATA. Now, we need to check whether we had to
1736 * rexmit the SYN. If that's the case, it's better to start
1737 * backing of TFO-cookie requests.
1738 */
39037602
A
1739 if (tp->t_tfo_flags & TFO_F_SYN_LOSS) {
1740 tp->t_tfo_stats |= TFO_S_SYN_LOSS;
1741 tcpstat.tcps_tfo_syn_loss++;
1742
1743 tcp_heuristic_tfo_loss(tp);
1744 } else {
1745 if (tp->t_tfo_flags & TFO_F_COOKIE_REQ) {
1746 tp->t_tfo_stats |= TFO_S_NO_COOKIE_RCV;
1747 tcpstat.tcps_tfo_no_cookie_rcv++;
1748 }
1749
1750 tcp_heuristic_tfo_success(tp);
1751 }
3e170ce0
A
1752 }
1753}
1754
1755static void
1756tcp_tfo_rcv_probe(struct tcpcb *tp, int tlen)
1757{
5ba3f43e
A
1758 if (tlen != 0)
1759 return;
3e170ce0 1760
5ba3f43e
A
1761 tp->t_tfo_probe_state = TFO_PROBE_PROBING;
1762
1763 /*
1764 * We send the probe out rather quickly (after one RTO). It does not
1765 * really hurt that much, it's only one additional segment on the wire.
1766 */
1767 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp, (TCP_REXMTVAL(tp)));
3e170ce0
A
1768}
1769
1770static void
1771tcp_tfo_rcv_data(struct tcpcb *tp)
1772{
1773 /* Transition from PROBING to NONE as data has been received */
5ba3f43e 1774 if (tp->t_tfo_probe_state >= TFO_PROBE_PROBING)
3e170ce0 1775 tp->t_tfo_probe_state = TFO_PROBE_NONE;
3e170ce0
A
1776}
1777
1778static void
1779tcp_tfo_rcv_ack(struct tcpcb *tp, struct tcphdr *th)
1780{
1781 if (tp->t_tfo_probe_state == TFO_PROBE_PROBING &&
1782 tp->t_tfo_probes > 0) {
1783 if (th->th_seq == tp->rcv_nxt) {
1784 /* No hole, so stop probing */
1785 tp->t_tfo_probe_state = TFO_PROBE_NONE;
1786 } else if (SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1787 /* There is a hole! Wait a bit for data... */
1788 tp->t_tfo_probe_state = TFO_PROBE_WAIT_DATA;
1789 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
1790 TCP_REXMTVAL(tp));
1791 }
1792 }
1793}
1794
39037602
A
1795/*
1796 * Update snd_wnd information.
1797 */
1798static inline bool
1799tcp_update_window(struct tcpcb *tp, int thflags, struct tcphdr * th,
1800 u_int32_t tiwin, int tlen)
1801{
1802 /* Don't look at the window if there is no ACK flag */
1803 if ((thflags & TH_ACK) &&
1804 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1805 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
1806 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
1807 /* keep track of pure window updates */
1808 if (tlen == 0 &&
1809 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1810 tcpstat.tcps_rcvwinupd++;
1811 tp->snd_wnd = tiwin;
1812 tp->snd_wl1 = th->th_seq;
1813 tp->snd_wl2 = th->th_ack;
1814 if (tp->snd_wnd > tp->max_sndwnd)
1815 tp->max_sndwnd = tp->snd_wnd;
5ba3f43e
A
1816
1817 if (tp->t_inpcb->inp_socket->so_flags & SOF_MP_SUBFLOW)
1818 mptcp_update_window_fallback(tp);
39037602
A
1819 return (true);
1820 }
1821 return (false);
1822}
1823
1c79356b 1824void
39037602 1825tcp_input(struct mbuf *m, int off0)
1c79356b 1826{
39037602
A
1827 struct tcphdr *th;
1828 struct ip *ip = NULL;
1829 struct inpcb *inp;
1c79356b
A
1830 u_char *optp = NULL;
1831 int optlen = 0;
39236c6e 1832 int tlen, off;
9bccf70c 1833 int drop_hdrlen;
39037602
A
1834 struct tcpcb *tp = 0;
1835 int thflags;
1c79356b
A
1836 struct socket *so = 0;
1837 int todrop, acked, ourfinisacked, needoutput = 0;
1838 struct in_addr laddr;
9bccf70c 1839#if INET6
1c79356b
A
1840 struct in6_addr laddr6;
1841#endif
1842 int dropsocket = 0;
39037602 1843 int iss = 0, nosock = 0;
39236c6e 1844 u_int32_t tiwin, sack_bytes_acked = 0;
1c79356b 1845 struct tcpopt to; /* options in this segment */
1c79356b
A
1846#if TCPDEBUG
1847 short ostate = 0;
1848#endif
3e170ce0
A
1849#if IPFIREWALL
1850 struct sockaddr_in *next_hop = NULL;
91447636 1851 struct m_tag *fwd_tag;
3e170ce0 1852#endif /* IPFIREWALL */
2d21ac55 1853 u_char ip_ecn = IPTOS_ECN_NOTECT;
fe8ab488 1854 unsigned int ifscope;
6d2010ae 1855 uint8_t isconnected, isdisconnected;
39236c6e
A
1856 struct ifnet *ifp = m->m_pkthdr.rcvif;
1857 int pktf_sw_lro_pkt = (m->m_pkthdr.pkt_flags & PKTF_SW_LRO_PKT) ? 1 : 0;
1858 int nlropkts = (pktf_sw_lro_pkt == 1) ? m->m_pkthdr.lro_npkts : 1;
1859 int turnoff_lro = 0, win;
1860#if MPTCP
1861 struct mptcb *mp_tp = NULL;
39236c6e
A
1862#endif /* MPTCP */
1863 boolean_t cell = IFNET_IS_CELLULAR(ifp);
1864 boolean_t wifi = (!cell && IFNET_IS_WIFI(ifp));
fe8ab488 1865 boolean_t wired = (!wifi && IFNET_IS_WIRED(ifp));
3e170ce0 1866 boolean_t recvd_dsack = FALSE;
fe8ab488 1867 struct tcp_respond_args tra;
39236c6e 1868
316670eb 1869#define TCP_INC_VAR(stat, npkts) do { \
39236c6e 1870 stat += npkts; \
316670eb 1871} while (0)
c910b4d9 1872
316670eb 1873 TCP_INC_VAR(tcpstat.tcps_rcvtotal, nlropkts);
3e170ce0 1874#if IPFIREWALL
91447636 1875 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
b0d623f7
A
1876 if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
1877 fwd_tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
1878 KERNEL_TAG_TYPE_IPFORWARD, NULL);
1879 } else {
1880 fwd_tag = NULL;
1881 }
91447636 1882 if (fwd_tag != NULL) {
39037602 1883 struct ip_fwd_tag *ipfwd_tag =
39236c6e
A
1884 (struct ip_fwd_tag *)(fwd_tag+1);
1885
91447636
A
1886 next_hop = ipfwd_tag->next_hop;
1887 m_tag_delete(m, fwd_tag);
1888 }
3e170ce0 1889#endif /* IPFIREWALL */
39236c6e 1890
1c79356b
A
1891#if INET6
1892 struct ip6_hdr *ip6 = NULL;
9bccf70c 1893 int isipv6;
1c79356b 1894#endif /* INET6 */
9bccf70c 1895 int rstreason; /* For badport_bandlim accounting purposes */
1c79356b 1896 struct proc *proc0=current_proc();
39236c6e 1897
1c79356b
A
1898 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_START,0,0,0,0,0);
1899
9bccf70c
A
1900#if INET6
1901 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
1902#endif
1c79356b
A
1903 bzero((char *)&to, sizeof(to));
1904
1c79356b
A
1905#if INET6
1906 if (isipv6) {
39037602
A
1907 /*
1908 * Expect 32-bit aligned data pointer on
1909 * strict-align platforms
39236c6e 1910 */
316670eb
A
1911 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
1912
9bccf70c 1913 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
1c79356b 1914 ip6 = mtod(m, struct ip6_hdr *);
9bccf70c 1915 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
316670eb 1916 th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
9bccf70c 1917
39236c6e
A
1918 if (tcp_input_checksum(AF_INET6, m, th, off0, tlen))
1919 goto dropnosock;
6d2010ae 1920
9bccf70c
A
1921 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
1922 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
1923 th->th_seq, th->th_ack, th->th_win);
1c79356b 1924 /*
9bccf70c
A
1925 * Be proactive about unspecified IPv6 address in source.
1926 * As we use all-zero to indicate unbounded/unconnected pcb,
1927 * unspecified IPv6 address can be used to confuse us.
1928 *
1929 * Note that packets with unspecified IPv6 destination is
1930 * already dropped in ip6_input.
1c79356b 1931 */
9bccf70c
A
1932 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1933 /* XXX stat */
39236c6e 1934 IF_TCP_STATINC(ifp, unspecv6);
91447636 1935 goto dropnosock;
1c79356b 1936 }
39236c6e 1937 DTRACE_TCP5(receive, struct mbuf *, m, struct inpcb *, NULL,
39037602 1938 struct ip6_hdr *, ip6, struct tcpcb *, NULL,
6d2010ae 1939 struct tcphdr *, th);
39236c6e
A
1940
1941 ip_ecn = (ntohl(ip6->ip6_flow) >> 20) & IPTOS_ECN_MASK;
9bccf70c
A
1942 } else
1943#endif /* INET6 */
ac5ea4a9 1944 {
9bccf70c
A
1945 /*
1946 * Get IP and TCP header together in first mbuf.
1947 * Note: IP leaves IP header in first mbuf.
1948 */
1949 if (off0 > sizeof (struct ip)) {
5ba3f43e 1950 ip_stripoptions(m);
9bccf70c 1951 off0 = sizeof(struct ip);
9bccf70c
A
1952 }
1953 if (m->m_len < sizeof (struct tcpiphdr)) {
1954 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
1955 tcpstat.tcps_rcvshort++;
1956 return;
0b4e3aa0 1957 }
9bccf70c 1958 }
316670eb
A
1959
1960 /* Expect 32-bit aligned data pointer on strict-align platforms */
1961 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
1962
9bccf70c 1963 ip = mtod(m, struct ip *);
316670eb 1964 th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
9bccf70c 1965 tlen = ip->ip_len;
0b4e3aa0 1966
39236c6e 1967 if (tcp_input_checksum(AF_INET, m, th, off0, tlen))
91447636 1968 goto dropnosock;
39236c6e 1969
9bccf70c
A
1970#if INET6
1971 /* Re-initialization for later version check */
1972 ip->ip_v = IPVERSION;
1973#endif
2d21ac55 1974 ip_ecn = (ip->ip_tos & IPTOS_ECN_MASK);
316670eb
A
1975
1976 DTRACE_TCP5(receive, struct mbuf *, m, struct inpcb *, NULL,
1977 struct ip *, ip, struct tcpcb *, NULL, struct tcphdr *, th);
39236c6e 1978
316670eb
A
1979 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
1980 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
1981 th->th_seq, th->th_ack, th->th_win);
1982
ac5ea4a9 1983 }
1c79356b
A
1984
1985 /*
1986 * Check that TCP offset makes sense,
39037602 1987 * pull out TCP options and adjust length.
1c79356b 1988 */
9bccf70c
A
1989 off = th->th_off << 2;
1990 if (off < sizeof (struct tcphdr) || off > tlen) {
1c79356b 1991 tcpstat.tcps_rcvbadoff++;
39236c6e 1992 IF_TCP_STATINC(ifp, badformat);
91447636 1993 goto dropnosock;
1c79356b 1994 }
9bccf70c
A
1995 tlen -= off; /* tlen is used instead of ti->ti_len */
1996 if (off > sizeof (struct tcphdr)) {
1c79356b
A
1997#if INET6
1998 if (isipv6) {
91447636 1999 IP6_EXTHDR_CHECK(m, off0, off, return);
1c79356b 2000 ip6 = mtod(m, struct ip6_hdr *);
316670eb 2001 th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
1c79356b
A
2002 } else
2003#endif /* INET6 */
2d21ac55
A
2004 {
2005 if (m->m_len < sizeof(struct ip) + off) {
2006 if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
2007 tcpstat.tcps_rcvshort++;
2008 return;
2009 }
2010 ip = mtod(m, struct ip *);
316670eb 2011 th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
1c79356b
A
2012 }
2013 }
9bccf70c 2014 optlen = off - sizeof (struct tcphdr);
1c79356b 2015 optp = (u_char *)(th + 1);
39037602 2016 /*
1c79356b
A
2017 * Do quick retrieval of timestamp options ("options
2018 * prediction?"). If timestamp is the only option and it's
2019 * formatted as recommended in RFC 1323 appendix A, we
2020 * quickly get the values now and not bother calling
2021 * tcp_dooptions(), etc.
2022 */
2023 if ((optlen == TCPOLEN_TSTAMP_APPA ||
2d21ac55 2024 (optlen > TCPOLEN_TSTAMP_APPA &&
1c79356b 2025 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
316670eb 2026 *(u_int32_t *)(void *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
2d21ac55 2027 (th->th_flags & TH_SYN) == 0) {
8ad349bb 2028 to.to_flags |= TOF_TS;
316670eb
A
2029 to.to_tsval = ntohl(*(u_int32_t *)(void *)(optp + 4));
2030 to.to_tsecr = ntohl(*(u_int32_t *)(void *)(optp + 8));
1c79356b
A
2031 optp = NULL; /* we've parsed the options */
2032 }
2033 }
2034 thflags = th->th_flags;
2035
9bccf70c
A
2036#if TCP_DROP_SYNFIN
2037 /*
2038 * If the drop_synfin option is enabled, drop all packets with
2039 * both the SYN and FIN bits set. This prevents e.g. nmap from
2040 * identifying the TCP/IP stack.
2041 *
8ad349bb 2042 * This is a violation of the TCP specification.
9bccf70c 2043 */
316670eb 2044 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN)) {
39236c6e 2045 IF_TCP_STATINC(ifp, synfin);
91447636 2046 goto dropnosock;
316670eb 2047 }
b0d623f7 2048#endif
1c79356b
A
2049
2050 /*
8ad349bb 2051 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
9bccf70c
A
2052 * until after ip6_savecontrol() is called and before other functions
2053 * which don't want those proto headers.
2054 * Because ip6_savecontrol() is going to parse the mbuf to
2055 * search for data to be passed up to user-land, it wants mbuf
2056 * parameters to be unchanged.
1c79356b 2057 */
9bccf70c 2058 drop_hdrlen = off0 + off;
39037602 2059
316670eb
A
2060 /* Since this is an entry point for input processing of tcp packets, we
2061 * can update the tcp clock here.
2062 */
2063 calculate_tcp_clock();
2064
2065 /*
39236c6e
A
2066 * Record the interface where this segment arrived on; this does not
2067 * affect normal data output (for non-detached TCP) as it provides a
2068 * hint about which route and interface to use for sending in the
2069 * absence of a PCB, when scoped routing (and thus source interface
2070 * selection) are enabled.
2071 */
2072 if ((m->m_pkthdr.pkt_flags & PKTF_LOOP) || m->m_pkthdr.rcvif == NULL)
2073 ifscope = IFSCOPE_NONE;
2074 else
2075 ifscope = m->m_pkthdr.rcvif->if_index;
316670eb
A
2076
2077 /*
2078 * Convert TCP protocol specific fields to host format.
2079 */
2080
2081#if BYTE_ORDER != BIG_ENDIAN
2082 NTOHL(th->th_seq);
2083 NTOHL(th->th_ack);
2084 NTOHS(th->th_win);
2085 NTOHS(th->th_urp);
2086#endif
1c79356b
A
2087
2088 /*
2089 * Locate pcb for segment.
2090 */
2091findpcb:
6d2010ae
A
2092
2093 isconnected = FALSE;
2094 isdisconnected = FALSE;
2095
1c79356b 2096#if IPFIREWALL_FORWARD
91447636 2097 if (next_hop != NULL
1c79356b 2098#if INET6
2d21ac55 2099 && isipv6 == 0 /* IPv6 support is not yet */
1c79356b
A
2100#endif /* INET6 */
2101 ) {
2102 /*
2103 * Diverted. Pretend to be the destination.
39037602 2104 * already got one like this?
1c79356b
A
2105 */
2106 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
2107 ip->ip_dst, th->th_dport, 0, m->m_pkthdr.rcvif);
2108 if (!inp) {
39037602 2109 /*
1c79356b
A
2110 * No, then it's new. Try find the ambushing socket
2111 */
91447636 2112 if (!next_hop->sin_port) {
1c79356b 2113 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src,
91447636 2114 th->th_sport, next_hop->sin_addr,
1c79356b
A
2115 th->th_dport, 1, m->m_pkthdr.rcvif);
2116 } else {
2117 inp = in_pcblookup_hash(&tcbinfo,
2118 ip->ip_src, th->th_sport,
91447636
A
2119 next_hop->sin_addr,
2120 ntohs(next_hop->sin_port), 1,
1c79356b
A
2121 m->m_pkthdr.rcvif);
2122 }
2123 }
1c79356b
A
2124 } else
2125#endif /* IPFIREWALL_FORWARD */
9bccf70c 2126 {
1c79356b
A
2127#if INET6
2128 if (isipv6)
2129 inp = in6_pcblookup_hash(&tcbinfo, &ip6->ip6_src, th->th_sport,
2130 &ip6->ip6_dst, th->th_dport, 1,
2131 m->m_pkthdr.rcvif);
2132 else
2133#endif /* INET6 */
2134 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
2135 ip->ip_dst, th->th_dport, 1, m->m_pkthdr.rcvif);
9bccf70c 2136 }
1c79356b 2137
c910b4d9
A
2138 /*
2139 * Use the interface scope information from the PCB for outbound
2140 * segments. If the PCB isn't present and if scoped routing is
2141 * enabled, tcp_respond will use the scope of the interface where
2142 * the segment arrived on.
2143 */
2144 if (inp != NULL && (inp->inp_flags & INP_BOUND_IF))
316670eb 2145 ifscope = inp->inp_boundifp->if_index;
1c79356b
A
2146
2147 /*
2148 * If the state is CLOSED (i.e., TCB does not exist) then
2149 * all data in the incoming segment is discarded.
2150 * If the TCB exists but is in CLOSED state, it is embryonic,
2151 * but should either do a listen or a connect soon.
2152 */
2153 if (inp == NULL) {
9bccf70c 2154 if (log_in_vain) {
1c79356b 2155#if INET6
91447636 2156 char dbuf[MAX_IPv6_STR_LEN], sbuf[MAX_IPv6_STR_LEN];
1c79356b 2157#else /* INET6 */
91447636 2158 char dbuf[MAX_IPv4_STR_LEN], sbuf[MAX_IPv4_STR_LEN];
1c79356b
A
2159#endif /* INET6 */
2160
2161#if INET6
2162 if (isipv6) {
91447636
A
2163 inet_ntop(AF_INET6, &ip6->ip6_dst, dbuf, sizeof(dbuf));
2164 inet_ntop(AF_INET6, &ip6->ip6_src, sbuf, sizeof(sbuf));
9bccf70c 2165 } else
1c79356b 2166#endif
91447636
A
2167 {
2168 inet_ntop(AF_INET, &ip->ip_dst, dbuf, sizeof(dbuf));
2169 inet_ntop(AF_INET, &ip->ip_src, sbuf, sizeof(sbuf));
2170 }
9bccf70c
A
2171 switch (log_in_vain) {
2172 case 1:
2173 if(thflags & TH_SYN)
2174 log(LOG_INFO,
91447636
A
2175 "Connection attempt to TCP %s:%d from %s:%d\n",
2176 dbuf, ntohs(th->th_dport),
2177 sbuf,
2178 ntohs(th->th_sport));
9bccf70c
A
2179 break;
2180 case 2:
2181 log(LOG_INFO,
91447636
A
2182 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
2183 dbuf, ntohs(th->th_dport), sbuf,
2184 ntohs(th->th_sport), thflags);
2185 break;
2186 case 3:
39236c6e 2187 case 4:
316670eb 2188 if ((thflags & TH_SYN) && !(thflags & TH_ACK) &&
91447636
A
2189 !(m->m_flags & (M_BCAST | M_MCAST)) &&
2190#if INET6
2191 ((isipv6 && !IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) ||
2192 (!isipv6 && ip->ip_dst.s_addr != ip->ip_src.s_addr))
2193#else
2194 ip->ip_dst.s_addr != ip->ip_src.s_addr
2195#endif
2196 )
2197 log_in_vain_log((LOG_INFO,
2198 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
2199 dbuf, ntohs(th->th_dport),
2200 sbuf,
2201 ntohs(th->th_sport)));
9bccf70c
A
2202 break;
2203 default:
2204 break;
1c79356b 2205 }
1c79356b 2206 }
39037602 2207 if (blackhole) {
91447636 2208 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type != IFT_LOOP)
39037602 2209
91447636
A
2210 switch (blackhole) {
2211 case 1:
2212 if (thflags & TH_SYN)
2213 goto dropnosock;
2214 break;
2215 case 2:
2216 goto dropnosock;
2217 default:
2218 goto dropnosock;
2219 }
9bccf70c
A
2220 }
2221 rstreason = BANDLIM_RST_CLOSEDPORT;
39236c6e 2222 IF_TCP_STATINC(ifp, noconnnolist);
91447636
A
2223 goto dropwithresetnosock;
2224 }
2225 so = inp->inp_socket;
2226 if (so == NULL) {
b0d623f7
A
2227 /* This case shouldn't happen as the socket shouldn't be null
2228 * if inp_state isn't set to INPCB_STATE_DEAD
2229 * But just in case, we pretend we didn't find the socket if we hit this case
2230 * as this isn't cause for a panic (the socket might be leaked however)...
2231 */
2232 inp = NULL;
91447636 2233#if TEMPDEBUG
b0d623f7 2234 printf("tcp_input: no more socket for inp=%x. This shouldn't happen\n", inp);
91447636
A
2235#endif
2236 goto dropnosock;
1c79356b 2237 }
8ad349bb 2238
5ba3f43e 2239 socket_lock(so, 1);
91447636 2240 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
5ba3f43e 2241 socket_unlock(so, 1);
3e170ce0 2242 inp = NULL; // pretend we didn't find it
91447636
A
2243 goto dropnosock;
2244 }
2245
3e170ce0 2246#if NECP
5ba3f43e
A
2247 if (so->so_state & SS_ISCONNECTED) {
2248 // Connected TCP sockets have a fully-bound local and remote,
2249 // so the policy check doesn't need to override addresses
2250 if (!necp_socket_is_allowed_to_send_recv(inp, NULL, NULL)) {
2251 IF_TCP_STATINC(ifp, badformat);
3e170ce0
A
2252 goto drop;
2253 }
5ba3f43e
A
2254 } else {
2255#if INET6
2256 if (isipv6) {
2257 if (!necp_socket_is_allowed_to_send_recv_v6(inp,
2258 th->th_dport, th->th_sport, &ip6->ip6_dst,
2259 &ip6->ip6_src, ifp, NULL, NULL)) {
2260 IF_TCP_STATINC(ifp, badformat);
2261 goto drop;
2262 }
2263 } else
3e170ce0 2264#endif
5ba3f43e
A
2265 {
2266 if (!necp_socket_is_allowed_to_send_recv_v4(inp,
2267 th->th_dport, th->th_sport, &ip->ip_dst, &ip->ip_src,
2268 ifp, NULL, NULL)) {
2269 IF_TCP_STATINC(ifp, badformat);
2270 goto drop;
2271 }
3e170ce0
A
2272 }
2273 }
2274#endif /* NECP */
2275
1c79356b 2276 tp = intotcpcb(inp);
9bccf70c
A
2277 if (tp == 0) {
2278 rstreason = BANDLIM_RST_CLOSEDPORT;
39236c6e 2279 IF_TCP_STATINC(ifp, noconnlist);
1c79356b 2280 goto dropwithreset;
9bccf70c 2281 }
1c79356b
A
2282 if (tp->t_state == TCPS_CLOSED)
2283 goto drop;
9bccf70c 2284
1c79356b
A
2285 /* Unscale the window into a 32-bit value. */
2286 if ((thflags & TH_SYN) == 0)
2287 tiwin = th->th_win << tp->snd_scale;
2288 else
2289 tiwin = th->th_win;
2290
2d21ac55
A
2291#if CONFIG_MACF_NET
2292 if (mac_inpcb_check_deliver(inp, m, AF_INET, SOCK_STREAM))
2293 goto drop;
2294#endif
2295
39236c6e 2296 /* Avoid processing packets while closing a listen socket */
39037602
A
2297 if (tp->t_state == TCPS_LISTEN &&
2298 (so->so_options & SO_ACCEPTCONN) == 0)
b7266188
A
2299 goto drop;
2300
1c79356b
A
2301 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
2302#if TCPDEBUG
2303 if (so->so_options & SO_DEBUG) {
2304 ostate = tp->t_state;
2305#if INET6
2306 if (isipv6)
9bccf70c
A
2307 bcopy((char *)ip6, (char *)tcp_saveipgen,
2308 sizeof(*ip6));
1c79356b 2309 else
1c79356b 2310#endif /* INET6 */
9bccf70c 2311 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1c79356b
A
2312 tcp_savetcp = *th;
2313 }
2314#endif
2315 if (so->so_options & SO_ACCEPTCONN) {
39037602 2316 struct tcpcb *tp0 = tp;
1c79356b 2317 struct socket *so2;
1c79356b 2318 struct socket *oso;
91447636 2319 struct sockaddr_storage from;
1c79356b
A
2320#if INET6
2321 struct inpcb *oinp = sotoinpcb(so);
2322#endif /* INET6 */
316670eb 2323 struct ifnet *head_ifscope;
fe8ab488 2324 unsigned int head_nocell, head_recvanyif,
39037602
A
2325 head_noexpensive, head_awdl_unrestricted,
2326 head_intcoproc_allowed;
c910b4d9
A
2327
2328 /* Get listener's bound-to-interface, if any */
2329 head_ifscope = (inp->inp_flags & INP_BOUND_IF) ?
316670eb 2330 inp->inp_boundifp : NULL;
6d2010ae 2331 /* Get listener's no-cellular information, if any */
fe8ab488 2332 head_nocell = INP_NO_CELLULAR(inp);
316670eb
A
2333 /* Get listener's recv-any-interface, if any */
2334 head_recvanyif = (inp->inp_flags & INP_RECV_ANYIF);
fe8ab488
A
2335 /* Get listener's no-expensive information, if any */
2336 head_noexpensive = INP_NO_EXPENSIVE(inp);
2337 head_awdl_unrestricted = INP_AWDL_UNRESTRICTED(inp);
39037602 2338 head_intcoproc_allowed = INP_INTCOPROC_ALLOWED(inp);
1c79356b 2339
9bccf70c 2340 /*
7e4a7d39
A
2341 * If the state is LISTEN then ignore segment if it contains an RST.
2342 * If the segment contains an ACK then it is bad and send a RST.
2343 * If it does not contain a SYN then it is not interesting; drop it.
2344 * If it is from this socket, drop it, it must be forged.
9bccf70c 2345 */
1c79356b 2346 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
39236c6e
A
2347 IF_TCP_STATINC(ifp, listbadsyn);
2348
7e4a7d39
A
2349 if (thflags & TH_RST) {
2350 goto drop;
2351 }
1c79356b 2352 if (thflags & TH_ACK) {
7e4a7d39 2353 tp = NULL;
1c79356b 2354 tcpstat.tcps_badsyn++;
9bccf70c 2355 rstreason = BANDLIM_RST_OPENPORT;
1c79356b
A
2356 goto dropwithreset;
2357 }
7e4a7d39
A
2358
2359 /* We come here if there is no SYN set */
2360 tcpstat.tcps_badsyn++;
1c79356b
A
2361 goto drop;
2362 }
1c79356b 2363 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_START,0,0,0,0,0);
39037602 2364 if (th->th_dport == th->th_sport) {
7e4a7d39
A
2365#if INET6
2366 if (isipv6) {
2367 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
2368 &ip6->ip6_src))
2369 goto drop;
2370 } else
2371#endif /* INET6 */
2372 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
2373 goto drop;
2374 }
2375 /*
2376 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
2377 * in_broadcast() should never return true on a received
2378 * packet with M_BCAST not set.
2379 *
2380 * Packets with a multicast source address should also
2381 * be discarded.
2382 */
2383 if (m->m_flags & (M_BCAST|M_MCAST))
2384 goto drop;
2385#if INET6
2386 if (isipv6) {
2387 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2388 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2389 goto drop;
2390 } else
2391#endif
2392 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2393 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2394 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2395 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2396 goto drop;
2397
1c79356b 2398
9bccf70c
A
2399#if INET6
2400 /*
2401 * If deprecated address is forbidden,
2402 * we do not accept SYN to deprecated interface
2403 * address to prevent any new inbound connection from
2404 * getting established.
2405 * When we do not accept SYN, we send a TCP RST,
2406 * with deprecated source address (instead of dropping
2407 * it). We compromise it as it is much better for peer
2408 * to send a RST, and RST will be the final packet
2409 * for the exchange.
2410 *
2411 * If we do not forbid deprecated addresses, we accept
39236c6e
A
2412 * the SYN packet. RFC 4862 forbids dropping SYN in
2413 * this case.
9bccf70c
A
2414 */
2415 if (isipv6 && !ip6_use_deprecated) {
39236c6e
A
2416 uint32_t ia6_flags;
2417
2418 if (ip6_getdstifaddr_info(m, NULL,
2419 &ia6_flags) == 0) {
2420 if (ia6_flags & IN6_IFF_DEPRECATED) {
6d2010ae
A
2421 tp = NULL;
2422 rstreason = BANDLIM_RST_OPENPORT;
39236c6e 2423 IF_TCP_STATINC(ifp, deprecate6);
6d2010ae
A
2424 goto dropwithreset;
2425 }
9bccf70c
A
2426 }
2427 }
2428#endif
91447636 2429 if (so->so_filt) {
2d21ac55 2430#if INET6
91447636
A
2431 if (isipv6) {
2432 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&from;
39037602 2433
91447636
A
2434 sin6->sin6_len = sizeof(*sin6);
2435 sin6->sin6_family = AF_INET6;
2436 sin6->sin6_port = th->th_sport;
2437 sin6->sin6_flowinfo = 0;
2438 sin6->sin6_addr = ip6->ip6_src;
2439 sin6->sin6_scope_id = 0;
2d21ac55
A
2440 }
2441 else
2442#endif
2443 {
91447636 2444 struct sockaddr_in *sin = (struct sockaddr_in*)&from;
39037602 2445
91447636
A
2446 sin->sin_len = sizeof(*sin);
2447 sin->sin_family = AF_INET;
2448 sin->sin_port = th->th_sport;
2449 sin->sin_addr = ip->ip_src;
2450 }
2451 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
2452 } else {
2453 so2 = sonewconn(so, 0, NULL);
2454 }
1c79356b
A
2455 if (so2 == 0) {
2456 tcpstat.tcps_listendrop++;
2d21ac55 2457 if (tcp_dropdropablreq(so)) {
91447636
A
2458 if (so->so_filt)
2459 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
2460 else
2461 so2 = sonewconn(so, 0, NULL);
1c79356b 2462 }
39037602 2463 if (!so2)
1c79356b
A
2464 goto drop;
2465 }
b0d623f7
A
2466
2467 /* Point "inp" and "tp" in tandem to new socket */
2468 inp = (struct inpcb *)so2->so_pcb;
2469 tp = intotcpcb(inp);
91447636 2470
1c79356b 2471 oso = so;
5ba3f43e 2472 socket_unlock(so, 0); /* Unlock but keep a reference on listener for now */
91447636 2473
1c79356b 2474 so = so2;
5ba3f43e 2475 socket_lock(so, 1);
1c79356b 2476 /*
1c79356b
A
2477 * Mark socket as temporary until we're
2478 * committed to keeping it. The code at
2479 * ``drop'' and ``dropwithreset'' check the
2480 * flag dropsocket to see if the temporary
2481 * socket created here should be discarded.
2482 * We mark the socket as discardable until
2483 * we're committed to it below in TCPS_LISTEN.
7e4a7d39
A
2484 * There are some error conditions in which we
2485 * have to drop the temporary socket.
1c79356b
A
2486 */
2487 dropsocket++;
c910b4d9
A
2488 /*
2489 * Inherit INP_BOUND_IF from listener; testing if
316670eb 2490 * head_ifscope is non-NULL is sufficient, since it
c910b4d9
A
2491 * can only be set to a non-zero value earlier if
2492 * the listener has such a flag set.
2493 */
316670eb 2494 if (head_ifscope != NULL) {
c910b4d9 2495 inp->inp_flags |= INP_BOUND_IF;
316670eb
A
2496 inp->inp_boundifp = head_ifscope;
2497 } else {
2498 inp->inp_flags &= ~INP_BOUND_IF;
c910b4d9 2499 }
6d2010ae 2500 /*
fe8ab488 2501 * Inherit restrictions from listener.
6d2010ae 2502 */
fe8ab488
A
2503 if (head_nocell)
2504 inp_set_nocellular(inp);
2505 if (head_noexpensive)
2506 inp_set_noexpensive(inp);
2507 if (head_awdl_unrestricted)
2508 inp_set_awdl_unrestricted(inp);
39037602
A
2509 if (head_intcoproc_allowed)
2510 inp_set_intcoproc_allowed(inp);
316670eb
A
2511 /*
2512 * Inherit {IN,IN6}_RECV_ANYIF from listener.
2513 */
2514 if (head_recvanyif)
2515 inp->inp_flags |= INP_RECV_ANYIF;
2516 else
2517 inp->inp_flags &= ~INP_RECV_ANYIF;
1c79356b
A
2518#if INET6
2519 if (isipv6)
2520 inp->in6p_laddr = ip6->ip6_dst;
2521 else {
9bccf70c
A
2522 inp->inp_vflag &= ~INP_IPV6;
2523 inp->inp_vflag |= INP_IPV4;
1c79356b 2524#endif /* INET6 */
7e4a7d39 2525 inp->inp_laddr = ip->ip_dst;
1c79356b
A
2526#if INET6
2527 }
2528#endif /* INET6 */
1c79356b 2529 inp->inp_lport = th->th_dport;
91447636 2530 if (in_pcbinshash(inp, 0) != 0) {
1c79356b 2531 /*
9bccf70c
A
2532 * Undo the assignments above if we failed to
2533 * put the PCB on the hash lists.
1c79356b
A
2534 */
2535#if INET6
2536 if (isipv6)
2537 inp->in6p_laddr = in6addr_any;
2538 else
2539#endif /* INET6 */
316670eb 2540 inp->inp_laddr.s_addr = INADDR_ANY;
1c79356b 2541 inp->inp_lport = 0;
5ba3f43e
A
2542 socket_lock(oso, 0); /* release ref on parent */
2543 socket_unlock(oso, 1);
1c79356b
A
2544 goto drop;
2545 }
1c79356b
A
2546#if INET6
2547 if (isipv6) {
5ba3f43e
A
2548 /*
2549 * Inherit socket options from the listening
2550 * socket.
2551 * Note that in6p_inputopts are not (even
2552 * should not be) copied, since it stores
1c79356b 2553 * previously received options and is used to
5ba3f43e
A
2554 * detect if each new option is different than
2555 * the previous one and hence should be passed
2556 * to a user.
2557 * If we copied in6p_inputopts, a user would
2558 * not be able to receive options just after
2559 * calling the accept system call.
2560 */
1c79356b
A
2561 inp->inp_flags |=
2562 oinp->inp_flags & INP_CONTROLOPTS;
5ba3f43e
A
2563 if (oinp->in6p_outputopts)
2564 inp->in6p_outputopts =
2565 ip6_copypktopts(oinp->in6p_outputopts,
2566 M_NOWAIT);
1c79356b
A
2567 } else
2568#endif /* INET6 */
3e170ce0 2569 {
316670eb 2570 inp->inp_options = ip_srcroute();
3e170ce0
A
2571 inp->inp_ip_tos = oinp->inp_ip_tos;
2572 }
5ba3f43e 2573 socket_lock(oso, 0);
1c79356b
A
2574#if IPSEC
2575 /* copy old policy into new socket's */
9bccf70c
A
2576 if (sotoinpcb(oso)->inp_sp)
2577 {
2578 int error = 0;
2579 /* Is it a security hole here to silently fail to copy the policy? */
2580 if (inp->inp_sp != NULL)
2581 error = ipsec_init_policy(so, &inp->inp_sp);
2582 if (error != 0 || ipsec_copy_policy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
2583 printf("tcp_input: could not copy policy\n");
2584 }
1c79356b 2585#endif
b0d623f7 2586 /* inherit states from the listener */
6d2010ae
A
2587 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
2588 struct tcpcb *, tp, int32_t, TCPS_LISTEN);
1c79356b 2589 tp->t_state = TCPS_LISTEN;
9bccf70c 2590 tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT|TF_NODELAY);
3e170ce0 2591 tp->t_flagsext |= (tp0->t_flagsext & (TF_RXTFINDROP|TF_NOTIMEWAIT|TF_FASTOPEN));
b0d623f7 2592 tp->t_keepinit = tp0->t_keepinit;
39236c6e
A
2593 tp->t_keepcnt = tp0->t_keepcnt;
2594 tp->t_keepintvl = tp0->t_keepintvl;
2595 tp->t_adaptive_wtimo = tp0->t_adaptive_wtimo;
2596 tp->t_adaptive_rtimo = tp0->t_adaptive_rtimo;
91447636 2597 tp->t_inpcb->inp_ip_ttl = tp0->t_inpcb->inp_ip_ttl;
316670eb
A
2598 if ((so->so_flags & SOF_NOTSENT_LOWAT) != 0)
2599 tp->t_notsent_lowat = tp0->t_notsent_lowat;
39037602
A
2600 tp->t_inpcb->inp_flags2 |=
2601 tp0->t_inpcb->inp_flags2 & INP2_KEEPALIVE_OFFLOAD;
b0d623f7
A
2602
2603 /* now drop the reference on the listener */
5ba3f43e 2604 socket_unlock(oso, 1);
b0d623f7 2605
39037602 2606 tcp_set_max_rwinscale(tp, so, TCP_AUTORCVBUF_MAX(ifp));
1c79356b
A
2607
2608 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END,0,0,0,0,0);
2609 }
2610 }
5ba3f43e 2611 socket_lock_assert_owned(so);
6d2010ae 2612
743b1565 2613 if (tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
39037602
A
2614 /*
2615 * Evaluate the rate of arrival of packets to see if the
2616 * receiver can reduce the ack traffic. The algorithm to
2617 * stretch acks will be enabled if the connection meets
6d2010ae
A
2618 * certain criteria defined in tcp_stretch_ack_enable function.
2619 */
2620 if ((tp->t_flagsext & TF_RCVUNACK_WAITSS) != 0) {
316670eb 2621 TCP_INC_VAR(tp->rcv_waitforss, nlropkts);
6d2010ae 2622 }
39037602 2623 if (tcp_stretch_ack_enable(tp, thflags)) {
6d2010ae
A
2624 tp->t_flags |= TF_STRETCHACK;
2625 tp->t_flagsext &= ~(TF_RCVUNACK_WAITSS);
2626 tp->rcv_waitforss = 0;
2627 } else {
2628 tp->t_flags &= ~(TF_STRETCHACK);
2629 }
2630 if (TSTMP_GT(tp->rcv_unackwin, tcp_now)) {
2631 tp->rcv_by_unackwin += (tlen + off);
2632 } else {
2633 tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
2634 tp->rcv_by_unackwin = tlen + off;
2635 }
91447636 2636 }
316670eb 2637
39037602 2638 /*
316670eb
A
2639 * Keep track of how many bytes were received in the LRO packet
2640 */
39236c6e 2641 if ((pktf_sw_lro_pkt) && (nlropkts > 2)) {
316670eb
A
2642 tp->t_lropktlen += tlen;
2643 }
2d21ac55 2644 /*
39236c6e
A
2645 * Explicit Congestion Notification - Flag that we need to send ECT if
2646 * + The IP Congestion experienced flag was set.
2647 * + Socket is in established state
2648 * + We negotiated ECN in the TCP setup
2649 * + This isn't a pure ack (tlen > 0)
2650 * + The data is in the valid window
2651 *
2652 * TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
2d21ac55
A
2653 */
2654 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
3e170ce0
A
2655 TCP_ECN_ENABLED(tp) && tlen > 0 &&
2656 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2657 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
4bd07ac2 2658 tp->t_ecn_recv_ce++;
3e170ce0 2659 tcpstat.tcps_ecn_recv_ce++;
4bd07ac2 2660 INP_INC_IFNET_STAT(inp, ecn_recv_ce);
3e170ce0
A
2661 /* Mark this connection as it received CE from network */
2662 tp->ecn_flags |= TE_RECV_ECN_CE;
2d21ac55
A
2663 tp->ecn_flags |= TE_SENDECE;
2664 }
4bd07ac2 2665
2d21ac55 2666 /*
39236c6e
A
2667 * Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
2668 * bother doing extensive checks for state and whatnot.
2d21ac55 2669 */
3e170ce0 2670 if (thflags & TH_CWR) {
2d21ac55 2671 tp->ecn_flags &= ~TE_SENDECE;
4bd07ac2 2672 tp->t_ecn_recv_cwr++;
2d21ac55 2673 }
6d2010ae 2674
39037602
A
2675 /*
2676 * If we received an explicit notification of congestion in
6d2010ae 2677 * ip tos ecn bits or by the CWR bit in TCP header flags, reset
fe8ab488
A
2678 * the ack-strteching state. We need to handle ECN notification if
2679 * an ECN setup SYN was sent even once.
6d2010ae 2680 */
fe8ab488
A
2681 if (tp->t_state == TCPS_ESTABLISHED
2682 && (tp->ecn_flags & TE_SETUPSENT)
3e170ce0 2683 && (ip_ecn == IPTOS_ECN_CE || (thflags & TH_CWR))) {
6d2010ae 2684 tcp_reset_stretch_ack(tp);
3e170ce0
A
2685 CLEAR_IAJ_STATE(tp);
2686 }
316670eb 2687
4bd07ac2
A
2688 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
2689 !TCP_ECN_ENABLED(tp) && !(tp->ecn_flags & TE_CEHEURI_SET)) {
2690 tcpstat.tcps_ecn_fallback_ce++;
2691 tcp_heuristic_ecn_aggressive(tp);
2692 tp->ecn_flags |= TE_CEHEURI_SET;
2693 }
2694
2695 if (tp->t_state == TCPS_ESTABLISHED && TCP_ECN_ENABLED(tp) &&
2696 ip_ecn == IPTOS_ECN_CE && !(tp->ecn_flags & TE_CEHEURI_SET)) {
2697 if (inp->inp_stat->rxpackets < ECN_MIN_CE_PROBES) {
2698 tp->t_ecn_recv_ce_pkt++;
2699 } else if (tp->t_ecn_recv_ce_pkt > ECN_MAX_CE_RATIO) {
2700 tcpstat.tcps_ecn_fallback_ce++;
2701 tcp_heuristic_ecn_aggressive(tp);
2702 tp->ecn_flags |= TE_CEHEURI_SET;
2703 INP_INC_IFNET_STAT(inp,ecn_fallback_ce);
2704 } else {
2705 /* We tracked the first ECN_MIN_CE_PROBES segments, we
2706 * now know that the path is good.
2707 */
2708 tp->ecn_flags |= TE_CEHEURI_SET;
2709 }
2710 }
2711
39037602 2712 /*
316670eb 2713 * Try to determine if we are receiving a packet after a long time.
39037602 2714 * Use our own approximation of idletime to roughly measure remote
316670eb
A
2715 * end's idle time. Since slowstart is used after an idle period
2716 * we want to avoid doing LRO if the remote end is not up to date
2717 * on initial window support and starts with 1 or 2 packets as its IW.
2718 */
2719 if (sw_lro && (tp->t_flagsext & TF_LRO_OFFLOADED) &&
2720 ((tcp_now - tp->t_rcvtime) >= (TCP_IDLETIMEOUT(tp)))) {
2721 turnoff_lro = 1;
2722 }
2723
39236c6e
A
2724 /* Update rcvtime as a new segment was received on the connection */
2725 tp->t_rcvtime = tcp_now;
2726
1c79356b
A
2727 /*
2728 * Segment received on connection.
2729 * Reset idle time and keep-alive timer.
2730 */
5ba3f43e 2731 if (TCPS_HAVEESTABLISHED(tp->t_state)) {
39236c6e 2732 tcp_keepalive_reset(tp);
1c79356b 2733
5ba3f43e
A
2734 if (tp->t_mpsub)
2735 mptcp_reset_keepalive(tp);
2736 }
2737
1c79356b
A
2738 /*
2739 * Process options if not in LISTEN state,
2740 * else do it below (after getting remote address).
2741 */
39236c6e 2742 if (tp->t_state != TCPS_LISTEN && optp) {
3e170ce0 2743 tcp_dooptions(tp, optp, optlen, th, &to);
5c9f4661 2744 }
39236c6e 2745#if MPTCP
5c9f4661
A
2746 if (tp->t_state != TCPS_LISTEN && (so->so_flags & SOF_MP_SUBFLOW) &&
2747 mptcp_input_preproc(tp, m, th, drop_hdrlen) != 0) {
2748 tp->t_flags |= TF_ACKNOW;
2749 (void) tcp_output(tp);
2750 tcp_check_timer_state(tp);
2751 socket_unlock(so, 1);
2752 KERNEL_DEBUG(DBG_FNC_TCP_INPUT |
2753 DBG_FUNC_END,0,0,0,0,0);
2754 return;
39236c6e 2755 }
5c9f4661 2756#endif /* MPTCP */
39236c6e 2757 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
3e170ce0
A
2758 if (!(thflags & TH_ACK) ||
2759 (SEQ_GT(th->th_ack, tp->iss) &&
2760 SEQ_LEQ(th->th_ack, tp->snd_max)))
2761 tcp_finalize_options(tp, &to, ifscope);
8ad349bb
A
2762 }
2763
6d2010ae 2764#if TRAFFIC_MGT
3e170ce0
A
2765 /*
2766 * Compute inter-packet arrival jitter. According to RFC 3550,
2767 * inter-packet arrival jitter is defined as the difference in
2768 * packet spacing at the receiver compared to the sender for a
2769 * pair of packets. When two packets of maximum segment size come
2770 * one after the other with consecutive sequence numbers, we
2771 * consider them as packets sent together at the sender and use
2772 * them as a pair to compute inter-packet arrival jitter. This
2773 * metric indicates the delay induced by the network components due
6d2010ae
A
2774 * to queuing in edge/access routers.
2775 */
2776 if (tp->t_state == TCPS_ESTABLISHED &&
2777 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK|TH_ECE|TH_PUSH)) == TH_ACK &&
2778 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
2779 ((to.to_flags & TOF_TS) == 0 ||
2780 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
39037602 2781 th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
316670eb 2782 int seg_size = tlen;
6d2010ae 2783 if (tp->iaj_pktcnt <= IAJ_IGNORE_PKTCNT) {
316670eb 2784 TCP_INC_VAR(tp->iaj_pktcnt, nlropkts);
6d2010ae
A
2785 }
2786
39236c6e 2787 if (m->m_pkthdr.pkt_flags & PKTF_SW_LRO_PKT) {
316670eb
A
2788 seg_size = m->m_pkthdr.lro_pktlen;
2789 }
2790 if ( tp->iaj_size == 0 || seg_size > tp->iaj_size ||
2791 (seg_size == tp->iaj_size && tp->iaj_rcv_ts == 0)) {
3e170ce0
A
2792 /*
2793 * State related to inter-arrival jitter is
2794 * uninitialized or we are trying to find a good
2795 * first packet to start computing the metric
6d2010ae 2796 */
316670eb 2797 update_iaj_state(tp, seg_size, 0);
6d2010ae 2798 } else {
316670eb 2799 if (seg_size == tp->iaj_size) {
3e170ce0
A
2800 /*
2801 * Compute inter-arrival jitter taking
2802 * this packet as the second packet
6d2010ae 2803 */
39236c6e
A
2804 if (pktf_sw_lro_pkt)
2805 compute_iaj(tp, nlropkts,
2806 m->m_pkthdr.lro_elapsed);
2807 else
2808 compute_iaj(tp, 1, 0);
39037602 2809 }
316670eb 2810 if (seg_size < tp->iaj_size) {
3e170ce0
A
2811 /*
2812 * There is a smaller packet in the stream.
2813 * Some times the maximum size supported
2814 * on a path can change if there is a new
2815 * link with smaller MTU. The receiver will
2816 * not know about this change. If there
2817 * are too many packets smaller than
2818 * iaj_size, we try to learn the iaj_size
2819 * again.
6d2010ae 2820 */
39037602 2821 TCP_INC_VAR(tp->iaj_small_pkt, nlropkts);
6d2010ae 2822 if (tp->iaj_small_pkt > RESET_IAJ_SIZE_THRESH) {
316670eb 2823 update_iaj_state(tp, seg_size, 1);
6d2010ae 2824 } else {
316670eb 2825 CLEAR_IAJ_STATE(tp);
6d2010ae
A
2826 }
2827 } else {
316670eb 2828 update_iaj_state(tp, seg_size, 0);
6d2010ae
A
2829 }
2830 }
2831 } else {
316670eb 2832 CLEAR_IAJ_STATE(tp);
6d2010ae
A
2833 }
2834#endif /* TRAFFIC_MGT */
2835
1c79356b
A
2836 /*
2837 * Header prediction: check for the two common cases
2838 * of a uni-directional data xfer. If the packet has
2839 * no control flags, is in-sequence, the window didn't
2840 * change and we're not retransmitting, it's a
2841 * candidate. If the length is zero and the ack moved
2842 * forward, we're the sender side of the xfer. Just
2843 * free the data acked & wake any higher level process
2844 * that was blocked waiting for space. If the length
2845 * is non-zero and the ack didn't move, we're the
2846 * receiver side. If we're getting packets in-order
2847 * (the reassembly queue is empty), add the data to
2848 * the socket buffer and note that we need a delayed ack.
2849 * Make sure that the hidden state-flags are also off.
2850 * Since we check for TCPS_ESTABLISHED above, it can only
2851 * be TH_NEEDSYN.
2852 */
2853 if (tp->t_state == TCPS_ESTABLISHED &&
4bd07ac2 2854 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK|TH_ECE|TH_CWR)) == TH_ACK &&
1c79356b 2855 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
8ad349bb 2856 ((to.to_flags & TOF_TS) == 0 ||
1c79356b 2857 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1c79356b
A
2858 th->th_seq == tp->rcv_nxt &&
2859 tiwin && tiwin == tp->snd_wnd &&
2860 tp->snd_nxt == tp->snd_max) {
2861
2862 /*
2863 * If last ACK falls within this segment's sequence numbers,
2864 * record the timestamp.
2865 * NOTE that the test is modified according to the latest
2866 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2867 */
8ad349bb 2868 if ((to.to_flags & TOF_TS) != 0 &&
1c79356b
A
2869 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
2870 tp->ts_recent_age = tcp_now;
2871 tp->ts_recent = to.to_tsval;
2872 }
2873
9bccf70c 2874 if (tlen == 0) {
1c79356b
A
2875 if (SEQ_GT(th->th_ack, tp->snd_una) &&
2876 SEQ_LEQ(th->th_ack, tp->snd_max) &&
2d21ac55 2877 tp->snd_cwnd >= tp->snd_ssthresh &&
39037602
A
2878 (!IN_FASTRECOVERY(tp) &&
2879 ((!(SACK_ENABLED(tp)) &&
fe8ab488
A
2880 tp->t_dupacks < tp->t_rexmtthresh) ||
2881 (SACK_ENABLED(tp) && to.to_nsacks == 0 &&
2882 TAILQ_EMPTY(&tp->snd_holes))))) {
1c79356b
A
2883 /*
2884 * this is a pure ack for outstanding data.
2885 */
2886 ++tcpstat.tcps_predack;
39236c6e 2887
39037602 2888 tcp_bad_rexmt_check(tp, th, &to);
39236c6e
A
2889
2890 /* Recalculate the RTT */
2891 tcp_compute_rtt(tp, &to, th);
2892
3e170ce0 2893 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
39236c6e 2894 acked = BYTES_ACKED(th, tp);
1c79356b
A
2895 tcpstat.tcps_rcvackpack++;
2896 tcpstat.tcps_rcvackbyte += acked;
39037602 2897
3e170ce0
A
2898 /*
2899 * Handle an ack that is in sequence during
2900 * congestion avoidance phase. The
2901 * calculations in this function
39037602 2902 * assume that snd_una is not updated yet.
2d21ac55 2903 */
fe8ab488
A
2904 if (CC_ALGO(tp)->congestion_avd != NULL)
2905 CC_ALGO(tp)->congestion_avd(tp, th);
2906 tcp_ccdbg_trace(tp, th, TCP_CC_INSEQ_ACK_RCVD);
1c79356b 2907 sbdrop(&so->so_snd, acked);
39236c6e
A
2908 if (so->so_flags & SOF_ENABLE_MSGS) {
2909 VERIFY(acked <= so->so_msg_state->msg_serial_bytes);
2910 so->so_msg_state->msg_serial_bytes -= acked;
2911 }
316670eb
A
2912 tcp_sbsnd_trim(&so->so_snd);
2913
8ad349bb
A
2914 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
2915 SEQ_LEQ(th->th_ack, tp->snd_recover))
2916 tp->snd_recover = th->th_ack - 1;
1c79356b 2917 tp->snd_una = th->th_ack;
316670eb 2918
39037602
A
2919 TCP_RESET_REXMT_STATE(tp);
2920
8ad349bb
A
2921 /*
2922 * pull snd_wl2 up to prevent seq wrap relative
2923 * to th_ack.
2924 */
2925 tp->snd_wl2 = th->th_ack;
39236c6e
A
2926
2927 if (tp->t_dupacks > 0) {
2928 tp->t_dupacks = 0;
2929 tp->t_rexmtthresh = tcprexmtthresh;
2930 }
2931
1c79356b 2932 m_freem(m);
1c79356b
A
2933
2934 /*
2935 * If all outstanding data are acked, stop
2936 * retransmit timer, otherwise restart timer
2937 * using current (possibly backed-off) value.
2938 * If process is waiting for space,
2939 * wakeup/selwakeup/signal. If data
2940 * are ready to send, let tcp_output
2941 * decide between more output or persist.
2942 */
fe8ab488 2943 if (tp->snd_una == tp->snd_max) {
1c79356b 2944 tp->t_timer[TCPT_REXMT] = 0;
fe8ab488
A
2945 tp->t_timer[TCPT_PTO] = 0;
2946 } else if (tp->t_timer[TCPT_PERSIST] == 0) {
2947 tp->t_timer[TCPT_REXMT] =
2948 OFFSET_FROM_START(tp,
2949 tp->t_rxtcur);
2950 }
3e170ce0
A
2951 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
2952 !TCP_DSACK_SEQ_IN_WINDOW(tp,
2953 tp->t_dsack_lastuna, tp->snd_una))
2954 tcp_rxtseg_clean(tp);
1c79356b 2955
316670eb
A
2956 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
2957 tp->t_bwmeas != NULL)
2958 tcp_bwmeas_check(tp);
39037602 2959
91447636 2960 sowwakeup(so); /* has to be done with socket lock held */
39037602
A
2961 if (!SLIST_EMPTY(&tp->t_notify_ack))
2962 tcp_notify_acknowledgement(tp, so);
2963
2d21ac55 2964 if ((so->so_snd.sb_cc) || (tp->t_flags & TF_ACKNOW)) {
1c79356b 2965 (void) tcp_output(tp);
2d21ac55 2966 }
6d2010ae 2967
3e170ce0
A
2968 tcp_tfo_rcv_ack(tp, th);
2969
6d2010ae 2970 tcp_check_timer_state(tp);
5ba3f43e 2971 socket_unlock(so, 1);
1c79356b
A
2972 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2973 return;
2974 }
2975 } else if (th->th_ack == tp->snd_una &&
9bccf70c 2976 LIST_EMPTY(&tp->t_segq) &&
2d21ac55 2977 tlen <= tcp_sbspace(tp)) {
1c79356b
A
2978 /*
2979 * this is a pure, in-sequence data packet
2980 * with nothing on the reassembly queue and
2981 * we have enough buffer space to take it.
2982 */
316670eb
A
2983
2984 /*
5ba3f43e 2985 * If this is a connection in steady state, start
316670eb
A
2986 * coalescing packets belonging to this flow.
2987 */
2988 if (turnoff_lro) {
2989 tcp_lro_remove_state(tp->t_inpcb->inp_laddr,
39236c6e 2990 tp->t_inpcb->inp_faddr,
39037602 2991 tp->t_inpcb->inp_lport,
39236c6e 2992 tp->t_inpcb->inp_fport);
316670eb
A
2993 tp->t_flagsext &= ~TF_LRO_OFFLOADED;
2994 tp->t_idleat = tp->rcv_nxt;
39236c6e 2995 } else if (sw_lro && !pktf_sw_lro_pkt && !isipv6 &&
39037602 2996 (so->so_flags & SOF_USELRO) &&
39236c6e 2997 !IFNET_IS_CELLULAR(m->m_pkthdr.rcvif) &&
316670eb 2998 (m->m_pkthdr.rcvif->if_type != IFT_LOOP) &&
39037602 2999 ((th->th_seq - tp->irs) >
39236c6e 3000 (tp->t_maxseg << lro_start)) &&
39037602 3001 ((tp->t_idleat == 0) || ((th->th_seq -
316670eb
A
3002 tp->t_idleat) > (tp->t_maxseg << lro_start)))) {
3003 tp->t_flagsext |= TF_LRO_OFFLOADED;
3004 tcp_start_coalescing(ip, th, tlen);
3005 tp->t_idleat = 0;
3006 }
3007
8ad349bb 3008 /* Clean receiver SACK report if present */
39236c6e 3009 if (SACK_ENABLED(tp) && tp->rcv_numsacks)
8ad349bb 3010 tcp_clean_sackreport(tp);
1c79356b 3011 ++tcpstat.tcps_preddat;
9bccf70c 3012 tp->rcv_nxt += tlen;
8ad349bb
A
3013 /*
3014 * Pull snd_wl1 up to prevent seq wrap relative to
3015 * th_seq.
3016 */
3017 tp->snd_wl1 = th->th_seq;
3018 /*
3019 * Pull rcv_up up to prevent seq wrap relative to
3020 * rcv_nxt.
3021 */
3022 tp->rcv_up = tp->rcv_nxt;
316670eb 3023 TCP_INC_VAR(tcpstat.tcps_rcvpack, nlropkts);
9bccf70c 3024 tcpstat.tcps_rcvbyte += tlen;
6d2010ae 3025 if (nstat_collect) {
39236c6e 3026 if (m->m_pkthdr.pkt_flags & PKTF_SW_LRO_PKT) {
39037602 3027 INP_ADD_STAT(inp, cell, wifi, wired,
fe8ab488 3028 rxpackets, m->m_pkthdr.lro_npkts);
39236c6e 3029 } else {
fe8ab488
A
3030 INP_ADD_STAT(inp, cell, wifi, wired,
3031 rxpackets, 1);
316670eb 3032 }
fe8ab488
A
3033 INP_ADD_STAT(inp, cell, wifi, wired,rxbytes,
3034 tlen);
5ba3f43e 3035 inp_set_activity_bitmap(inp);
6d2010ae 3036 }
39236c6e
A
3037
3038 /*
39037602
A
3039 * Calculate the RTT on the receiver only if the
3040 * connection is in streaming mode and the last
39236c6e
A
3041 * packet was not an end-of-write
3042 */
39037602 3043 if (tp->t_flags & TF_STREAMING_ON)
39236c6e 3044 tcp_compute_rtt(tp, &to, th);
316670eb 3045
39037602
A
3046 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen,
3047 TCP_AUTORCVBUF_MAX(ifp));
3048
9bccf70c
A
3049 /*
3050 * Add data to socket buffer.
3051 */
6d2010ae 3052 so_recv_data_stat(so, m, 0);
9bccf70c 3053 m_adj(m, drop_hdrlen); /* delayed header drop */
39037602 3054
39236c6e 3055 /*
39037602 3056 * If message delivery (SOF_ENABLE_MSGS) is enabled on
39236c6e
A
3057 * this socket, deliver the packet received as an
3058 * in-order message with sequence number attached to it.
3059 */
39037602 3060 if (sbappendstream_rcvdemux(so, m,
39236c6e 3061 th->th_seq - (tp->irs + 1), 0)) {
91447636 3062 sorwakeup(so);
39037602 3063 }
9bccf70c
A
3064#if INET6
3065 if (isipv6) {
3066 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3067 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
39037602 3068 th->th_seq, th->th_ack, th->th_win);
9bccf70c
A
3069 }
3070 else
39037602 3071#endif
9bccf70c
A
3072 {
3073 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3074 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
39037602 3075 th->th_seq, th->th_ack, th->th_win);
9bccf70c 3076 }
316670eb 3077 TCP_INC_VAR(tp->t_unacksegs, nlropkts);
6d2010ae
A
3078 if (DELAY_ACK(tp, th)) {
3079 if ((tp->t_flags & TF_DELACK) == 0) {
3080 tp->t_flags |= TF_DELACK;
3081 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3082 }
1c79356b
A
3083 } else {
3084 tp->t_flags |= TF_ACKNOW;
3085 tcp_output(tp);
3086 }
39236c6e
A
3087
3088 tcp_adaptive_rwtimo_check(tp, tlen);
3089
3e170ce0
A
3090 if (tlen > 0)
3091 tcp_tfo_rcv_data(tp);
3092
6d2010ae 3093 tcp_check_timer_state(tp);
5ba3f43e 3094 socket_unlock(so, 1);
1c79356b
A
3095 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
3096 return;
3097 }
3098 }
3099
3100 /*
3101 * Calculate amount of space in receive window,
3102 * and then do TCP input processing.
3103 * Receive window is amount of space in rcv queue,
3104 * but not less than advertised window.
3105 */
5ba3f43e 3106 socket_lock_assert_owned(so);
2d21ac55 3107 win = tcp_sbspace(tp);
1c79356b
A
3108 if (win < 0)
3109 win = 0;
d12e1678
A
3110 else { /* clip rcv window to 4K for modems */
3111 if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0)
3112 win = min(win, slowlink_wsize);
3113 }
1c79356b 3114 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
39236c6e
A
3115#if MPTCP
3116 /*
3117 * Ensure that the subflow receive window isn't greater
3118 * than the connection level receive window.
3119 */
3120 if ((tp->t_mpflags & TMPF_MPTCP_TRUE) &&
3121 (mp_tp = tptomptp(tp))) {
5ba3f43e 3122 mpte_lock_assert_held(mp_tp->mpt_mpte);
39236c6e 3123 if (tp->rcv_wnd > mp_tp->mpt_rcvwnd) {
39037602 3124 tp->rcv_wnd = imax(mp_tp->mpt_rcvwnd, (int)(tp->rcv_adv - tp->rcv_nxt));
39236c6e
A
3125 tcpstat.tcps_mp_reducedwin++;
3126 }
1c79356b 3127 }
39236c6e 3128#endif /* MPTCP */
1c79356b
A
3129
3130 switch (tp->t_state) {
3131
3132 /*
7e4a7d39 3133 * Initialize tp->rcv_nxt, and tp->irs, select an initial
1c79356b
A
3134 * tp->iss, and send a segment:
3135 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3136 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
3137 * Fill in remote peer address fields if not previously specified.
3138 * Enter SYN_RECEIVED state, and process any other fields of this
3139 * segment in this state.
3140 */
3141 case TCPS_LISTEN: {
39037602 3142 struct sockaddr_in *sin;
9bccf70c 3143#if INET6
39037602 3144 struct sockaddr_in6 *sin6;
1c79356b
A
3145#endif
3146
5ba3f43e 3147 socket_lock_assert_owned(so);
9bccf70c
A
3148#if INET6
3149 if (isipv6) {
1c79356b
A
3150 MALLOC(sin6, struct sockaddr_in6 *, sizeof *sin6,
3151 M_SONAME, M_NOWAIT);
3152 if (sin6 == NULL)
3153 goto drop;
3154 bzero(sin6, sizeof(*sin6));
3155 sin6->sin6_family = AF_INET6;
3156 sin6->sin6_len = sizeof(*sin6);
3157 sin6->sin6_addr = ip6->ip6_src;
3158 sin6->sin6_port = th->th_sport;
3159 laddr6 = inp->in6p_laddr;
3160 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
3161 inp->in6p_laddr = ip6->ip6_dst;
3162 if (in6_pcbconnect(inp, (struct sockaddr *)sin6,
9bccf70c 3163 proc0)) {
1c79356b
A
3164 inp->in6p_laddr = laddr6;
3165 FREE(sin6, M_SONAME);
3166 goto drop;
3167 }
3168 FREE(sin6, M_SONAME);
9bccf70c 3169 } else
1c79356b 3170#endif
9bccf70c 3171 {
5ba3f43e 3172 socket_lock_assert_owned(so);
1c79356b 3173 MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
5ba3f43e 3174 M_NOWAIT);
1c79356b
A
3175 if (sin == NULL)
3176 goto drop;
3177 sin->sin_family = AF_INET;
3178 sin->sin_len = sizeof(*sin);
3179 sin->sin_addr = ip->ip_src;
3180 sin->sin_port = th->th_sport;
3181 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
3182 laddr = inp->inp_laddr;
3183 if (inp->inp_laddr.s_addr == INADDR_ANY)
3184 inp->inp_laddr = ip->ip_dst;
39236c6e
A
3185 if (in_pcbconnect(inp, (struct sockaddr *)sin, proc0,
3186 IFSCOPE_NONE, NULL)) {
1c79356b
A
3187 inp->inp_laddr = laddr;
3188 FREE(sin, M_SONAME);
3189 goto drop;
3190 }
3191 FREE(sin, M_SONAME);
1c79356b 3192 }
8ad349bb 3193
3e170ce0
A
3194 tcp_dooptions(tp, optp, optlen, th, &to);
3195 tcp_finalize_options(tp, &to, ifscope);
3196
3197 if (tfo_enabled(tp) && tcp_tfo_syn(tp, &to))
3198 isconnected = TRUE;
8ad349bb 3199
1c79356b
A
3200 if (iss)
3201 tp->iss = iss;
0b4e3aa0 3202 else {
9bccf70c
A
3203 tp->iss = tcp_new_isn(tp);
3204 }
1c79356b
A
3205 tp->irs = th->th_seq;
3206 tcp_sendseqinit(tp);
3207 tcp_rcvseqinit(tp);
9bccf70c 3208 tp->snd_recover = tp->snd_una;
1c79356b
A
3209 /*
3210 * Initialization of the tcpcb for transaction;
3211 * set SND.WND = SEG.WND,
3212 * initialize CCsend and CCrecv.
3213 */
3214 tp->snd_wnd = tiwin; /* initial send-window */
1c79356b 3215 tp->t_flags |= TF_ACKNOW;
2d21ac55 3216 tp->t_unacksegs = 0;
6d2010ae
A
3217 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3218 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
1c79356b 3219 tp->t_state = TCPS_SYN_RECEIVED;
39037602 3220 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
39236c6e 3221 TCP_CONN_KEEPINIT(tp));
1c79356b 3222 dropsocket = 0; /* committed to socket */
6d2010ae 3223
316670eb
A
3224 if (inp->inp_flowhash == 0)
3225 inp->inp_flowhash = inp_calc_flowhash(inp);
39236c6e
A
3226#if INET6
3227 /* update flowinfo - RFC 6437 */
3228 if (inp->inp_flow == 0 &&
3229 inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
3230 inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
3231 inp->inp_flow |=
3232 (htonl(inp->inp_flowhash) & IPV6_FLOWLABEL_MASK);
3233 }
3234#endif /* INET6 */
316670eb 3235
6d2010ae
A
3236 /* reset the incomp processing flag */
3237 so->so_flags &= ~(SOF_INCOMP_INPROGRESS);
1c79356b 3238 tcpstat.tcps_accepts++;
2d21ac55
A
3239 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE | TH_CWR)) {
3240 /* ECN-setup SYN */
3241 tp->ecn_flags |= (TE_SETUPRECEIVED | TE_SENDIPECT);
3242 }
316670eb 3243
1c79356b
A
3244 goto trimthenstep6;
3245 }
3246
3247 /*
3e170ce0
A
3248 * If the state is SYN_RECEIVED and the seg contains an ACK,
3249 * but not for our SYN/ACK, send a RST.
1c79356b
A
3250 */
3251 case TCPS_SYN_RECEIVED:
3252 if ((thflags & TH_ACK) &&
3253 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
9bccf70c
A
3254 SEQ_GT(th->th_ack, tp->snd_max))) {
3255 rstreason = BANDLIM_RST_OPENPORT;
39236c6e 3256 IF_TCP_STATINC(ifp, ooopacket);
1c79356b 3257 goto dropwithreset;
9bccf70c 3258 }
39236c6e
A
3259
3260 /*
3261 * In SYN_RECEIVED state, if we recv some SYNS with
3262 * window scale and others without, window scaling should
3263 * be disabled. Otherwise the window advertised will be
3264 * lower if we assume scaling and the other end does not.
3265 */
3266 if ((thflags & TH_SYN) &&
3e170ce0 3267 (tp->irs == th->th_seq) &&
39236c6e
A
3268 !(to.to_flags & TOF_SCALE))
3269 tp->t_flags &= ~TF_RCVD_SCALE;
1c79356b
A
3270 break;
3271
3272 /*
3273 * If the state is SYN_SENT:
3274 * if seg contains an ACK, but not for our SYN, drop the input.
3275 * if seg contains a RST, then drop the connection.
3276 * if seg does not contain SYN, then drop it.
3277 * Otherwise this is an acceptable SYN segment
3278 * initialize tp->rcv_nxt and tp->irs
3279 * if seg contains ack then advance tp->snd_una
3280 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
3281 * arrange for segment to be acked (eventually)
3282 * continue processing rest of data/controls, beginning with URG
3283 */
3284 case TCPS_SYN_SENT:
1c79356b
A
3285 if ((thflags & TH_ACK) &&
3286 (SEQ_LEQ(th->th_ack, tp->iss) ||
3287 SEQ_GT(th->th_ack, tp->snd_max))) {
8ad349bb 3288 rstreason = BANDLIM_UNLIMITED;
39236c6e 3289 IF_TCP_STATINC(ifp, ooopacket);
8ad349bb 3290 goto dropwithreset;
1c79356b
A
3291 }
3292 if (thflags & TH_RST) {
2d21ac55 3293 if ((thflags & TH_ACK) != 0) {
5ba3f43e
A
3294 if (tfo_enabled(tp))
3295 tcp_heuristic_tfo_rst(tp);
3296 if ((tp->ecn_flags & (TE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_SETUPSENT) {
3297 /*
3298 * On local connections, send
3299 * non-ECN syn one time before
3300 * dropping the connection
3301 */
3302 if (tp->t_flags & TF_LOCAL) {
3303 tp->ecn_flags |= TE_RCVD_SYN_RST;
3304 goto drop;
3305 } else {
3306 tcp_heuristic_ecn_synrst(tp);
3307 }
fe8ab488 3308 }
39037602 3309 soevent(so,
316670eb
A
3310 (SO_FILT_HINT_LOCKED |
3311 SO_FILT_HINT_CONNRESET));
1c79356b
A
3312 tp = tcp_drop(tp, ECONNREFUSED);
3313 postevent(so, 0, EV_RESET);
2d21ac55 3314 }
1c79356b
A
3315 goto drop;
3316 }
3317 if ((thflags & TH_SYN) == 0)
3318 goto drop;
3319 tp->snd_wnd = th->th_win; /* initial send window */
1c79356b
A
3320
3321 tp->irs = th->th_seq;
3322 tcp_rcvseqinit(tp);
3323 if (thflags & TH_ACK) {
1c79356b 3324 tcpstat.tcps_connects++;
39037602 3325
2d21ac55
A
3326 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE)) {
3327 /* ECN-setup SYN-ACK */
3328 tp->ecn_flags |= TE_SETUPRECEIVED;
4bd07ac2 3329 if (TCP_ECN_ENABLED(tp)) {
39037602 3330 tcp_heuristic_ecn_success(tp);
3e170ce0 3331 tcpstat.tcps_ecn_client_success++;
4bd07ac2 3332 }
3e170ce0
A
3333 } else {
3334 if (tp->ecn_flags & TE_SETUPSENT &&
4bd07ac2 3335 tp->t_rxtshift == 0) {
39037602 3336 tcp_heuristic_ecn_success(tp);
3e170ce0 3337 tcpstat.tcps_ecn_not_supported++;
4bd07ac2
A
3338 }
3339 if (tp->ecn_flags & TE_SETUPSENT &&
3340 tp->t_rxtshift > 0)
39037602 3341 tcp_heuristic_ecn_loss(tp);
4bd07ac2 3342
2d21ac55
A
3343 /* non-ECN-setup SYN-ACK */
3344 tp->ecn_flags &= ~TE_SENDIPECT;
3345 }
39037602 3346
2d21ac55
A
3347#if CONFIG_MACF_NET && CONFIG_MACF_SOCKET
3348 /* XXXMAC: recursive lock: SOCK_LOCK(so); */
3349 mac_socketpeer_label_associate_mbuf(m, so);
3350 /* XXXMAC: SOCK_UNLOCK(so); */
3351#endif
1c79356b 3352 /* Do window scaling on this connection? */
3e170ce0 3353 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
1c79356b
A
3354 tp->snd_scale = tp->requested_s_scale;
3355 tp->rcv_scale = tp->request_r_scale;
3356 }
3e170ce0 3357
316670eb 3358 tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN << tp->rcv_scale);
1c79356b 3359 tp->snd_una++; /* SYN is acked */
3e170ce0
A
3360 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
3361 tp->snd_nxt = tp->snd_una;
3362
3363 /*
3364 * We have sent more in the SYN than what is being
3365 * acked. (e.g., TFO)
3366 * We should restart the sending from what the receiver
3367 * has acknowledged immediately.
3368 */
5ba3f43e
A
3369 if (SEQ_GT(tp->snd_nxt, th->th_ack)) {
3370 /*
3371 * rdar://problem/33214601
3372 * There is a middlebox that acks all but one
3373 * byte and still drops the data.
3374 */
3375 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3376 tp->snd_max == th->th_ack + 1 &&
3377 tp->snd_max > tp->snd_una + 1) {
3378 tcp_heuristic_tfo_middlebox(tp);
3379
3380 so->so_error = ENODATA;
3381
3382 tp->t_tfo_stats |= TFO_S_ONE_BYTE_PROXY;
3383 }
3384
490019cf 3385 tp->snd_max = tp->snd_nxt = th->th_ack;
5ba3f43e 3386 }
3e170ce0 3387
1c79356b
A
3388 /*
3389 * If there's data, delay ACK; if there's also a FIN
3390 * ACKNOW will be turned on later.
3391 */
316670eb
A
3392 TCP_INC_VAR(tp->t_unacksegs, nlropkts);
3393 if (DELAY_ACK(tp, th) && tlen != 0 ) {
6d2010ae
A
3394 if ((tp->t_flags & TF_DELACK) == 0) {
3395 tp->t_flags |= TF_DELACK;
3396 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3397 }
1c79356b 3398 }
91447636 3399 else {
1c79356b 3400 tp->t_flags |= TF_ACKNOW;
91447636 3401 }
1c79356b
A
3402 /*
3403 * Received <SYN,ACK> in SYN_SENT[*] state.
3404 * Transitions:
3405 * SYN_SENT --> ESTABLISHED
3406 * SYN_SENT* --> FIN_WAIT_1
3407 */
6d2010ae 3408 tp->t_starttime = tcp_now;
316670eb 3409 tcp_sbrcv_tstmp_check(tp);
1c79356b 3410 if (tp->t_flags & TF_NEEDFIN) {
3e170ce0
A
3411 DTRACE_TCP4(state__change, void, NULL,
3412 struct inpcb *, inp,
3413 struct tcpcb *, tp, int32_t,
3414 TCPS_FIN_WAIT_1);
1c79356b
A
3415 tp->t_state = TCPS_FIN_WAIT_1;
3416 tp->t_flags &= ~TF_NEEDFIN;
3417 thflags &= ~TH_SYN;
3418 } else {
3e170ce0
A
3419 DTRACE_TCP4(state__change, void, NULL,
3420 struct inpcb *, inp, struct tcpcb *,
3421 tp, int32_t, TCPS_ESTABLISHED);
1c79356b 3422 tp->t_state = TCPS_ESTABLISHED;
3e170ce0
A
3423 tp->t_timer[TCPT_KEEP] =
3424 OFFSET_FROM_START(tp,
3425 TCP_CONN_KEEPIDLE(tp));
6d2010ae 3426 if (nstat_collect)
3e170ce0 3427 nstat_route_connect_success(
39037602
A
3428 inp->inp_route.ro_rt);
3429 /*
3430 * The SYN is acknowledged but una is not
3431 * updated yet. So pass the value of
3432 * ack to compute sndbytes correctly
3433 */
3434 inp_count_sndbytes(inp, th->th_ack);
1c79356b 3435 }
39236c6e
A
3436#if MPTCP
3437 /*
3438 * Do not send the connect notification for additional
3439 * subflows until ACK for 3-way handshake arrives.
3440 */
3441 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
3442 (tp->t_mpflags & TMPF_SENT_JOIN)) {
3443 isconnected = FALSE;
3444 } else
3445#endif /* MPTCP */
3446 isconnected = TRUE;
3e170ce0 3447
813fb2f6
A
3448 if ((tp->t_tfo_flags & (TFO_F_COOKIE_REQ | TFO_F_COOKIE_SENT)) ||
3449 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT)) {
3e170ce0
A
3450 tcp_tfo_synack(tp, &to);
3451
3452 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3453 SEQ_LT(tp->snd_una, th->th_ack)) {
3454 tp->t_tfo_stats |= TFO_S_SYN_DATA_ACKED;
3455 tcpstat.tcps_tfo_syn_data_acked++;
490019cf
A
3456#if MPTCP
3457 if (so->so_flags & SOF_MP_SUBFLOW)
3458 so->so_flags1 |= SOF1_TFO_REWIND;
3459#endif
5ba3f43e 3460 tcp_tfo_rcv_probe(tp, tlen);
3e170ce0
A
3461 }
3462 }
1c79356b 3463 } else {
6d2010ae
A
3464 /*
3465 * Received initial SYN in SYN-SENT[*] state => simul-
5ba3f43e 3466 * taneous open. If segment contains CC option and there is
6d2010ae
A
3467 * a cached CC, apply TAO test; if it succeeds, connection is
3468 * half-synchronized. Otherwise, do 3-way handshake:
3469 * SYN-SENT -> SYN-RECEIVED
3470 * SYN-SENT* -> SYN-RECEIVED*
3471 */
1c79356b
A
3472 tp->t_flags |= TF_ACKNOW;
3473 tp->t_timer[TCPT_REXMT] = 0;
6d2010ae
A
3474 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3475 struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
8ad349bb
A
3476 tp->t_state = TCPS_SYN_RECEIVED;
3477
3e170ce0
A
3478 /*
3479 * During simultaneous open, TFO should not be used.
3480 * So, we disable it here, to prevent that data gets
3481 * sent on the SYN/ACK.
3482 */
3483 tcp_disable_tfo(tp);
1c79356b
A
3484 }
3485
3486trimthenstep6:
3487 /*
3488 * Advance th->th_seq to correspond to first data byte.
3489 * If data, trim to stay within window,
3490 * dropping FIN if necessary.
3491 */
3492 th->th_seq++;
9bccf70c
A
3493 if (tlen > tp->rcv_wnd) {
3494 todrop = tlen - tp->rcv_wnd;
1c79356b 3495 m_adj(m, -todrop);
9bccf70c 3496 tlen = tp->rcv_wnd;
1c79356b
A
3497 thflags &= ~TH_FIN;
3498 tcpstat.tcps_rcvpackafterwin++;
3499 tcpstat.tcps_rcvbyteafterwin += todrop;
3500 }
3501 tp->snd_wl1 = th->th_seq - 1;
3502 tp->rcv_up = th->th_seq;
3503 /*
3504 * Client side of transaction: already sent SYN and data.
3505 * If the remote host used T/TCP to validate the SYN,
3506 * our data will be ACK'd; if so, enter normal data segment
3507 * processing in the middle of step 5, ack processing.
3508 * Otherwise, goto step 6.
3509 */
3510 if (thflags & TH_ACK)
3511 goto process_ACK;
3512 goto step6;
3513 /*
3514 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
8ad349bb 3515 * do normal processing.
1c79356b 3516 *
8ad349bb 3517 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1c79356b
A
3518 */
3519 case TCPS_LAST_ACK:
3520 case TCPS_CLOSING:
3521 case TCPS_TIME_WAIT:
1c79356b 3522 break; /* continue normal processing */
55e303ae
A
3523
3524 /* Received a SYN while connection is already established.
3525 * This is a "half open connection and other anomalies" described
3526 * in RFC793 page 34, send an ACK so the remote reset the connection
39037602 3527 * or recovers by adjusting its sequence numberering
55e303ae
A
3528 */
3529 case TCPS_ESTABLISHED:
3e170ce0
A
3530 if (thflags & TH_SYN)
3531 goto dropafterack;
55e303ae 3532 break;
1c79356b
A
3533 }
3534
3535 /*
3536 * States other than LISTEN or SYN_SENT.
3537 * First check the RST flag and sequence number since reset segments
3538 * are exempt from the timestamp and connection count tests. This
3539 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
3540 * below which allowed reset segments in half the sequence space
3541 * to fall though and be processed (which gives forged reset
3542 * segments with a random sequence number a 50 percent chance of
3543 * killing a connection).
3544 * Then check timestamp, if present.
3545 * Then check the connection count, if present.
3546 * Then check that at least some bytes of segment are within
3547 * receive window. If segment begins before rcv_nxt,
3548 * drop leading data (and SYN); if nothing left, just ack.
3549 *
3550 *
3551 * If the RST bit is set, check the sequence number to see
3552 * if this is a valid reset segment.
3553 * RFC 793 page 37:
3554 * In all states except SYN-SENT, all reset (RST) segments
3555 * are validated by checking their SEQ-fields. A reset is
3556 * valid if its sequence number is in the window.
3557 * Note: this does not take into account delayed ACKs, so
3558 * we should test against last_ack_sent instead of rcv_nxt.
9bccf70c
A
3559 * The sequence number in the reset segment is normally an
3560 * echo of our outgoing acknowlegement numbers, but some hosts
3561 * send a reset with the sequence number at the rightmost edge
3562 * of our receive window, and we have to handle this case.
8ad349bb
A
3563 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
3564 * that brute force RST attacks are possible. To combat this,
3565 * we use a much stricter check while in the ESTABLISHED state,
3566 * only accepting RSTs where the sequence number is equal to
3567 * last_ack_sent. In all other states (the states in which a
3568 * RST is more likely), the more permissive check is used.
1c79356b
A
3569 * If we have multiple segments in flight, the intial reset
3570 * segment sequence numbers will be to the left of last_ack_sent,
3571 * but they will eventually catch up.
3572 * In any case, it never made sense to trim reset segments to
3573 * fit the receive window since RFC 1122 says:
3574 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
3575 *
3576 * A TCP SHOULD allow a received RST segment to include data.
3577 *
3578 * DISCUSSION
3579 * It has been suggested that a RST segment could contain
3580 * ASCII text that encoded and explained the cause of the
3581 * RST. No standard has yet been established for such
3582 * data.
3583 *
3584 * If the reset segment passes the sequence number test examine
3585 * the state:
3586 * SYN_RECEIVED STATE:
3587 * If passive open, return to LISTEN state.
3588 * If active open, inform user that connection was refused.
8ad349bb 3589 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1c79356b 3590 * Inform user that connection was reset, and close tcb.
9bccf70c 3591 * CLOSING, LAST_ACK STATES:
1c79356b 3592 * Close the tcb.
9bccf70c 3593 * TIME_WAIT STATE:
1c79356b
A
3594 * Drop the segment - see Stevens, vol. 2, p. 964 and
3595 * RFC 1337.
0c530ab8 3596 *
2d21ac55
A
3597 * Radar 4803931: Allows for the case where we ACKed the FIN but
3598 * there is already a RST in flight from the peer.
3599 * In that case, accept the RST for non-established
3600 * state if it's one off from last_ack_sent.
3601
1c79356b
A
3602 */
3603 if (thflags & TH_RST) {
8ad349bb
A
3604 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
3605 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
39037602
A
3606 (tp->rcv_wnd == 0 &&
3607 ((tp->last_ack_sent == th->th_seq) ||
39236c6e 3608 ((tp->last_ack_sent -1) == th->th_seq)))) {
1c79356b
A
3609 switch (tp->t_state) {
3610
3611 case TCPS_SYN_RECEIVED:
39236c6e 3612 IF_TCP_STATINC(ifp, rstinsynrcv);
1c79356b
A
3613 so->so_error = ECONNREFUSED;
3614 goto close;
3615
3616 case TCPS_ESTABLISHED:
8ad349bb 3617 if (tp->last_ack_sent != th->th_seq) {
2d21ac55 3618 tcpstat.tcps_badrst++;
8ad349bb
A
3619 goto drop;
3620 }
39037602
A
3621 if (TCP_ECN_ENABLED(tp) &&
3622 tp->snd_una == tp->iss + 1 &&
3623 SEQ_GT(tp->snd_max, tp->snd_una)) {
3624 /*
3625 * If the first data packet on an
3626 * ECN connection, receives a RST
3627 * increment the heuristic
3628 */
3629 tcp_heuristic_ecn_droprst(tp);
3630 }
1c79356b
A
3631 case TCPS_FIN_WAIT_1:
3632 case TCPS_CLOSE_WAIT:
1c79356b
A
3633 /*
3634 Drop through ...
3635 */
3636 case TCPS_FIN_WAIT_2:
3637 so->so_error = ECONNRESET;
3638 close:
3639 postevent(so, 0, EV_RESET);
316670eb
A
3640 soevent(so,
3641 (SO_FILT_HINT_LOCKED |
3642 SO_FILT_HINT_CONNRESET));
3643
1c79356b
A
3644 tcpstat.tcps_drops++;
3645 tp = tcp_close(tp);
3646 break;
3647
3648 case TCPS_CLOSING:
3649 case TCPS_LAST_ACK:
1c79356b
A
3650 tp = tcp_close(tp);
3651 break;
3652
3653 case TCPS_TIME_WAIT:
3654 break;
3655 }
3656 }
3657 goto drop;
3658 }
3659
3660 /*
3661 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3662 * and it's less than ts_recent, drop it.
3663 */
8ad349bb 3664 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1c79356b
A
3665 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3666
3667 /* Check to see if ts_recent is over 24 days old. */
3668 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
3669 /*
3670 * Invalidate ts_recent. If this segment updates
3671 * ts_recent, the age will be reset later and ts_recent
3672 * will get a valid value. If it does not, setting
3673 * ts_recent to zero will at least satisfy the
3674 * requirement that zero be placed in the timestamp
3675 * echo reply when ts_recent isn't valid. The
3676 * age isn't reset until we get a valid ts_recent
3677 * because we don't want out-of-order segments to be
3678 * dropped when ts_recent is old.
3679 */
3680 tp->ts_recent = 0;
3681 } else {
3682 tcpstat.tcps_rcvduppack++;
9bccf70c 3683 tcpstat.tcps_rcvdupbyte += tlen;
4bd07ac2 3684 tp->t_pawsdrop++;
1c79356b 3685 tcpstat.tcps_pawsdrop++;
4bd07ac2
A
3686
3687 /*
3688 * PAWS-drop when ECN is being used? That indicates
3689 * that ECT-marked packets take a different path, with
3690 * different congestion-characteristics.
3691 *
3692 * Only fallback when we did send less than 2GB as PAWS
3693 * really has no reason to kick in earlier.
3694 */
3695 if (TCP_ECN_ENABLED(tp) &&
3696 inp->inp_stat->rxbytes < 2147483648) {
3697 INP_INC_IFNET_STAT(inp, ecn_fallback_reorder);
3698 tcpstat.tcps_ecn_fallback_reorder++;
3699 tcp_heuristic_ecn_aggressive(tp);
3700 }
3701
6d2010ae 3702 if (nstat_collect) {
39037602 3703 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt,
39236c6e 3704 1, tlen, NSTAT_RX_FLAG_DUPLICATE);
fe8ab488
A
3705 INP_ADD_STAT(inp, cell, wifi, wired,
3706 rxpackets, 1);
3707 INP_ADD_STAT(inp, cell, wifi, wired,
3708 rxbytes, tlen);
6d2010ae 3709 tp->t_stat.rxduplicatebytes += tlen;
5ba3f43e 3710 inp_set_activity_bitmap(inp);
6d2010ae 3711 }
3e170ce0 3712 if (tlen > 0)
8ad349bb
A
3713 goto dropafterack;
3714 goto drop;
1c79356b
A
3715 }
3716 }
3717
1c79356b
A
3718 /*
3719 * In the SYN-RECEIVED state, validate that the packet belongs to
3720 * this connection before trimming the data to fit the receive
3721 * window. Check the sequence number versus IRS since we know
3722 * the sequence numbers haven't wrapped. This is a partial fix
3723 * for the "LAND" DoS attack.
3724 */
9bccf70c
A
3725 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
3726 rstreason = BANDLIM_RST_OPENPORT;
39236c6e 3727 IF_TCP_STATINC(ifp, dospacket);
1c79356b 3728 goto dropwithreset;
9bccf70c 3729 }
1c79356b
A
3730
3731 todrop = tp->rcv_nxt - th->th_seq;
3732 if (todrop > 0) {
3733 if (thflags & TH_SYN) {
3734 thflags &= ~TH_SYN;
3735 th->th_seq++;
3736 if (th->th_urp > 1)
3737 th->th_urp--;
3738 else
3739 thflags &= ~TH_URG;
3740 todrop--;
3741 }
3742 /*
3743 * Following if statement from Stevens, vol. 2, p. 960.
3744 */
9bccf70c
A
3745 if (todrop > tlen
3746 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1c79356b
A
3747 /*
3748 * Any valid FIN must be to the left of the window.
3749 * At this point the FIN must be a duplicate or out
3750 * of sequence; drop it.
3751 */
3752 thflags &= ~TH_FIN;
3753
3754 /*
3755 * Send an ACK to resynchronize and drop any data.
3756 * But keep on processing for RST or ACK.
3757 */
3758 tp->t_flags |= TF_ACKNOW;
316670eb
A
3759 if (todrop == 1) {
3760 /* This could be a keepalive */
3761 soevent(so, SO_FILT_HINT_LOCKED |
3762 SO_FILT_HINT_KEEPALIVE);
3763 }
9bccf70c 3764 todrop = tlen;
1c79356b 3765 tcpstat.tcps_rcvduppack++;
39037602 3766 tcpstat.tcps_rcvdupbyte += todrop;
1c79356b
A
3767 } else {
3768 tcpstat.tcps_rcvpartduppack++;
3769 tcpstat.tcps_rcvpartdupbyte += todrop;
3770 }
3e170ce0
A
3771
3772 if (TCP_DSACK_ENABLED(tp) && todrop > 1) {
3773 /*
3774 * Note the duplicate data sequence space so that
3775 * it can be reported in DSACK option.
3776 */
3777 tp->t_dsack_lseq = th->th_seq;
3778 tp->t_dsack_rseq = th->th_seq + todrop;
3779 tp->t_flags |= TF_ACKNOW;
3780 }
6d2010ae 3781 if (nstat_collect) {
39037602 3782 nstat_route_rx(tp->t_inpcb->inp_route.ro_rt, 1,
39236c6e 3783 todrop, NSTAT_RX_FLAG_DUPLICATE);
fe8ab488
A
3784 INP_ADD_STAT(inp, cell, wifi, wired, rxpackets, 1);
3785 INP_ADD_STAT(inp, cell, wifi, wired, rxbytes, todrop);
6d2010ae 3786 tp->t_stat.rxduplicatebytes += todrop;
5ba3f43e 3787 inp_set_activity_bitmap(inp);
6d2010ae 3788 }
9bccf70c 3789 drop_hdrlen += todrop; /* drop from the top afterwards */
1c79356b 3790 th->th_seq += todrop;
9bccf70c 3791 tlen -= todrop;
1c79356b
A
3792 if (th->th_urp > todrop)
3793 th->th_urp -= todrop;
3794 else {
3795 thflags &= ~TH_URG;
3796 th->th_urp = 0;
3797 }
3798 }
3799
3800 /*
3e170ce0
A
3801 * If new data are received on a connection after the user
3802 * processes are gone, then RST the other end.
3803 * Send also a RST when we received a data segment after we've
3804 * sent our FIN when the socket is defunct.
3805 * Note that an MPTCP subflow socket would have SS_NOFDREF set
5ba3f43e
A
3806 * by default. So, if it's an MPTCP-subflow we rather check the
3807 * MPTCP-level's socket state for SS_NOFDREF.
1c79356b 3808 */
5ba3f43e
A
3809 if (tlen) {
3810 boolean_t close_it = FALSE;
3811
3812 if (!(so->so_flags & SOF_MP_SUBFLOW) && (so->so_state & SS_NOFDREF) &&
3813 tp->t_state > TCPS_CLOSE_WAIT)
3814 close_it = TRUE;
3815
3816 if ((so->so_flags & SOF_MP_SUBFLOW) && (mptetoso(tptomptp(tp)->mpt_mpte)->so_state & SS_NOFDREF) &&
3817 tp->t_state > TCPS_CLOSE_WAIT)
3818 close_it = TRUE;
3819
3820 if ((so->so_flags & SOF_DEFUNCT) && tp->t_state > TCPS_FIN_WAIT_1)
3821 close_it = TRUE;
3822
3823 if (close_it) {
3824 tp = tcp_close(tp);
3825 tcpstat.tcps_rcvafterclose++;
3826 rstreason = BANDLIM_UNLIMITED;
3827 IF_TCP_STATINC(ifp, cleanup);
3828 goto dropwithreset;
3829 }
1c79356b
A
3830 }
3831
3832 /*
3833 * If segment ends after window, drop trailing data
3834 * (and PUSH and FIN); if nothing left, just ACK.
3835 */
9bccf70c 3836 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1c79356b
A
3837 if (todrop > 0) {
3838 tcpstat.tcps_rcvpackafterwin++;
9bccf70c
A
3839 if (todrop >= tlen) {
3840 tcpstat.tcps_rcvbyteafterwin += tlen;
1c79356b
A
3841 /*
3842 * If a new connection request is received
3843 * while in TIME_WAIT, drop the old connection
3844 * and start over if the sequence numbers
3845 * are above the previous ones.
3846 */
3847 if (thflags & TH_SYN &&
3848 tp->t_state == TCPS_TIME_WAIT &&
3849 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
9bccf70c 3850 iss = tcp_new_isn(tp);
1c79356b 3851 tp = tcp_close(tp);
5ba3f43e 3852 socket_unlock(so, 1);
1c79356b
A
3853 goto findpcb;
3854 }
3855 /*
3856 * If window is closed can only take segments at
3857 * window edge, and have to drop data and PUSH from
3858 * incoming segments. Continue processing, but
3859 * remember to ack. Otherwise, drop segment
3860 * and ack.
3861 */
3862 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
3863 tp->t_flags |= TF_ACKNOW;
3864 tcpstat.tcps_rcvwinprobe++;
3865 } else
3866 goto dropafterack;
3867 } else
3868 tcpstat.tcps_rcvbyteafterwin += todrop;
3869 m_adj(m, -todrop);
9bccf70c 3870 tlen -= todrop;
1c79356b
A
3871 thflags &= ~(TH_PUSH|TH_FIN);
3872 }
3873
3874 /*
3875 * If last ACK falls within this segment's sequence numbers,
3876 * record its timestamp.
39037602 3877 * NOTE:
8ad349bb
A
3878 * 1) That the test incorporates suggestions from the latest
3879 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
3880 * 2) That updating only on newer timestamps interferes with
3881 * our earlier PAWS tests, so this check should be solely
3882 * predicated on the sequence space of this segment.
39037602
A
3883 * 3) That we modify the segment boundary check to be
3884 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
8ad349bb
A
3885 * instead of RFC1323's
3886 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
3887 * This modified check allows us to overcome RFC1323's
3888 * limitations as described in Stevens TCP/IP Illustrated
3889 * Vol. 2 p.869. In such cases, we can still calculate the
3890 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1c79356b 3891 */
8ad349bb
A
3892 if ((to.to_flags & TOF_TS) != 0 &&
3893 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
3894 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
3895 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1c79356b
A
3896 tp->ts_recent_age = tcp_now;
3897 tp->ts_recent = to.to_tsval;
3898 }
3899
3900 /*
3901 * If a SYN is in the window, then this is an
3902 * error and we send an RST and drop the connection.
3903 */
3904 if (thflags & TH_SYN) {
3905 tp = tcp_drop(tp, ECONNRESET);
9bccf70c 3906 rstreason = BANDLIM_UNLIMITED;
1c79356b 3907 postevent(so, 0, EV_RESET);
39236c6e 3908 IF_TCP_STATINC(ifp, synwindow);
1c79356b
A
3909 goto dropwithreset;
3910 }
3911
3912 /*
3913 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
3914 * flag is on (half-synchronized state), then queue data for
3915 * later processing; else drop segment and return.
3916 */
3917 if ((thflags & TH_ACK) == 0) {
3918 if (tp->t_state == TCPS_SYN_RECEIVED ||
3e170ce0
A
3919 (tp->t_flags & TF_NEEDSYN)) {
3920 if ((tfo_enabled(tp))) {
3921 /*
3922 * So, we received a valid segment while in
3923 * SYN-RECEIVED (TF_NEEDSYN is actually never
3924 * set, so this is dead code).
3925 * As this cannot be an RST (see that if a bit
3926 * higher), and it does not have the ACK-flag
3927 * set, we want to retransmit the SYN/ACK.
3928 * Thus, we have to reset snd_nxt to snd_una to
3929 * trigger the going back to sending of the
3930 * SYN/ACK. This is more consistent with the
3931 * behavior of tcp_output(), which expects
3932 * to send the segment that is pointed to by
3933 * snd_nxt.
3934 */
3935 tp->snd_nxt = tp->snd_una;
3936
3937 /*
3938 * We need to make absolutely sure that we are
3939 * going to reply upon a duplicate SYN-segment.
3940 */
3941 if (th->th_flags & TH_SYN)
3942 needoutput = 1;
3943 }
3944
1c79356b 3945 goto step6;
3e170ce0 3946 } else if (tp->t_flags & TF_ACKNOW)
2d21ac55 3947 goto dropafterack;
1c79356b
A
3948 else
3949 goto drop;
3950 }
3951
3952 /*
3953 * Ack processing.
3954 */
39236c6e 3955
1c79356b
A
3956 switch (tp->t_state) {
3957
3958 /*
3959 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
3960 * ESTABLISHED state and continue processing.
3961 * The ACK was checked above.
3962 */
3963 case TCPS_SYN_RECEIVED:
3964
3965 tcpstat.tcps_connects++;
1c79356b
A
3966
3967 /* Do window scaling? */
3e170ce0 3968 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
1c79356b
A
3969 tp->snd_scale = tp->requested_s_scale;
3970 tp->rcv_scale = tp->request_r_scale;
6d2010ae
A
3971 tp->snd_wnd = th->th_win << tp->snd_scale;
3972 tiwin = tp->snd_wnd;
1c79356b 3973 }
1c79356b
A
3974 /*
3975 * Make transitions:
3976 * SYN-RECEIVED -> ESTABLISHED
3977 * SYN-RECEIVED* -> FIN-WAIT-1
3978 */
6d2010ae 3979 tp->t_starttime = tcp_now;
316670eb 3980 tcp_sbrcv_tstmp_check(tp);
1c79356b 3981 if (tp->t_flags & TF_NEEDFIN) {
3e170ce0
A
3982 DTRACE_TCP4(state__change, void, NULL,
3983 struct inpcb *, inp,
3984 struct tcpcb *, tp, int32_t, TCPS_FIN_WAIT_1);
1c79356b
A
3985 tp->t_state = TCPS_FIN_WAIT_1;
3986 tp->t_flags &= ~TF_NEEDFIN;
3987 } else {
3e170ce0
A
3988 DTRACE_TCP4(state__change, void, NULL,
3989 struct inpcb *, inp,
3990 struct tcpcb *, tp, int32_t, TCPS_ESTABLISHED);
1c79356b 3991 tp->t_state = TCPS_ESTABLISHED;
39236c6e
A
3992 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
3993 TCP_CONN_KEEPIDLE(tp));
6d2010ae 3994 if (nstat_collect)
3e170ce0
A
3995 nstat_route_connect_success(
3996 tp->t_inpcb->inp_route.ro_rt);
39037602
A
3997 /*
3998 * The SYN is acknowledged but una is not updated
3999 * yet. So pass the value of ack to compute
4000 * sndbytes correctly
4001 */
4002 inp_count_sndbytes(inp, th->th_ack);
1c79356b
A
4003 }
4004 /*
4005 * If segment contains data or ACK, will call tcp_reass()
4006 * later; if not, do so now to pass queued data to user.
4007 */
9bccf70c 4008 if (tlen == 0 && (thflags & TH_FIN) == 0)
2d21ac55 4009 (void) tcp_reass(tp, (struct tcphdr *)0, &tlen,
39236c6e 4010 NULL, ifp);
1c79356b 4011 tp->snd_wl1 = th->th_seq - 1;
4a3eedf9 4012
39236c6e
A
4013#if MPTCP
4014 /*
4015 * Do not send the connect notification for additional subflows
4016 * until ACK for 3-way handshake arrives.
4017 */
4018 if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
4019 (tp->t_mpflags & TMPF_SENT_JOIN)) {
4020 isconnected = FALSE;
4021 } else
4022#endif /* MPTCP */
4023 isconnected = TRUE;
3e170ce0
A
4024 if ((tp->t_tfo_flags & TFO_F_COOKIE_VALID)) {
4025 /* Done this when receiving the SYN */
4026 isconnected = FALSE;
4027
4028 OSDecrementAtomic(&tcp_tfo_halfcnt);
4029
4030 /* Panic if something has gone terribly wrong. */
4031 VERIFY(tcp_tfo_halfcnt >= 0);
4032
4033 tp->t_tfo_flags &= ~TFO_F_COOKIE_VALID;
4034 }
4035
4036 /*
4037 * In case there is data in the send-queue (e.g., TFO is being
4038 * used, or connectx+data has been done), then if we would
4039 * "FALLTHROUGH", we would handle this ACK as if data has been
4040 * acknowledged. But, we have to prevent this. And this
4041 * can be prevented by increasing snd_una by 1, so that the
4042 * SYN is not considered as data (snd_una++ is actually also
4043 * done in SYN_SENT-state as part of the regular TCP stack).
4044 *
4045 * In case there is data on this ack as well, the data will be
4046 * handled by the label "dodata" right after step6.
4047 */
4048 if (so->so_snd.sb_cc) {
4049 tp->snd_una++; /* SYN is acked */
4050 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
4051 tp->snd_nxt = tp->snd_una;
4052
4053 /*
4054 * No duplicate-ACK handling is needed. So, we
4055 * directly advance to processing the ACK (aka,
4056 * updating the RTT estimation,...)
4057 *
4058 * But, we first need to handle eventual SACKs,
4059 * because TFO will start sending data with the
4060 * SYN/ACK, so it might be that the client
4061 * includes a SACK with its ACK.
4062 */
4063 if (SACK_ENABLED(tp) &&
4064 (to.to_nsacks > 0 ||
4065 !TAILQ_EMPTY(&tp->snd_holes)))
4066 tcp_sack_doack(tp, &to, th,
4067 &sack_bytes_acked);
4068
4069 goto process_ACK;
4070 }
4071
4072 /* FALLTHROUGH */
4a3eedf9 4073
1c79356b
A
4074 /*
4075 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
4076 * ACKs. If the ack is in the range
4077 * tp->snd_una < th->th_ack <= tp->snd_max
4078 * then advance tp->snd_una to th->th_ack and drop
4079 * data from the retransmission queue. If this ACK reflects
4080 * more up to date window information we update our window information.
4081 */
4082 case TCPS_ESTABLISHED:
4083 case TCPS_FIN_WAIT_1:
4084 case TCPS_FIN_WAIT_2:
4085 case TCPS_CLOSE_WAIT:
4086 case TCPS_CLOSING:
4087 case TCPS_LAST_ACK:
4088 case TCPS_TIME_WAIT:
8ad349bb
A
4089 if (SEQ_GT(th->th_ack, tp->snd_max)) {
4090 tcpstat.tcps_rcvacktoomuch++;
4091 goto dropafterack;
4092 }
3e170ce0
A
4093 if (SACK_ENABLED(tp) && to.to_nsacks > 0) {
4094 recvd_dsack = tcp_sack_process_dsack(tp, &to, th);
4095 /*
4096 * If DSACK is received and this packet has no
4097 * other SACK information, it can be dropped.
4098 * We do not want to treat it as a duplicate ack.
4099 */
4100 if (recvd_dsack &&
4101 SEQ_LEQ(th->th_ack, tp->snd_una) &&
4102 to.to_nsacks == 0) {
4103 tcp_bad_rexmt_check(tp, th, &to);
4104 goto drop;
4105 }
4106 }
4107
39236c6e 4108 if (SACK_ENABLED(tp) &&
8ad349bb 4109 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes)))
fe8ab488
A
4110 tcp_sack_doack(tp, &to, th, &sack_bytes_acked);
4111
39236c6e 4112#if MPTCP
5ba3f43e 4113 if (tp->t_mpuna && SEQ_GEQ(th->th_ack, tp->t_mpuna)) {
39236c6e
A
4114 if (tp->t_mpflags & TMPF_PREESTABLISHED) {
4115 /* MP TCP establishment succeeded */
4116 tp->t_mpuna = 0;
4117 if (tp->t_mpflags & TMPF_JOINED_FLOW) {
4118 if (tp->t_mpflags & TMPF_SENT_JOIN) {
4119 tp->t_mpflags &=
4120 ~TMPF_PREESTABLISHED;
4121 tp->t_mpflags |=
4122 TMPF_MPTCP_TRUE;
4123 so->so_flags |= SOF_MPTCP_TRUE;
3e170ce0
A
4124 mptcplog((LOG_DEBUG, "MPTCP "
4125 "Sockets: %s \n",__func__),
4126 MPTCP_SOCKET_DBG,
4127 MPTCP_LOGLVL_LOG);
4128
39236c6e
A
4129 tp->t_timer[TCPT_JACK_RXMT] = 0;
4130 tp->t_mprxtshift = 0;
4131 isconnected = TRUE;
4132 } else {
4133 isconnected = FALSE;
4134 }
4135 } else {
4136 isconnected = TRUE;
39236c6e
A
4137 }
4138 }
4139 }
4140#endif /* MPTCP */
3e170ce0
A
4141
4142 tcp_tfo_rcv_ack(tp, th);
4143
39236c6e
A
4144 /*
4145 * If we have outstanding data (other than
4146 * a window probe), this is a completely
39037602
A
4147 * duplicate ack and the ack is the biggest we've seen.
4148 *
4149 * Need to accommodate a change in window on duplicate acks
4150 * to allow operating systems that update window during
4151 * recovery with SACK
4152 */
1c79356b 4153 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
39037602
A
4154 if (tlen == 0 && (tiwin == tp->snd_wnd ||
4155 (to.to_nsacks > 0 && sack_bytes_acked > 0))) {
8a3053a0
A
4156 /*
4157 * If both ends send FIN at the same time,
4158 * then the ack will be a duplicate ack
4159 * but we have to process the FIN. Check
4160 * for this condition and process the FIN
4161 * instead of the dupack
39037602 4162 */
8a3053a0 4163 if ((thflags & TH_FIN) &&
39037602 4164 !TCPS_HAVERCVDFIN(tp->t_state))
8a3053a0 4165 break;
39236c6e
A
4166process_dupack:
4167#if MPTCP
4168 /*
4169 * MPTCP options that are ignored must
4170 * not be treated as duplicate ACKs.
4171 */
4172 if (to.to_flags & TOF_MPTCP) {
4173 goto drop;
4174 }
fe8ab488
A
4175
4176 if ((isconnected) && (tp->t_mpflags & TMPF_JOINED_FLOW)) {
3e170ce0
A
4177 mptcplog((LOG_DEBUG, "MPTCP "
4178 "Sockets: bypass ack recovery\n"),
39037602 4179 MPTCP_SOCKET_DBG,
3e170ce0 4180 MPTCP_LOGLVL_VERBOSE);
fe8ab488
A
4181 break;
4182 }
39236c6e 4183#endif /* MPTCP */
fe8ab488
A
4184 /*
4185 * If a duplicate acknowledgement was seen
4186 * after ECN, it indicates packet loss in
4187 * addition to ECN. Reset INRECOVERY flag
4188 * so that we can process partial acks
4189 * correctly
4190 */
4191 if (tp->ecn_flags & TE_INRECOVERY)
4192 tp->ecn_flags &= ~TE_INRECOVERY;
4193
1c79356b 4194 tcpstat.tcps_rcvdupack++;
39236c6e 4195 ++tp->t_dupacks;
fe8ab488
A
4196
4197 /*
4198 * Check if we need to reset the limit on
4199 * early retransmit
39236c6e 4200 */
fe8ab488
A
4201 if (tp->t_early_rexmt_count > 0 &&
4202 TSTMP_GEQ(tcp_now,
4203 (tp->t_early_rexmt_win +
4204 TCP_EARLY_REXMT_WIN)))
39236c6e
A
4205 tp->t_early_rexmt_count = 0;
4206
39037602 4207 /*
39236c6e
A
4208 * Is early retransmit needed? We check for
4209 * this when the connection is waiting for
fe8ab488 4210 * duplicate acks to enter fast recovery.
39236c6e 4211 */
fe8ab488
A
4212 if (!IN_FASTRECOVERY(tp))
4213 tcp_early_rexmt_check(tp, th);
39236c6e 4214
1c79356b 4215 /*
39037602 4216 * If we've seen exactly rexmt threshold
39236c6e 4217 * of duplicate acks, assume a packet
1c79356b
A
4218 * has been dropped and retransmit it.
4219 * Kludge snd_nxt & the congestion
4220 * window so we send only this one
4221 * packet.
4222 *
4223 * We know we're losing at the current
4224 * window size so do congestion avoidance
4225 * (set ssthresh to half the current window
4226 * and pull our congestion window back to
4227 * the new ssthresh).
4228 *
4229 * Dup acks mean that packets have left the
4230 * network (they're now cached at the receiver)
4231 * so bump cwnd by the amount in the receiver
4232 * to keep a constant cwnd packets in the
4233 * network.
4234 */
4235 if (tp->t_timer[TCPT_REXMT] == 0 ||
fe8ab488
A
4236 (th->th_ack != tp->snd_una
4237 && sack_bytes_acked == 0)) {
1c79356b 4238 tp->t_dupacks = 0;
39236c6e
A
4239 tp->t_rexmtthresh = tcprexmtthresh;
4240 } else if (tp->t_dupacks > tp->t_rexmtthresh ||
fe8ab488
A
4241 IN_FASTRECOVERY(tp)) {
4242
4243 /*
4244 * If this connection was seeing packet
4245 * reordering, then recovery might be
4246 * delayed to disambiguate between
4247 * reordering and loss
4248 */
4249 if (SACK_ENABLED(tp) && !IN_FASTRECOVERY(tp) &&
39037602 4250 (tp->t_flagsext &
fe8ab488
A
4251 (TF_PKTS_REORDERED|TF_DELAY_RECOVERY)) ==
4252 (TF_PKTS_REORDERED|TF_DELAY_RECOVERY)) {
4253 /*
4254 * Since the SACK information is already
4255 * updated, this ACK will be dropped
4256 */
4257 break;
4258 }
4259
39037602 4260 if (SACK_ENABLED(tp)
fe8ab488 4261 && IN_FASTRECOVERY(tp)) {
8ad349bb 4262 int awnd;
39037602 4263
8ad349bb
A
4264 /*
4265 * Compute the amount of data in flight first.
39037602
A
4266 * We can inject new data into the pipe iff
4267 * we have less than 1/2 the original window's
8ad349bb 4268 * worth of data in flight.
9bccf70c 4269 */
8ad349bb
A
4270 awnd = (tp->snd_nxt - tp->snd_fack) +
4271 tp->sackhint.sack_bytes_rexmit;
4272 if (awnd < tp->snd_ssthresh) {
4273 tp->snd_cwnd += tp->t_maxseg;
4274 if (tp->snd_cwnd > tp->snd_ssthresh)
4275 tp->snd_cwnd = tp->snd_ssthresh;
4276 }
39037602 4277 } else {
9bccf70c 4278 tp->snd_cwnd += tp->t_maxseg;
39037602 4279 }
6d2010ae 4280
39037602
A
4281 /* Process any window updates */
4282 if (tiwin > tp->snd_wnd)
4283 tcp_update_window(tp, thflags,
4284 th, tiwin, tlen);
4285 tcp_ccdbg_trace(tp, th,
4286 TCP_CC_IN_FASTRECOVERY);
6d2010ae 4287
8ad349bb 4288 (void) tcp_output(tp);
39037602 4289
8ad349bb 4290 goto drop;
39236c6e 4291 } else if (tp->t_dupacks == tp->t_rexmtthresh) {
8ad349bb 4292 tcp_seq onxt = tp->snd_nxt;
8ad349bb
A
4293
4294 /*
4295 * If we're doing sack, check to
4296 * see if we're already in sack
4297 * recovery. If we're not doing sack,
4298 * check to see if we're in newreno
4299 * recovery.
4300 */
39236c6e 4301 if (SACK_ENABLED(tp)) {
8ad349bb
A
4302 if (IN_FASTRECOVERY(tp)) {
4303 tp->t_dupacks = 0;
4304 break;
fe8ab488
A
4305 } else if (tp->t_flagsext & TF_DELAY_RECOVERY) {
4306 break;
8ad349bb 4307 }
6d2010ae 4308 } else {
8ad349bb
A
4309 if (SEQ_LEQ(th->th_ack,
4310 tp->snd_recover)) {
4311 tp->t_dupacks = 0;
4312 break;
4313 }
9bccf70c 4314 }
3e170ce0
A
4315 if (tp->t_flags & TF_SENTFIN)
4316 tp->snd_recover = tp->snd_max - 1;
4317 else
4318 tp->snd_recover = tp->snd_max;
fe8ab488
A
4319 tp->t_timer[TCPT_PTO] = 0;
4320 tp->t_rtttime = 0;
4321
4322 /*
4323 * If the connection has seen pkt
4324 * reordering, delay recovery until
4325 * it is clear that the packet
4326 * was lost.
4327 */
4328 if (SACK_ENABLED(tp) &&
4329 (tp->t_flagsext &
4330 (TF_PKTS_REORDERED|TF_DELAY_RECOVERY))
4331 == TF_PKTS_REORDERED &&
4332 !IN_FASTRECOVERY(tp) &&
4333 tp->t_reorderwin > 0 &&
3e170ce0
A
4334 (tp->t_state == TCPS_ESTABLISHED ||
4335 tp->t_state == TCPS_FIN_WAIT_1)) {
fe8ab488
A
4336 tp->t_timer[TCPT_DELAYFR] =
4337 OFFSET_FROM_START(tp,
4338 tp->t_reorderwin);
4339 tp->t_flagsext |= TF_DELAY_RECOVERY;
4340 tcpstat.tcps_delay_recovery++;
4341 tcp_ccdbg_trace(tp, th,
4342 TCP_CC_DELAY_FASTRECOVERY);
4343 break;
4344 }
4345
3e170ce0 4346 tcp_rexmt_save_state(tp);
6d2010ae 4347 /*
39037602 4348 * If the current tcp cc module has
6d2010ae
A
4349 * defined a hook for tasks to run
4350 * before entering FR, call it
4351 */
4352 if (CC_ALGO(tp)->pre_fr != NULL)
316670eb 4353 CC_ALGO(tp)->pre_fr(tp);
8ad349bb 4354 ENTER_FASTRECOVERY(tp);
1c79356b 4355 tp->t_timer[TCPT_REXMT] = 0;
3e170ce0 4356 if (TCP_ECN_ENABLED(tp))
316670eb 4357 tp->ecn_flags |= TE_SENDCWR;
fe8ab488 4358
39236c6e 4359 if (SACK_ENABLED(tp)) {
8ad349bb 4360 tcpstat.tcps_sack_recovery_episode++;
4bd07ac2 4361 tp->t_sack_recovery_episode++;
8ad349bb
A
4362 tp->sack_newdata = tp->snd_nxt;
4363 tp->snd_cwnd = tp->t_maxseg;
3e170ce0
A
4364 tp->t_flagsext &=
4365 ~TF_CWND_NONVALIDATED;
39037602
A
4366
4367 /* Process any window updates */
4368 if (tiwin > tp->snd_wnd)
4369 tcp_update_window(
4370 tp, thflags,
4371 th, tiwin, tlen);
4372
fe8ab488
A
4373 tcp_ccdbg_trace(tp, th,
4374 TCP_CC_ENTER_FASTRECOVERY);
8ad349bb
A
4375 (void) tcp_output(tp);
4376 goto drop;
4377 }
1c79356b
A
4378 tp->snd_nxt = th->th_ack;
4379 tp->snd_cwnd = tp->t_maxseg;
39037602
A
4380
4381 /* Process any window updates */
4382 if (tiwin > tp->snd_wnd)
4383 tcp_update_window(tp,
4384 thflags,
4385 th, tiwin, tlen);
4386
1c79356b 4387 (void) tcp_output(tp);
3e170ce0
A
4388 if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
4389 tcp_cc_adjust_nonvalidated_cwnd(tp);
4390 } else {
4391 tp->snd_cwnd = tp->snd_ssthresh +
4392 tp->t_maxseg * tp->t_dupacks;
4393 }
1c79356b
A
4394 if (SEQ_GT(onxt, tp->snd_nxt))
4395 tp->snd_nxt = onxt;
39037602 4396
fe8ab488
A
4397 tcp_ccdbg_trace(tp, th,
4398 TCP_CC_ENTER_FASTRECOVERY);
1c79356b 4399 goto drop;
39037602 4400 } else if (limited_txmt &&
39236c6e 4401 ALLOW_LIMITED_TRANSMIT(tp) &&
39037602 4402 (!(SACK_ENABLED(tp)) || sack_bytes_acked > 0) &&
39236c6e
A
4403 (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)) > 0) {
4404 u_int32_t incr = (tp->t_maxseg * tp->t_dupacks);
4405
4406 /* Use Limited Transmit algorithm on the first two
4407 * duplicate acks when there is new data to transmit
4408 */
4409 tp->snd_cwnd += incr;
4410 tcpstat.tcps_limited_txt++;
4411 (void) tcp_output(tp);
4412
fe8ab488 4413 tcp_ccdbg_trace(tp, th, TCP_CC_LIMITED_TRANSMIT);
39037602 4414
39236c6e
A
4415 /* Reset snd_cwnd back to normal */
4416 tp->snd_cwnd -= incr;
1c79356b 4417 }
39236c6e 4418 }
1c79356b
A
4419 break;
4420 }
b0d623f7
A
4421 /*
4422 * If the congestion window was inflated to account
4423 * for the other side's cached packets, retract it.
4424 */
6d2010ae
A
4425 if (IN_FASTRECOVERY(tp)) {
4426 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
fe8ab488 4427 /*
39037602 4428 * If we received an ECE and entered
fe8ab488
A
4429 * recovery, the subsequent ACKs should
4430 * not be treated as partial acks.
4431 */
4432 if (tp->ecn_flags & TE_INRECOVERY)
4433 goto process_ACK;
4434
39236c6e 4435 if (SACK_ENABLED(tp))
6d2010ae
A
4436 tcp_sack_partialack(tp, th);
4437 else
39037602 4438 tcp_newreno_partial_ack(tp, th);
fe8ab488 4439 tcp_ccdbg_trace(tp, th, TCP_CC_PARTIAL_ACK);
6d2010ae
A
4440 } else {
4441 EXIT_FASTRECOVERY(tp);
4442 if (CC_ALGO(tp)->post_fr != NULL)
4443 CC_ALGO(tp)->post_fr(tp, th);
3e170ce0
A
4444 tp->t_pipeack = 0;
4445 tcp_clear_pipeack_state(tp);
fe8ab488
A
4446 tcp_ccdbg_trace(tp, th,
4447 TCP_CC_EXIT_FASTRECOVERY);
4448 }
39037602 4449 } else if ((tp->t_flagsext &
fe8ab488
A
4450 (TF_PKTS_REORDERED|TF_DELAY_RECOVERY))
4451 == (TF_PKTS_REORDERED|TF_DELAY_RECOVERY)) {
4452 /*
4453 * If the ack acknowledges upto snd_recover or if
4454 * it acknowledges all the snd holes, exit
4455 * recovery and cancel the timer. Otherwise,
4456 * this is a partial ack. Wait for recovery timer
4457 * to enter recovery. The snd_holes have already
4458 * been updated.
4459 */
4460 if (SEQ_GEQ(th->th_ack, tp->snd_recover) ||
4461 TAILQ_EMPTY(&tp->snd_holes)) {
4462 tp->t_timer[TCPT_DELAYFR] = 0;
4463 tp->t_flagsext &= ~TF_DELAY_RECOVERY;
4464 EXIT_FASTRECOVERY(tp);
4465 tcp_ccdbg_trace(tp, th,
4466 TCP_CC_EXIT_FASTRECOVERY);
6d2010ae
A
4467 }
4468 } else {
593a1d5f 4469 /*
fe8ab488
A
4470 * We were not in fast recovery. Reset the
4471 * duplicate ack counter.
593a1d5f
A
4472 */
4473 tp->t_dupacks = 0;
39236c6e 4474 tp->t_rexmtthresh = tcprexmtthresh;
593a1d5f 4475 }
593a1d5f
A
4476
4477
1c79356b 4478 /*
8ad349bb 4479 * If we reach this point, ACK is not a duplicate,
1c79356b
A
4480 * i.e., it ACKs something we sent.
4481 */
4482 if (tp->t_flags & TF_NEEDSYN) {
4483 /*
4484 * T/TCP: Connection was half-synchronized, and our
4485 * SYN has been ACK'd (so connection is now fully
4486 * synchronized). Go to non-starred state,
4487 * increment snd_una for ACK of SYN, and check if
4488 * we can do window scaling.
4489 */
4490 tp->t_flags &= ~TF_NEEDSYN;
4491 tp->snd_una++;
4492 /* Do window scaling? */
3e170ce0 4493 if (TCP_WINDOW_SCALE_ENABLED(tp)) {
1c79356b
A
4494 tp->snd_scale = tp->requested_s_scale;
4495 tp->rcv_scale = tp->request_r_scale;
4496 }
4497 }
4498
4499process_ACK:
3e170ce0 4500 VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
39236c6e 4501 acked = BYTES_ACKED(th, tp);
1c79356b
A
4502 tcpstat.tcps_rcvackpack++;
4503 tcpstat.tcps_rcvackbyte += acked;
4504
9bccf70c 4505 /*
39236c6e
A
4506 * If the last packet was a retransmit, make sure
4507 * it was not spurious.
4508 *
fe8ab488
A
4509 * This will also take care of congestion window
4510 * adjustment if a last packet was recovered due to a
4511 * tail loss probe.
9bccf70c 4512 */
fe8ab488 4513 tcp_bad_rexmt_check(tp, th, &to);
9bccf70c 4514
39236c6e
A
4515 /* Recalculate the RTT */
4516 tcp_compute_rtt(tp, &to, th);
1c79356b
A
4517
4518 /*
4519 * If all outstanding data is acked, stop retransmit
4520 * timer and remember to restart (more output or persist).
4521 * If there is more data to be acked, restart retransmit
4522 * timer, using current (possibly backed-off) value.
4523 */
39037602
A
4524 TCP_RESET_REXMT_STATE(tp);
4525 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
4526 tp->t_rttmin, TCPTV_REXMTMAX,
4527 TCP_ADD_REXMTSLOP(tp));
1c79356b
A
4528 if (th->th_ack == tp->snd_max) {
4529 tp->t_timer[TCPT_REXMT] = 0;
fe8ab488 4530 tp->t_timer[TCPT_PTO] = 0;
1c79356b
A
4531 needoutput = 1;
4532 } else if (tp->t_timer[TCPT_PERSIST] == 0)
fe8ab488
A
4533 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp,
4534 tp->t_rxtcur);
1c79356b
A
4535
4536 /*
fe8ab488
A
4537 * If no data (only SYN) was ACK'd, skip rest of ACK
4538 * processing.
1c79356b
A
4539 */
4540 if (acked == 0)
4541 goto step6;
4542
3e170ce0
A
4543 /*
4544 * When outgoing data has been acked (except the SYN+data), we
4545 * mark this connection as "sending good" for TFO.
4546 */
4547 if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
4548 !(tp->t_tfo_flags & TFO_F_NO_SNDPROBING) &&
4549 !(th->th_flags & TH_SYN))
5ba3f43e 4550 tp->t_tfo_flags |= TFO_F_NO_SNDPROBING;
fe8ab488 4551
3e170ce0
A
4552 /*
4553 * If TH_ECE is received, make sure that ECN is enabled
4554 * on that connection and we have sent ECT on data packets.
4555 */
4556 if ((thflags & TH_ECE) != 0 && TCP_ECN_ENABLED(tp) &&
4557 (tp->ecn_flags & TE_SENDIPECT)) {
2d21ac55 4558 /*
fe8ab488
A
4559 * Reduce the congestion window if we haven't
4560 * done so.
2d21ac55 4561 */
fe8ab488 4562 if (!IN_FASTRECOVERY(tp)) {
316670eb 4563 tcp_reduce_congestion_window(tp);
fe8ab488 4564 tp->ecn_flags |= (TE_INRECOVERY|TE_SENDCWR);
3e170ce0
A
4565 /*
4566 * Also note that the connection received
4567 * ECE atleast once
4568 */
4569 tp->ecn_flags |= TE_RECV_ECN_ECE;
4bd07ac2 4570 INP_INC_IFNET_STAT(inp, ecn_recv_ece);
3e170ce0 4571 tcpstat.tcps_ecn_recv_ece++;
fe8ab488 4572 tcp_ccdbg_trace(tp, th, TCP_CC_ECN_RCVD);
2d21ac55 4573 }
6d2010ae 4574 }
b0d623f7 4575
6d2010ae
A
4576 /*
4577 * When new data is acked, open the congestion window.
4578 * The specifics of how this is achieved are up to the
4579 * congestion control algorithm in use for this connection.
4580 *
4581 * The calculations in this function assume that snd_una is
4582 * not updated yet.
4583 */
4584 if (!IN_FASTRECOVERY(tp)) {
4585 if (CC_ALGO(tp)->ack_rcvd != NULL)
4586 CC_ALGO(tp)->ack_rcvd(tp, th);
fe8ab488 4587 tcp_ccdbg_trace(tp, th, TCP_CC_ACK_RCVD);
1c79356b
A
4588 }
4589 if (acked > so->so_snd.sb_cc) {
4590 tp->snd_wnd -= so->so_snd.sb_cc;
4591 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
39236c6e 4592 if (so->so_flags & SOF_ENABLE_MSGS) {
39037602 4593 so->so_msg_state->msg_serial_bytes -=
39236c6e
A
4594 (int)so->so_snd.sb_cc;
4595 }
1c79356b
A
4596 ourfinisacked = 1;
4597 } else {
4598 sbdrop(&so->so_snd, acked);
39236c6e 4599 if (so->so_flags & SOF_ENABLE_MSGS) {
39037602 4600 so->so_msg_state->msg_serial_bytes -=
39236c6e
A
4601 acked;
4602 }
316670eb 4603 tcp_sbsnd_trim(&so->so_snd);
1c79356b
A
4604 tp->snd_wnd -= acked;
4605 ourfinisacked = 0;
4606 }
91447636 4607 /* detect una wraparound */
6d2010ae 4608 if ( !IN_FASTRECOVERY(tp) &&
8ad349bb
A
4609 SEQ_GT(tp->snd_una, tp->snd_recover) &&
4610 SEQ_LEQ(th->th_ack, tp->snd_recover))
4611 tp->snd_recover = th->th_ack - 1;
6d2010ae
A
4612
4613 if (IN_FASTRECOVERY(tp) &&
8ad349bb
A
4614 SEQ_GEQ(th->th_ack, tp->snd_recover))
4615 EXIT_FASTRECOVERY(tp);
6d2010ae 4616
1c79356b 4617 tp->snd_una = th->th_ack;
39037602 4618
39236c6e 4619 if (SACK_ENABLED(tp)) {
8ad349bb
A
4620 if (SEQ_GT(tp->snd_una, tp->snd_recover))
4621 tp->snd_recover = tp->snd_una;
4622 }
1c79356b
A
4623 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
4624 tp->snd_nxt = tp->snd_una;
3e170ce0
A
4625 if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
4626 !TCP_DSACK_SEQ_IN_WINDOW(tp, tp->t_dsack_lastuna,
4627 tp->snd_una))
4628 tcp_rxtseg_clean(tp);
316670eb
A
4629 if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
4630 tp->t_bwmeas != NULL)
4631 tcp_bwmeas_check(tp);
4632
4a3eedf9 4633 /*
39037602
A
4634 * sowwakeup must happen after snd_una, et al. are
4635 * updated so that the sequence numbers are in sync with
4636 * so_snd
4a3eedf9
A
4637 */
4638 sowwakeup(so);
1c79356b 4639
39037602
A
4640 if (!SLIST_EMPTY(&tp->t_notify_ack))
4641 tcp_notify_acknowledgement(tp, so);
4642
1c79356b
A
4643 switch (tp->t_state) {
4644
4645 /*
4646 * In FIN_WAIT_1 STATE in addition to the processing
4647 * for the ESTABLISHED state if our FIN is now acknowledged
4648 * then enter FIN_WAIT_2.
4649 */
4650 case TCPS_FIN_WAIT_1:
4651 if (ourfinisacked) {
4652 /*
4653 * If we can't receive any more
4654 * data, then closing user can proceed.
39236c6e 4655 * Starting the TCPT_2MSL timer is contrary to the
1c79356b
A
4656 * specification, but if we don't get a FIN
4657 * we'll hang forever.
4658 */
4659 if (so->so_state & SS_CANTRCVMORE) {
39236c6e
A
4660 tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp,
4661 TCP_CONN_MAXIDLE(tp));
6d2010ae
A
4662 isconnected = FALSE;
4663 isdisconnected = TRUE;
1c79356b 4664 }
39037602 4665 DTRACE_TCP4(state__change, void, NULL,
39236c6e 4666 struct inpcb *, inp,
39037602 4667 struct tcpcb *, tp,
39236c6e 4668 int32_t, TCPS_FIN_WAIT_2);
1c79356b 4669 tp->t_state = TCPS_FIN_WAIT_2;
39037602
A
4670 /* fall through and make sure we also recognize
4671 * data ACKed with the FIN
39236c6e 4672 */
1c79356b
A
4673 }
4674 break;
4675
4676 /*
4677 * In CLOSING STATE in addition to the processing for
4678 * the ESTABLISHED state if the ACK acknowledges our FIN
4679 * then enter the TIME-WAIT state, otherwise ignore
4680 * the segment.
4681 */
4682 case TCPS_CLOSING:
4683 if (ourfinisacked) {
39037602 4684 DTRACE_TCP4(state__change, void, NULL,
39236c6e 4685 struct inpcb *, inp,
39037602 4686 struct tcpcb *, tp,
39236c6e 4687 int32_t, TCPS_TIME_WAIT);
1c79356b
A
4688 tp->t_state = TCPS_TIME_WAIT;
4689 tcp_canceltimers(tp);
fe8ab488
A
4690 if (tp->t_flagsext & TF_NOTIMEWAIT) {
4691 tp->t_flags |= TF_CLOSING;
4692 } else {
4693 add_to_time_wait(tp, 2 * tcp_msl);
4694 }
6d2010ae
A
4695 isconnected = FALSE;
4696 isdisconnected = TRUE;
1c79356b
A
4697 }
4698 break;
4699
4700 /*
4701 * In LAST_ACK, we may still be waiting for data to drain
4702 * and/or to be acked, as well as for the ack of our FIN.
4703 * If our FIN is now acknowledged, delete the TCB,
4704 * enter the closed state and return.
4705 */
4706 case TCPS_LAST_ACK:
4707 if (ourfinisacked) {
4708 tp = tcp_close(tp);
4709 goto drop;
4710 }
4711 break;
4712
4713 /*
4714 * In TIME_WAIT state the only thing that should arrive
4715 * is a retransmission of the remote FIN. Acknowledge
4716 * it and restart the finack timer.
4717 */
4718 case TCPS_TIME_WAIT:
6d2010ae 4719 add_to_time_wait(tp, 2 * tcp_msl);
1c79356b
A
4720 goto dropafterack;
4721 }
39236c6e
A
4722
4723 /*
39037602 4724 * If there is a SACK option on the ACK and we
39236c6e
A
4725 * haven't seen any duplicate acks before, count
4726 * it as a duplicate ack even if the cumulative
4727 * ack is advanced. If the receiver delayed an
4728 * ack and detected loss afterwards, then the ack
39037602 4729 * will advance cumulative ack and will also have
39236c6e
A
4730 * a SACK option. So counting it as one duplicate
4731 * ack is ok.
39037602 4732 */
39236c6e 4733 if (sack_ackadv == 1 &&
39037602
A
4734 tp->t_state == TCPS_ESTABLISHED &&
4735 SACK_ENABLED(tp) && sack_bytes_acked > 0 &&
fe8ab488
A
4736 to.to_nsacks > 0 && tp->t_dupacks == 0 &&
4737 SEQ_LEQ(th->th_ack, tp->snd_una) && tlen == 0 &&
4738 !(tp->t_flagsext & TF_PKTS_REORDERED)) {
39236c6e
A
4739 tcpstat.tcps_sack_ackadv++;
4740 goto process_dupack;
4741 }
1c79356b
A
4742 }
4743
4744step6:
4745 /*
4746 * Update window information.
1c79356b 4747 */
39037602 4748 if (tcp_update_window(tp, thflags, th, tiwin, tlen))
1c79356b 4749 needoutput = 1;
1c79356b
A
4750
4751 /*
4752 * Process segments with URG.
4753 */
4754 if ((thflags & TH_URG) && th->th_urp &&
4755 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4756 /*
4757 * This is a kludge, but if we receive and accept
4758 * random urgent pointers, we'll crash in
4759 * soreceive. It's hard to imagine someone
4760 * actually wanting to send this much urgent data.
4761 */
4762 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
4763 th->th_urp = 0; /* XXX */
4764 thflags &= ~TH_URG; /* XXX */
4765 goto dodata; /* XXX */
4766 }
4767 /*
4768 * If this segment advances the known urgent pointer,
4769 * then mark the data stream. This should not happen
4770 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
4771 * a FIN has been received from the remote side.
4772 * In these states we ignore the URG.
4773 *
4774 * According to RFC961 (Assigned Protocols),
4775 * the urgent pointer points to the last octet
4776 * of urgent data. We continue, however,
4777 * to consider it to indicate the first octet
4778 * of data past the urgent section as the original
4779 * spec states (in one of two places).
4780 */
4781 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
4782 tp->rcv_up = th->th_seq + th->th_urp;
4783 so->so_oobmark = so->so_rcv.sb_cc +
4784 (tp->rcv_up - tp->rcv_nxt) - 1;
4785 if (so->so_oobmark == 0) {
4786 so->so_state |= SS_RCVATMARK;
4787 postevent(so, 0, EV_OOB);
4788 }
4789 sohasoutofband(so);
4790 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
4791 }
4792 /*
4793 * Remove out of band data so doesn't get presented to user.
4794 * This can happen independent of advancing the URG pointer,
4795 * but if two URG's are pending at once, some out-of-band
4796 * data may creep in... ick.
4797 */
b0d623f7 4798 if (th->th_urp <= (u_int32_t)tlen
1c79356b
A
4799#if SO_OOBINLINE
4800 && (so->so_options & SO_OOBINLINE) == 0
4801#endif
4802 )
9bccf70c
A
4803 tcp_pulloutofband(so, th, m,
4804 drop_hdrlen); /* hdr drop is delayed */
6d2010ae 4805 } else {
1c79356b
A
4806 /*
4807 * If no out of band data is expected,
4808 * pull receive urgent pointer along
4809 * with the receive window.
4810 */
4811 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
4812 tp->rcv_up = tp->rcv_nxt;
6d2010ae
A
4813 }
4814dodata:
1c79356b 4815
6d2010ae
A
4816 /* Set socket's connect or disconnect state correcly before doing data.
4817 * The following might unlock the socket if there is an upcall or a socket
4818 * filter.
4819 */
4820 if (isconnected) {
4821 soisconnected(so);
4822 } else if (isdisconnected) {
4823 soisdisconnected(so);
4824 }
4825
39037602 4826 /* Let's check the state of pcb just to make sure that it did not get closed
6d2010ae
A
4827 * when we unlocked above
4828 */
4829 if (inp->inp_state == INPCB_STATE_DEAD) {
4830 /* Just drop the packet that we are processing and return */
4831 goto drop;
4832 }
39037602 4833
1c79356b
A
4834 /*
4835 * Process the segment text, merging it into the TCP sequencing queue,
4836 * and arranging for acknowledgment of receipt if necessary.
4837 * This process logically involves adjusting tp->rcv_wnd as data
4838 * is presented to the user (this happens in tcp_usrreq.c,
4839 * case PRU_RCVD). If a FIN has already been received on this
4840 * connection then we just ignore the text.
3e170ce0
A
4841 *
4842 * If we are in SYN-received state and got a valid TFO cookie, we want
4843 * to process the data.
1c79356b 4844 */
c910b4d9 4845 if ((tlen || (thflags & TH_FIN)) &&
3e170ce0
A
4846 TCPS_HAVERCVDFIN(tp->t_state) == 0 &&
4847 (TCPS_HAVEESTABLISHED(tp->t_state) ||
4848 (tp->t_state == TCPS_SYN_RECEIVED &&
4849 (tp->t_tfo_flags & TFO_F_COOKIE_VALID)))) {
8ad349bb
A
4850 tcp_seq save_start = th->th_seq;
4851 tcp_seq save_end = th->th_seq + tlen;
9bccf70c
A
4852 m_adj(m, drop_hdrlen); /* delayed header drop */
4853 /*
8ad349bb
A
4854 * Insert segment which includes th into TCP reassembly queue
4855 * with control block tp. Set thflags to whether reassembly now
4856 * includes a segment with FIN. This handles the common case
4857 * inline (segment is the next to be received on an established
4858 * connection, and the queue is empty), avoiding linkage into
4859 * and removal from the queue and repetition of various
4860 * conversions.
4861 * Set DELACK for segments received in order, but ack
4862 * immediately when segments are out of order (so
4863 * fast retransmit can work).
9bccf70c 4864 */
3e170ce0 4865 if (th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
316670eb 4866 TCP_INC_VAR(tp->t_unacksegs, nlropkts);
39236c6e 4867 /*
39037602
A
4868 * Calculate the RTT on the receiver only if the
4869 * connection is in streaming mode and the last
39236c6e
A
4870 * packet was not an end-of-write
4871 */
39037602 4872 if (tp->t_flags & TF_STREAMING_ON)
39236c6e 4873 tcp_compute_rtt(tp, &to, th);
39037602
A
4874
4875 if (DELAY_ACK(tp, th) &&
316670eb 4876 ((tp->t_flags & TF_ACKNOW) == 0) ) {
6d2010ae
A
4877 if ((tp->t_flags & TF_DELACK) == 0) {
4878 tp->t_flags |= TF_DELACK;
39037602 4879 tp->t_timer[TCPT_DELACK] =
39236c6e 4880 OFFSET_FROM_START(tp, tcp_delack);
6d2010ae 4881 }
39037602 4882 }
91447636 4883 else {
9bccf70c 4884 tp->t_flags |= TF_ACKNOW;
91447636 4885 }
9bccf70c
A
4886 tp->rcv_nxt += tlen;
4887 thflags = th->th_flags & TH_FIN;
316670eb 4888 TCP_INC_VAR(tcpstat.tcps_rcvpack, nlropkts);
9bccf70c 4889 tcpstat.tcps_rcvbyte += tlen;
6d2010ae 4890 if (nstat_collect) {
39236c6e 4891 if (m->m_pkthdr.pkt_flags & PKTF_SW_LRO_PKT) {
39037602 4892 INP_ADD_STAT(inp, cell, wifi, wired,
fe8ab488 4893 rxpackets, m->m_pkthdr.lro_npkts);
39236c6e 4894 } else {
fe8ab488
A
4895 INP_ADD_STAT(inp, cell, wifi, wired,
4896 rxpackets, 1);
316670eb 4897 }
fe8ab488
A
4898 INP_ADD_STAT(inp, cell, wifi, wired,
4899 rxbytes, tlen);
5ba3f43e 4900 inp_set_activity_bitmap(inp);
6d2010ae 4901 }
39037602
A
4902 tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen,
4903 TCP_AUTORCVBUF_MAX(ifp));
6d2010ae 4904 so_recv_data_stat(so, m, drop_hdrlen);
39037602 4905
39236c6e
A
4906 if (sbappendstream_rcvdemux(so, m,
4907 th->th_seq - (tp->irs + 1), 0)) {
91447636 4908 sorwakeup(so);
39236c6e 4909 }
9bccf70c 4910 } else {
39236c6e 4911 thflags = tcp_reass(tp, th, &tlen, m, ifp);
9bccf70c
A
4912 tp->t_flags |= TF_ACKNOW;
4913 }
1c79356b 4914
39037602
A
4915 if ((tlen > 0 || (th->th_flags & TH_FIN)) && SACK_ENABLED(tp)) {
4916 if (th->th_flags & TH_FIN)
4917 save_end++;
8ad349bb 4918 tcp_update_sack_list(tp, save_start, save_end);
39037602 4919 }
8ad349bb 4920
39236c6e
A
4921 tcp_adaptive_rwtimo_check(tp, tlen);
4922
3e170ce0
A
4923 if (tlen > 0)
4924 tcp_tfo_rcv_data(tp);
4925
39037602 4926 if (tp->t_flags & TF_DELACK)
1c79356b 4927 {
9bccf70c
A
4928#if INET6
4929 if (isipv6) {
4930 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
4931 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
39037602 4932 th->th_seq, th->th_ack, th->th_win);
9bccf70c
A
4933 }
4934 else
4935#endif
4936 {
4937 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
4938 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
39037602 4939 th->th_seq, th->th_ack, th->th_win);
9bccf70c 4940 }
39037602 4941
1c79356b 4942 }
1c79356b 4943 } else {
5c9f4661
A
4944 if ((so->so_flags & SOF_MP_SUBFLOW) && tlen == 0 &&
4945 (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN)) {
4946 m_adj(m, drop_hdrlen); /* delayed header drop */
4947 mptcp_input(tptomptp(tp)->mpt_mpte, m);
4948 tp->t_flags |= TF_ACKNOW;
4949 } else {
4950 m_freem(m);
4951 }
1c79356b
A
4952 thflags &= ~TH_FIN;
4953 }
4954
4955 /*
4956 * If FIN is received ACK the FIN and let the user know
4957 * that the connection is closing.
4958 */
4959 if (thflags & TH_FIN) {
4960 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
4961 socantrcvmore(so);
4962 postevent(so, 0, EV_FIN);
4963 /*
8ad349bb
A
4964 * If connection is half-synchronized
4965 * (ie NEEDSYN flag on) then delay ACK,
4966 * so it may be piggybacked when SYN is sent.
4967 * Otherwise, since we received a FIN then no
4968 * more input can be expected, send ACK now.
1c79356b 4969 */
316670eb 4970 TCP_INC_VAR(tp->t_unacksegs, nlropkts);
6d2010ae
A
4971 if (DELAY_ACK(tp, th) && (tp->t_flags & TF_NEEDSYN)) {
4972 if ((tp->t_flags & TF_DELACK) == 0) {
4973 tp->t_flags |= TF_DELACK;
4974 tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
4975 }
4bd07ac2 4976 } else {
1c79356b 4977 tp->t_flags |= TF_ACKNOW;
91447636 4978 }
1c79356b
A
4979 tp->rcv_nxt++;
4980 }
4981 switch (tp->t_state) {
4982
4983 /*
4984 * In SYN_RECEIVED and ESTABLISHED STATES
4985 * enter the CLOSE_WAIT state.
4986 */
4987 case TCPS_SYN_RECEIVED:
6d2010ae 4988 tp->t_starttime = tcp_now;
1c79356b 4989 case TCPS_ESTABLISHED:
6d2010ae
A
4990 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
4991 struct tcpcb *, tp, int32_t, TCPS_CLOSE_WAIT);
1c79356b
A
4992 tp->t_state = TCPS_CLOSE_WAIT;
4993 break;
4994
4995 /*
4996 * If still in FIN_WAIT_1 STATE FIN has not been acked so
4997 * enter the CLOSING state.
4998 */
4999 case TCPS_FIN_WAIT_1:
6d2010ae
A
5000 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5001 struct tcpcb *, tp, int32_t, TCPS_CLOSING);
1c79356b
A
5002 tp->t_state = TCPS_CLOSING;
5003 break;
5004
5005 /*
5006 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5007 * starting the time-wait timer, turning off the other
5008 * standard timers.
5009 */
5010 case TCPS_FIN_WAIT_2:
39037602 5011 DTRACE_TCP4(state__change, void, NULL,
39236c6e 5012 struct inpcb *, inp,
39037602 5013 struct tcpcb *, tp,
39236c6e 5014 int32_t, TCPS_TIME_WAIT);
1c79356b
A
5015 tp->t_state = TCPS_TIME_WAIT;
5016 tcp_canceltimers(tp);
fe8ab488
A
5017 tp->t_flags |= TF_ACKNOW;
5018 if (tp->t_flagsext & TF_NOTIMEWAIT) {
5019 tp->t_flags |= TF_CLOSING;
5020 } else {
5021 add_to_time_wait(tp, 2 * tcp_msl);
1c79356b 5022 }
1c79356b
A
5023 soisdisconnected(so);
5024 break;
5025
5026 /*
5027 * In TIME_WAIT state restart the 2 MSL time_wait timer.
5028 */
5029 case TCPS_TIME_WAIT:
6d2010ae 5030 add_to_time_wait(tp, 2 * tcp_msl);
1c79356b
A
5031 break;
5032 }
5033 }
5034#if TCPDEBUG
9bccf70c
A
5035 if (so->so_options & SO_DEBUG)
5036 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
1c79356b 5037 &tcp_savetcp, 0);
1c79356b
A
5038#endif
5039
5040 /*
5041 * Return any desired output.
5042 */
2d21ac55 5043 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
1c79356b 5044 (void) tcp_output(tp);
2d21ac55 5045 }
6d2010ae
A
5046
5047 tcp_check_timer_state(tp);
5048
39037602 5049
5ba3f43e 5050 socket_unlock(so, 1);
1c79356b
A
5051 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
5052 return;
5053
5054dropafterack:
5055 /*
5056 * Generate an ACK dropping incoming segment if it occupies
5057 * sequence space, where the ACK reflects our state.
5058 *
5059 * We can now skip the test for the RST flag since all
5060 * paths to this code happen after packets containing
5061 * RST have been dropped.
5062 *
5063 * In the SYN-RECEIVED state, don't send an ACK unless the
5064 * segment we received passes the SYN-RECEIVED ACK test.
5065 * If it fails send a RST. This breaks the loop in the
5066 * "LAND" DoS attack, and also prevents an ACK storm
5067 * between two listening ports that have been sent forged
5068 * SYN segments, each with the source address of the other.
5069 */
5070 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
5071 (SEQ_GT(tp->snd_una, th->th_ack) ||
9bccf70c
A
5072 SEQ_GT(th->th_ack, tp->snd_max)) ) {
5073 rstreason = BANDLIM_RST_OPENPORT;
39236c6e 5074 IF_TCP_STATINC(ifp, dospacket);
1c79356b 5075 goto dropwithreset;
9bccf70c 5076 }
1c79356b 5077#if TCPDEBUG
9bccf70c
A
5078 if (so->so_options & SO_DEBUG)
5079 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
1c79356b 5080 &tcp_savetcp, 0);
1c79356b
A
5081#endif
5082 m_freem(m);
5083 tp->t_flags |= TF_ACKNOW;
5084 (void) tcp_output(tp);
6d2010ae
A
5085
5086 /* Don't need to check timer state as we should have done it during tcp_output */
5ba3f43e 5087 socket_unlock(so, 1);
1c79356b
A
5088 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
5089 return;
91447636
A
5090dropwithresetnosock:
5091 nosock = 1;
1c79356b
A
5092dropwithreset:
5093 /*
5094 * Generate a RST, dropping incoming segment.
5095 * Make ACK acceptable to originator of segment.
5096 * Don't bother to respond if destination was broadcast/multicast.
5097 */
5098 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
5099 goto drop;
5100#if INET6
5101 if (isipv6) {
9bccf70c
A
5102 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
5103 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
5104 goto drop;
1c79356b
A
5105 } else
5106#endif /* INET6 */
14353aa8
A
5107 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
5108 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
5109 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
5110 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1c79356b 5111 goto drop;
9bccf70c
A
5112 /* IPv6 anycast check is done at tcp6_input() */
5113
39037602 5114 /*
9bccf70c
A
5115 * Perform bandwidth limiting.
5116 */
5117#if ICMP_BANDLIM
5118 if (badport_bandlim(rstreason) < 0)
5119 goto drop;
5120#endif
5121
1c79356b 5122#if TCPDEBUG
9bccf70c
A
5123 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
5124 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
1c79356b 5125 &tcp_savetcp, 0);
1c79356b 5126#endif
fe8ab488
A
5127 bzero(&tra, sizeof(tra));
5128 tra.ifscope = ifscope;
5129 tra.awdl_unrestricted = 1;
39037602 5130 tra.intcoproc_allowed = 1;
1c79356b 5131 if (thflags & TH_ACK)
9bccf70c
A
5132 /* mtod() below is safe as long as hdr dropping is delayed */
5133 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
fe8ab488 5134 TH_RST, &tra);
1c79356b
A
5135 else {
5136 if (thflags & TH_SYN)
9bccf70c
A
5137 tlen++;
5138 /* mtod() below is safe as long as hdr dropping is delayed */
5139 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
fe8ab488 5140 (tcp_seq)0, TH_RST|TH_ACK, &tra);
1c79356b
A
5141 }
5142 /* destroy temporarily created socket */
91447636 5143 if (dropsocket) {
39037602 5144 (void) soabort(so);
5ba3f43e 5145 socket_unlock(so, 1);
39236c6e 5146 } else if ((inp != NULL) && (nosock == 0)) {
5ba3f43e 5147 socket_unlock(so, 1);
6d2010ae 5148 }
1c79356b
A
5149 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
5150 return;
91447636
A
5151dropnosock:
5152 nosock = 1;
1c79356b
A
5153drop:
5154 /*
5155 * Drop space held by incoming segment and return.
5156 */
5157#if TCPDEBUG
9bccf70c
A
5158 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
5159 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
1c79356b 5160 &tcp_savetcp, 0);
1c79356b
A
5161#endif
5162 m_freem(m);
1c79356b 5163 /* destroy temporarily created socket */
91447636 5164 if (dropsocket) {
39037602 5165 (void) soabort(so);
5ba3f43e 5166 socket_unlock(so, 1);
91447636 5167 }
6d2010ae 5168 else if (nosock == 0) {
5ba3f43e 5169 socket_unlock(so, 1);
6d2010ae 5170 }
1c79356b
A
5171 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
5172 return;
5173}
5174
8ad349bb
A
5175/*
5176 * Parse TCP options and place in tcpopt.
5177 */
3e170ce0
A
5178static void
5179tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
5180 struct tcpopt *to)
1c79356b
A
5181{
5182 u_short mss = 0;
5183 int opt, optlen;
5184
5185 for (; cnt > 0; cnt -= optlen, cp += optlen) {
5186 opt = cp[0];
5187 if (opt == TCPOPT_EOL)
5188 break;
5189 if (opt == TCPOPT_NOP)
5190 optlen = 1;
5191 else {
9bccf70c
A
5192 if (cnt < 2)
5193 break;
1c79356b 5194 optlen = cp[1];
9bccf70c 5195 if (optlen < 2 || optlen > cnt)
1c79356b
A
5196 break;
5197 }
5198 switch (opt) {
5199
5200 default:
5201 continue;
5202
5203 case TCPOPT_MAXSEG:
5204 if (optlen != TCPOLEN_MAXSEG)
5205 continue;
5206 if (!(th->th_flags & TH_SYN))
5207 continue;
5208 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
9bccf70c 5209 NTOHS(mss);
3e170ce0
A
5210 to->to_mss = mss;
5211 to->to_flags |= TOF_MSS;
1c79356b
A
5212 break;
5213
5214 case TCPOPT_WINDOW:
5215 if (optlen != TCPOLEN_WINDOW)
5216 continue;
5217 if (!(th->th_flags & TH_SYN))
5218 continue;
39236c6e 5219 to->to_flags |= TOF_SCALE;
3e170ce0 5220 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1c79356b
A
5221 break;
5222
5223 case TCPOPT_TIMESTAMP:
5224 if (optlen != TCPOLEN_TIMESTAMP)
5225 continue;
8ad349bb 5226 to->to_flags |= TOF_TS;
1c79356b
A
5227 bcopy((char *)cp + 2,
5228 (char *)&to->to_tsval, sizeof(to->to_tsval));
5229 NTOHL(to->to_tsval);
5230 bcopy((char *)cp + 6,
5231 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
5232 NTOHL(to->to_tsecr);
3e170ce0
A
5233 /* Re-enable sending Timestamps if we received them */
5234 if (!(tp->t_flags & TF_REQ_TSTMP) &&
5235 tcp_do_rfc1323 == 1)
5236 tp->t_flags |= TF_REQ_TSTMP;
1c79356b 5237 break;
8ad349bb
A
5238 case TCPOPT_SACK_PERMITTED:
5239 if (!tcp_do_sack ||
5240 optlen != TCPOLEN_SACK_PERMITTED)
1c79356b 5241 continue;
1c79356b 5242 if (th->th_flags & TH_SYN)
8ad349bb 5243 to->to_flags |= TOF_SACK;
1c79356b 5244 break;
8ad349bb
A
5245 case TCPOPT_SACK:
5246 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
1c79356b 5247 continue;
8ad349bb
A
5248 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
5249 to->to_sacks = cp + 2;
5250 tcpstat.tcps_sack_rcv_blocks++;
5251
1c79356b 5252 break;
3e170ce0
A
5253 case TCPOPT_FASTOPEN:
5254 if (optlen == TCPOLEN_FASTOPEN_REQ) {
5255 if (tp->t_state != TCPS_LISTEN)
5256 continue;
5257
5258 to->to_flags |= TOF_TFOREQ;
5259 } else {
5260 if (optlen < TCPOLEN_FASTOPEN_REQ ||
5261 (optlen - TCPOLEN_FASTOPEN_REQ) > TFO_COOKIE_LEN_MAX ||
5262 (optlen - TCPOLEN_FASTOPEN_REQ) < TFO_COOKIE_LEN_MIN)
5263 continue;
5264 if (tp->t_state != TCPS_LISTEN &&
5265 tp->t_state != TCPS_SYN_SENT)
5266 continue;
5267
5268 to->to_flags |= TOF_TFO;
5269 to->to_tfo = cp + 1;
5270 }
5271
5272 break;
39236c6e
A
5273#if MPTCP
5274 case TCPOPT_MULTIPATH:
5275 tcp_do_mptcp_options(tp, cp, th, to, optlen);
5276 break;
5277#endif /* MPTCP */
1c79356b
A
5278 }
5279 }
3e170ce0
A
5280}
5281
5282static void
5283tcp_finalize_options(struct tcpcb *tp, struct tcpopt *to, unsigned int ifscope)
5284{
5285 if (to->to_flags & TOF_TS) {
5286 tp->t_flags |= TF_RCVD_TSTMP;
5287 tp->ts_recent = to->to_tsval;
5288 tp->ts_recent_age = tcp_now;
5289
5290 }
5291 if (to->to_flags & TOF_MSS)
5292 tcp_mss(tp, to->to_mss, ifscope);
5293 if (SACK_ENABLED(tp)) {
5294 if (!(to->to_flags & TOF_SACK))
5295 tp->t_flagsext &= ~(TF_SACK_ENABLE);
5296 else
5297 tp->t_flags |= TF_SACK_PERMIT;
5298 }
5299 if (to->to_flags & TOF_SCALE) {
5300 tp->t_flags |= TF_RCVD_SCALE;
5301 tp->requested_s_scale = to->to_requested_s_scale;
5302
5303 /* Re-enable window scaling, if the option is received */
5304 if (tp->request_r_scale > 0)
5305 tp->t_flags |= TF_REQ_SCALE;
5306 }
1c79356b
A
5307}
5308
5309/*
5310 * Pull out of band byte out of a segment so
5311 * it doesn't appear in the user's data queue.
5312 * It is still reflected in the segment length for
5313 * sequencing purposes.
39037602
A
5314 *
5315 * @param off delayed to be droped hdrlen
1c79356b
A
5316 */
5317static void
39037602 5318tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
1c79356b 5319{
9bccf70c 5320 int cnt = off + th->th_urp - 1;
1c79356b
A
5321
5322 while (cnt >= 0) {
5323 if (m->m_len > cnt) {
5324 char *cp = mtod(m, caddr_t) + cnt;
5325 struct tcpcb *tp = sototcpcb(so);
5326
5327 tp->t_iobc = *cp;
5328 tp->t_oobflags |= TCPOOB_HAVEDATA;
5329 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
5330 m->m_len--;
9bccf70c
A
5331 if (m->m_flags & M_PKTHDR)
5332 m->m_pkthdr.len--;
1c79356b
A
5333 return;
5334 }
5335 cnt -= m->m_len;
5336 m = m->m_next;
5337 if (m == 0)
5338 break;
5339 }
5340 panic("tcp_pulloutofband");
5341}
5342
6d2010ae 5343uint32_t
39037602 5344get_base_rtt(struct tcpcb *tp)
6d2010ae 5345{
ecc0ceb4 5346 struct rtentry *rt = tp->t_inpcb->inp_route.ro_rt;
39037602 5347 return ((rt == NULL) ? 0 : rt->rtt_min);
6d2010ae
A
5348}
5349
5350/* Each value of RTT base represents the minimum RTT seen in a minute.
5351 * We keep upto N_RTT_BASE minutes worth of history.
5352 */
5353void
5354update_base_rtt(struct tcpcb *tp, uint32_t rtt)
5355{
39037602 5356 u_int32_t base_rtt, i;
ecc0ceb4 5357 struct rtentry *rt;
39236c6e 5358
ecc0ceb4
A
5359 if ((rt = tp->t_inpcb->inp_route.ro_rt) == NULL)
5360 return;
5361 if (rt->rtt_expire_ts == 0) {
5362 RT_LOCK_SPIN(rt);
ecc0ceb4
A
5363 if (rt->rtt_expire_ts != 0) {
5364 RT_UNLOCK(rt);
5365 goto update;
5366 }
5367 rt->rtt_expire_ts = tcp_now;
5368 rt->rtt_index = 0;
5369 rt->rtt_hist[0] = rtt;
39037602 5370 rt->rtt_min = rtt;
ecc0ceb4
A
5371 RT_UNLOCK(rt);
5372 return;
5373 }
5374update:
39236c6e 5375#if TRAFFIC_MGT
ecc0ceb4
A
5376 /*
5377 * If the recv side is being throttled, check if the
5378 * current RTT is closer to the base RTT seen in
5379 * first (recent) two slots. If so, unthrottle the stream.
5380 */
5381 if ((tp->t_flagsext & TF_RECV_THROTTLE) &&
5382 (int)(tcp_now - tp->t_recv_throttle_ts) >= TCP_RECV_THROTTLE_WIN) {
39037602 5383 base_rtt = rt->rtt_min;
ecc0ceb4
A
5384 if (tp->t_rttcur <= (base_rtt + target_qdelay)) {
5385 tp->t_flagsext &= ~TF_RECV_THROTTLE;
5386 tp->t_recv_throttle_ts = 0;
39236c6e 5387 }
ecc0ceb4 5388 }
39236c6e 5389#endif /* TRAFFIC_MGT */
ecc0ceb4
A
5390 if ((int)(tcp_now - rt->rtt_expire_ts) >=
5391 TCP_RTT_HISTORY_EXPIRE_TIME) {
5392 RT_LOCK_SPIN(rt);
5393 /* check the condition again to avoid race */
5394 if ((int)(tcp_now - rt->rtt_expire_ts) >=
5395 TCP_RTT_HISTORY_EXPIRE_TIME) {
5396 rt->rtt_index++;
5397 if (rt->rtt_index >= NRTT_HIST)
5398 rt->rtt_index = 0;
5399 rt->rtt_hist[rt->rtt_index] = rtt;
5400 rt->rtt_expire_ts = tcp_now;
5401 } else {
5402 rt->rtt_hist[rt->rtt_index] =
5403 min(rt->rtt_hist[rt->rtt_index], rtt);
6d2010ae 5404 }
39037602
A
5405 /* forget the old value and update minimum */
5406 rt->rtt_min = 0;
5407 for (i = 0; i < NRTT_HIST; ++i) {
5408 if (rt->rtt_hist[i] != 0 &&
5409 (rt->rtt_min == 0 ||
5410 rt->rtt_hist[i] < rt->rtt_min))
5411 rt->rtt_min = rt->rtt_hist[i];
5412 }
ecc0ceb4 5413 RT_UNLOCK(rt);
6d2010ae 5414 } else {
ecc0ceb4
A
5415 rt->rtt_hist[rt->rtt_index] =
5416 min(rt->rtt_hist[rt->rtt_index], rtt);
39037602
A
5417 if (rt->rtt_min == 0)
5418 rt->rtt_min = rtt;
5419 else
5420 rt->rtt_min = min(rt->rtt_min, rtt);
6d2010ae
A
5421 }
5422}
5423
39236c6e
A
5424/*
5425 * If we have a timestamp reply, update smoothed RTT. If no timestamp is
39037602
A
5426 * present but transmit timer is running and timed sequence number was
5427 * acked, update smoothed RTT.
39236c6e
A
5428 *
5429 * If timestamps are supported, a receiver can update RTT even if
5430 * there is no outstanding data.
5431 *
5432 * Some boxes send broken timestamp replies during the SYN+ACK phase,
39037602 5433 * ignore timestamps of 0or we could calculate a huge RTT and blow up
39236c6e
A
5434 * the retransmit timer.
5435 */
5436static void
5437tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
5438{
3e170ce0 5439 int rtt = 0;
39236c6e 5440 VERIFY(to != NULL && th != NULL);
3e170ce0
A
5441 if (tp->t_rtttime != 0 && SEQ_GT(th->th_ack, tp->t_rtseq)) {
5442 u_int32_t pipe_ack_val;
5443 rtt = tcp_now - tp->t_rtttime;
5444 /*
5445 * Compute pipe ack -- the amount of data acknowledged
5446 * in the last RTT
5447 */
5448 if (SEQ_GT(th->th_ack, tp->t_pipeack_lastuna)) {
5449 pipe_ack_val = th->th_ack - tp->t_pipeack_lastuna;
5450 /* Update the sample */
5451 tp->t_pipeack_sample[tp->t_pipeack_ind++] =
5452 pipe_ack_val;
5453 tp->t_pipeack_ind %= TCP_PIPEACK_SAMPLE_COUNT;
5454
5455 /* Compute the max of the pipeack samples */
5456 pipe_ack_val = tcp_get_max_pipeack(tp);
5457 tp->t_pipeack = (pipe_ack_val >
5458 TCP_CC_CWND_INIT_BYTES) ?
5459 pipe_ack_val : 0;
5460 }
5461 /* start another measurement */
5462 tp->t_rtttime = 0;
5463 }
39037602 5464 if (((to->to_flags & TOF_TS) != 0) &&
39236c6e
A
5465 (to->to_tsecr != 0) &&
5466 TSTMP_GEQ(tcp_now, to->to_tsecr)) {
3e170ce0 5467 tcp_xmit_timer(tp, (tcp_now - to->to_tsecr),
39236c6e 5468 to->to_tsecr, th->th_ack);
3e170ce0
A
5469 } else if (rtt > 0) {
5470 tcp_xmit_timer(tp, rtt, 0, th->th_ack);
39236c6e
A
5471 }
5472}
5473
1c79356b 5474/*
d190cdc3
A
5475 * Collect new round-trip time estimate and update averages and
5476 * current timeout.
1c79356b
A
5477 */
5478static void
39037602 5479tcp_xmit_timer(struct tcpcb *tp, int rtt,
39236c6e 5480 u_int32_t tsecr, tcp_seq th_ack)
1c79356b 5481{
39037602 5482 int delta;
1c79356b 5483
d190cdc3
A
5484 /*
5485 * On AWDL interface, the initial RTT measurement on SYN
5486 * can be wrong due to peer caching. Avoid the first RTT
5487 * measurement as it might skew up the RTO.
5488 * <rdar://problem/28739046>
5489 */
5490 if (tp->t_inpcb->inp_last_outifp != NULL &&
5491 (tp->t_inpcb->inp_last_outifp->if_eflags & IFEF_AWDL) &&
5492 th_ack == tp->iss + 1)
5493 return;
5494
39236c6e
A
5495 if (tp->t_flagsext & TF_RECOMPUTE_RTT) {
5496 if (SEQ_GT(th_ack, tp->snd_una) &&
5497 SEQ_LEQ(th_ack, tp->snd_max) &&
5498 (tsecr == 0 ||
5499 TSTMP_GEQ(tsecr, tp->t_badrexmt_time))) {
5500 /*
5501 * We received a new ACk after a
39037602 5502 * spurious timeout. Adapt retransmission
39236c6e
A
5503 * timer as described in rfc 4015.
5504 */
5505 tp->t_flagsext &= ~(TF_RECOMPUTE_RTT);
5506 tp->t_badrexmt_time = 0;
5507 tp->t_srtt = max(tp->t_srtt_prev, rtt);
5508 tp->t_srtt = tp->t_srtt << TCP_RTT_SHIFT;
5509 tp->t_rttvar = max(tp->t_rttvar_prev, (rtt >> 1));
5510 tp->t_rttvar = tp->t_rttvar << TCP_RTTVAR_SHIFT;
5511
5512 if (tp->t_rttbest > (tp->t_srtt + tp->t_rttvar))
5513 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
5514
5515 goto compute_rto;
5516 } else {
5517 return;
5518 }
5519 }
5520
1c79356b
A
5521 tcpstat.tcps_rttupdated++;
5522 tp->t_rttupdated++;
6d2010ae
A
5523
5524 if (rtt > 0) {
5525 tp->t_rttcur = rtt;
5526 update_base_rtt(tp, rtt);
5527 }
5528
1c79356b
A
5529 if (tp->t_srtt != 0) {
5530 /*
5531 * srtt is stored as fixed point with 5 bits after the
6d2010ae 5532 * binary point (i.e., scaled by 32). The following magic
1c79356b
A
5533 * is equivalent to the smoothing algorithm in rfc793 with
5534 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
6d2010ae
A
5535 * point).
5536 *
39037602
A
5537 * Freebsd adjusts rtt to origin 0 by subtracting 1
5538 * from the provided rtt value. This was required because
5539 * of the way t_rtttime was initiailised to 1 before.
39236c6e 5540 * Since we changed t_rtttime to be based on
6d2010ae 5541 * tcp_now, this extra adjustment is not needed.
1c79356b 5542 */
6d2010ae 5543 delta = (rtt << TCP_DELTA_SHIFT)
1c79356b
A
5544 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
5545
5546 if ((tp->t_srtt += delta) <= 0)
5547 tp->t_srtt = 1;
5548
5549 /*
5550 * We accumulate a smoothed rtt variance (actually, a
5551 * smoothed mean difference), then set the retransmit
5552 * timer to smoothed rtt + 4 times the smoothed variance.
5553 * rttvar is stored as fixed point with 4 bits after the
5554 * binary point (scaled by 16). The following is
5555 * equivalent to rfc793 smoothing with an alpha of .75
5556 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
5557 * rfc793's wired-in beta.
5558 */
5559 if (delta < 0)
5560 delta = -delta;
5561 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
5562 if ((tp->t_rttvar += delta) <= 0)
5563 tp->t_rttvar = 1;
39037602 5564 if (tp->t_rttbest == 0 ||
316670eb
A
5565 tp->t_rttbest > (tp->t_srtt + tp->t_rttvar))
5566 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
1c79356b
A
5567 } else {
5568 /*
5569 * No rtt measurement yet - use the unsmoothed rtt.
5570 * Set the variance to half the rtt (so our first
5571 * retransmit happens at 3*rtt).
5572 */
5573 tp->t_srtt = rtt << TCP_RTT_SHIFT;
5574 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
5575 }
39236c6e
A
5576
5577compute_rto:
39037602 5578 nstat_route_rtt(tp->t_inpcb->inp_route.ro_rt, tp->t_srtt,
39236c6e 5579 tp->t_rttvar);
1c79356b
A
5580
5581 /*
5582 * the retransmit should happen at rtt + 4 * rttvar.
5583 * Because of the way we do the smoothing, srtt and rttvar
5584 * will each average +1/2 tick of bias. When we compute
5585 * the retransmit timer, we want 1/2 tick of rounding and
5586 * 1 extra tick because of +-1/2 tick uncertainty in the
5587 * firing of the timer. The bias will give us exactly the
5588 * 1.5 tick we need. But, because the bias is
5589 * statistical, we have to test that we don't drop below
5590 * the minimum feasible timer (which is 2 ticks).
5591 */
5592 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
39037602 5593 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX,
6d2010ae 5594 TCP_ADD_REXMTSLOP(tp));
1c79356b
A
5595
5596 /*
5597 * We received an ack for a packet that wasn't retransmitted;
5598 * it is probably safe to discard any error indications we've
5599 * received recently. This isn't quite right, but close enough
5600 * for now (a route might have failed after we sent a segment,
5601 * and the return path might not be symmetrical).
5602 */
5603 tp->t_softerror = 0;
5604}
5605
2d21ac55
A
5606static inline unsigned int
5607tcp_maxmtu(struct rtentry *rt)
5608{
5609 unsigned int maxmtu;
5610
b0d623f7 5611 RT_LOCK_ASSERT_HELD(rt);
2d21ac55
A
5612 if (rt->rt_rmx.rmx_mtu == 0)
5613 maxmtu = rt->rt_ifp->if_mtu;
5614 else
5615 maxmtu = MIN(rt->rt_rmx.rmx_mtu, rt->rt_ifp->if_mtu);
5616
5617 return (maxmtu);
5618}
5619
5620#if INET6
5621static inline unsigned int
5622tcp_maxmtu6(struct rtentry *rt)
5623{
5624 unsigned int maxmtu;
3e170ce0 5625 struct nd_ifinfo *ndi = NULL;
2d21ac55 5626
b0d623f7 5627 RT_LOCK_ASSERT_HELD(rt);
316670eb
A
5628 if ((ndi = ND_IFINFO(rt->rt_ifp)) != NULL && !ndi->initialized)
5629 ndi = NULL;
5630 if (ndi != NULL)
5631 lck_mtx_lock(&ndi->lock);
2d21ac55
A
5632 if (rt->rt_rmx.rmx_mtu == 0)
5633 maxmtu = IN6_LINKMTU(rt->rt_ifp);
5634 else
5635 maxmtu = MIN(rt->rt_rmx.rmx_mtu, IN6_LINKMTU(rt->rt_ifp));
316670eb
A
5636 if (ndi != NULL)
5637 lck_mtx_unlock(&ndi->lock);
2d21ac55
A
5638
5639 return (maxmtu);
5640}
5641#endif
5642
5ba3f43e
A
5643unsigned int
5644get_maxmtu(struct rtentry *rt)
5645{
5646 unsigned int maxmtu = 0;
5647
5648 RT_LOCK_ASSERT_NOTHELD(rt);
5649
5650 RT_LOCK(rt);
5651
5652 if (rt_key(rt)->sa_family == AF_INET6) {
5653 maxmtu = tcp_maxmtu6(rt);
5654 } else {
5655 maxmtu = tcp_maxmtu(rt);
5656 }
5657
5658 RT_UNLOCK(rt);
5659
5660 return (maxmtu);
5661}
5662
1c79356b
A
5663/*
5664 * Determine a reasonable value for maxseg size.
5665 * If the route is known, check route for mtu.
5666 * If none, use an mss that can be handled on the outgoing
5667 * interface without forcing IP to fragment; if bigger than
5668 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
5669 * to utilize large mbufs. If no route is found, route has no mtu,
5670 * or the destination isn't local, use a default, hopefully conservative
5671 * size (usually 512 or the default IP max size, but no more than the mtu
5672 * of the interface), as we can't discover anything about intervening
5673 * gateways or networks. We also initialize the congestion/slow start
39037602
A
5674 * window. While looking at the routing entry, we also initialize
5675 * other path-dependent parameters from pre-set or cached values
fe8ab488 5676 * in the routing entry.
1c79356b
A
5677 *
5678 * Also take into account the space needed for options that we
5679 * send regularly. Make maxseg shorter by that amount to assure
5680 * that we can send maxseg amount of data even when the options
5681 * are present. Store the upper limit of the length of options plus
5682 * data in maxopd.
5683 *
5684 * NOTE that this routine is only called when we process an incoming
5685 * segment, for outgoing segments only tcp_mssopt is called.
5686 *
1c79356b
A
5687 */
5688void
39037602 5689tcp_mss(struct tcpcb *tp, int offer, unsigned int input_ifscope)
1c79356b 5690{
ecc0ceb4 5691 struct rtentry *rt;
1c79356b 5692 struct ifnet *ifp;
ecc0ceb4 5693 int rtt, mss;
b0d623f7 5694 u_int32_t bufsize;
1c79356b
A
5695 struct inpcb *inp;
5696 struct socket *so;
5697 struct rmxp_tao *taop;
5698 int origoffer = offer;
b0d623f7 5699 u_int32_t sb_max_corrected;
2d21ac55 5700 int isnetlocal = 0;
1c79356b 5701#if INET6
9bccf70c
A
5702 int isipv6;
5703 int min_protoh;
5704#endif
1c79356b
A
5705
5706 inp = tp->t_inpcb;
9bccf70c
A
5707#if INET6
5708 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
5709 min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
5710 : sizeof (struct tcpiphdr);
5711#else
5712#define min_protoh (sizeof (struct tcpiphdr))
5713#endif
b0d623f7 5714
1c79356b 5715#if INET6
2d21ac55 5716 if (isipv6) {
6d2010ae 5717 rt = tcp_rtlookup6(inp, input_ifscope);
2d21ac55 5718 }
1c79356b
A
5719 else
5720#endif /* INET6 */
2d21ac55 5721 {
c910b4d9 5722 rt = tcp_rtlookup(inp, input_ifscope);
2d21ac55 5723 }
6d2010ae
A
5724 isnetlocal = (tp->t_flags & TF_LOCAL);
5725
1c79356b
A
5726 if (rt == NULL) {
5727 tp->t_maxopd = tp->t_maxseg =
5728#if INET6
5729 isipv6 ? tcp_v6mssdflt :
5730#endif /* INET6 */
5731 tcp_mssdflt;
5732 return;
5733 }
5734 ifp = rt->rt_ifp;
d12e1678
A
5735 /*
5736 * Slower link window correction:
fe8ab488
A
5737 * If a value is specificied for slowlink_wsize use it for
5738 * PPP links believed to be on a serial modem (speed <128Kbps).
5739 * Excludes 9600bps as it is the default value adversized
5740 * by pseudo-devices over ppp.
d12e1678 5741 */
39037602 5742 if (ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
d12e1678
A
5743 ifp->if_baudrate > 9600 && ifp->if_baudrate <= 128000) {
5744 tp->t_flags |= TF_SLOWLINK;
5745 }
1c79356b
A
5746 so = inp->inp_socket;
5747
5748 taop = rmx_taop(rt->rt_rmx);
5749 /*
5750 * Offer == -1 means that we didn't receive SYN yet,
5751 * use cached value in that case;
5752 */
5753 if (offer == -1)
5754 offer = taop->tao_mssopt;
5755 /*
5756 * Offer == 0 means that there was no MSS on the SYN segment,
5757 * in this case we use tcp_mssdflt.
5758 */
5759 if (offer == 0)
5760 offer =
5761#if INET6
5762 isipv6 ? tcp_v6mssdflt :
5763#endif /* INET6 */
5764 tcp_mssdflt;
e5568f75
A
5765 else {
5766 /*
5767 * Prevent DoS attack with too small MSS. Round up
5768 * to at least minmss.
5769 */
5770 offer = max(offer, tcp_minmss);
1c79356b
A
5771 /*
5772 * Sanity check: make sure that maxopd will be large
5773 * enough to allow some data on segments even is the
5774 * all the option space is used (40bytes). Otherwise
5775 * funny things may happen in tcp_output.
5776 */
5777 offer = max(offer, 64);
e5568f75 5778 }
1c79356b
A
5779 taop->tao_mssopt = offer;
5780
5781 /*
5782 * While we're here, check if there's an initial rtt
5783 * or rttvar. Convert from the route-table units
5784 * to scaled multiples of the slow timeout timer.
5785 */
316670eb
A
5786 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt) != 0) {
5787 tcp_getrt_rtt(tp, rt);
5788 } else {
6d2010ae 5789 tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN : TCPTV_REXMTMIN;
316670eb 5790 }
2d21ac55 5791
9bccf70c 5792#if INET6
2d21ac55
A
5793 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
5794#else
5795 mss = tcp_maxmtu(rt);
9bccf70c 5796#endif
3e170ce0
A
5797
5798#if NECP
5799 // At this point, the mss is just the MTU. Adjust if necessary.
5800 mss = necp_socket_get_effective_mtu(inp, mss);
5801#endif /* NECP */
5802
2d21ac55
A
5803 mss -= min_protoh;
5804
5805 if (rt->rt_rmx.rmx_mtu == 0) {
1c79356b
A
5806#if INET6
5807 if (isipv6) {
2d21ac55 5808 if (!isnetlocal)
1c79356b
A
5809 mss = min(mss, tcp_v6mssdflt);
5810 } else
5811#endif /* INET6 */
2d21ac55 5812 if (!isnetlocal)
1c79356b
A
5813 mss = min(mss, tcp_mssdflt);
5814 }
2d21ac55 5815
1c79356b
A
5816 mss = min(mss, offer);
5817 /*
5818 * maxopd stores the maximum length of data AND options
5819 * in a segment; maxseg is the amount of data in a normal
5820 * segment. We need to store this value (maxopd) apart
5821 * from maxseg, because now every segment carries options
5822 * and thus we normally have somewhat less data in segments.
5823 */
5824 tp->t_maxopd = mss;
5825
5826 /*
8ad349bb
A
5827 * origoffer==-1 indicates, that no segments were received yet.
5828 * In this case we just guess.
1c79356b 5829 */
8ad349bb 5830 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1c79356b
A
5831 (origoffer == -1 ||
5832 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
5833 mss -= TCPOLEN_TSTAMP_APPA;
1c79356b 5834
39236c6e
A
5835#if MPTCP
5836 mss -= mptcp_adj_mss(tp, FALSE);
5837#endif /* MPTCP */
5838 tp->t_maxseg = mss;
39037602 5839
2d21ac55
A
5840 /*
5841 * Calculate corrected value for sb_max; ensure to upgrade the
5842 * numerator for large sb_max values else it will overflow.
5843 */
5844 sb_max_corrected = (sb_max * (u_int64_t)MCLBYTES) / (MSIZE + MCLBYTES);
5845
1c79356b 5846 /*
55e303ae
A
5847 * If there's a pipesize (ie loopback), change the socket
5848 * buffer to that size only if it's bigger than the current
5849 * sockbuf size. Make the socket buffers an integral
1c79356b
A
5850 * number of mss units; if the mss is larger than
5851 * the socket buffer, decrease the mss.
5852 */
5853#if RTV_SPIPE
55e303ae
A
5854 bufsize = rt->rt_rmx.rmx_sendpipe;
5855 if (bufsize < so->so_snd.sb_hiwat)
1c79356b
A
5856#endif
5857 bufsize = so->so_snd.sb_hiwat;
5858 if (bufsize < mss)
5859 mss = bufsize;
5860 else {
2d21ac55
A
5861 bufsize = (((bufsize + (u_int64_t)mss - 1) / (u_int64_t)mss) * (u_int64_t)mss);
5862 if (bufsize > sb_max_corrected)
5863 bufsize = sb_max_corrected;
1c79356b
A
5864 (void)sbreserve(&so->so_snd, bufsize);
5865 }
5866 tp->t_maxseg = mss;
5867
39037602
A
5868 /*
5869 * Update MSS using recommendation from link status report. This is
5870 * temporary
5871 */
5872 tcp_update_mss_locked(so, ifp);
5873
1c79356b 5874#if RTV_RPIPE
55e303ae
A
5875 bufsize = rt->rt_rmx.rmx_recvpipe;
5876 if (bufsize < so->so_rcv.sb_hiwat)
1c79356b
A
5877#endif
5878 bufsize = so->so_rcv.sb_hiwat;
5879 if (bufsize > mss) {
2d21ac55
A
5880 bufsize = (((bufsize + (u_int64_t)mss - 1) / (u_int64_t)mss) * (u_int64_t)mss);
5881 if (bufsize > sb_max_corrected)
5882 bufsize = sb_max_corrected;
1c79356b
A
5883 (void)sbreserve(&so->so_rcv, bufsize);
5884 }
9bccf70c 5885
6d2010ae 5886 set_tcp_stream_priority(so);
1c79356b
A
5887
5888 if (rt->rt_rmx.rmx_ssthresh) {
5889 /*
5890 * There's some sort of gateway or interface
5891 * buffer limit on the path. Use this to set
fe8ab488
A
5892 * slow-start threshold, but set the threshold to
5893 * no less than 2*mss.
1c79356b
A
5894 */
5895 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
5896 tcpstat.tcps_usedssthresh++;
b0d623f7 5897 } else {
cf7d32b8 5898 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
b0d623f7 5899 }
cf7d32b8 5900
6d2010ae
A
5901 /*
5902 * Set the slow-start flight size depending on whether this
5903 * is a local network or not.
5904 */
5905 if (CC_ALGO(tp)->cwnd_init != NULL)
5906 CC_ALGO(tp)->cwnd_init(tp);
5907
fe8ab488 5908 tcp_ccdbg_trace(tp, NULL, TCP_CC_CWND_INIT);
6d2010ae 5909
b0d623f7
A
5910 /* Route locked during lookup above */
5911 RT_UNLOCK(rt);
1c79356b
A
5912}
5913
5914/*
5915 * Determine the MSS option to send on an outgoing SYN.
5916 */
5917int
39037602 5918tcp_mssopt(struct tcpcb *tp)
1c79356b
A
5919{
5920 struct rtentry *rt;
8ad349bb 5921 int mss;
1c79356b 5922#if INET6
9bccf70c
A
5923 int isipv6;
5924 int min_protoh;
5925#endif
1c79356b 5926
9bccf70c
A
5927#if INET6
5928 isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
5929 min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
5930 : sizeof (struct tcpiphdr);
5931#else
5932#define min_protoh (sizeof (struct tcpiphdr))
5933#endif
b0d623f7 5934
1c79356b
A
5935#if INET6
5936 if (isipv6)
6d2010ae 5937 rt = tcp_rtlookup6(tp->t_inpcb, IFSCOPE_NONE);
1c79356b
A
5938 else
5939#endif /* INET6 */
c910b4d9 5940 rt = tcp_rtlookup(tp->t_inpcb, IFSCOPE_NONE);
2d21ac55 5941 if (rt == NULL) {
2d21ac55 5942 return (
1c79356b
A
5943#if INET6
5944 isipv6 ? tcp_v6mssdflt :
5945#endif /* INET6 */
2d21ac55
A
5946 tcp_mssdflt);
5947 }
d12e1678
A
5948 /*
5949 * Slower link window correction:
5950 * If a value is specificied for slowlink_wsize use it for PPP links
5951 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
5952 * it is the default value adversized by pseudo-devices over ppp.
5953 */
39037602 5954 if (rt->rt_ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
d12e1678
A
5955 rt->rt_ifp->if_baudrate > 9600 && rt->rt_ifp->if_baudrate <= 128000) {
5956 tp->t_flags |= TF_SLOWLINK;
5957 }
1c79356b 5958
8ad349bb 5959#if INET6
2d21ac55
A
5960 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
5961#else
5962 mss = tcp_maxmtu(rt);
8ad349bb 5963#endif
b0d623f7
A
5964 /* Route locked during lookup above */
5965 RT_UNLOCK(rt);
3e170ce0
A
5966
5967#if NECP
5968 // At this point, the mss is just the MTU. Adjust if necessary.
5969 mss = necp_socket_get_effective_mtu(tp->t_inpcb, mss);
5970#endif /* NECP */
5971
8ad349bb 5972 return (mss - min_protoh);
9bccf70c
A
5973}
5974
9bccf70c 5975/*
8ad349bb
A
5976 * On a partial ack arrives, force the retransmission of the
5977 * next unacknowledged segment. Do not clear tp->t_dupacks.
6d2010ae 5978 * By setting snd_nxt to th_ack, this forces retransmission timer to
8ad349bb 5979 * be started again.
9bccf70c 5980 */
8ad349bb 5981static void
39037602 5982tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
9bccf70c 5983{
9bccf70c 5984 tcp_seq onxt = tp->snd_nxt;
b0d623f7 5985 u_int32_t ocwnd = tp->snd_cwnd;
9bccf70c 5986 tp->t_timer[TCPT_REXMT] = 0;
fe8ab488 5987 tp->t_timer[TCPT_PTO] = 0;
9bccf70c
A
5988 tp->t_rtttime = 0;
5989 tp->snd_nxt = th->th_ack;
5990 /*
5991 * Set snd_cwnd to one segment beyond acknowledged offset
39037602 5992 * (tp->snd_una has not yet been updated when this function
9bccf70c
A
5993 * is called)
5994 */
39236c6e 5995 tp->snd_cwnd = tp->t_maxseg + BYTES_ACKED(th, tp);
91447636 5996 tp->t_flags |= TF_ACKNOW;
9bccf70c
A
5997 (void) tcp_output(tp);
5998 tp->snd_cwnd = ocwnd;
5999 if (SEQ_GT(onxt, tp->snd_nxt))
6000 tp->snd_nxt = onxt;
6001 /*
6002 * Partial window deflation. Relies on fact that tp->snd_una
6003 * not updated yet.
6004 */
39236c6e
A
6005 if (tp->snd_cwnd > BYTES_ACKED(th, tp))
6006 tp->snd_cwnd -= BYTES_ACKED(th, tp);
2d21ac55
A
6007 else
6008 tp->snd_cwnd = 0;
6009 tp->snd_cwnd += tp->t_maxseg;
1c79356b 6010}
91447636
A
6011
6012/*
6013 * Drop a random TCP connection that hasn't been serviced yet and
6014 * is eligible for discard. There is a one in qlen chance that
6015 * we will return a null, saying that there are no dropable
6016 * requests. In this case, the protocol specific code should drop
6017 * the new request. This insures fairness.
6018 *
6019 * The listening TCP socket "head" must be locked
6020 */
6021static int
2d21ac55 6022tcp_dropdropablreq(struct socket *head)
91447636 6023{
2d21ac55 6024 struct socket *so, *sonext;
91447636 6025 unsigned int i, j, qlen;
39236c6e
A
6026 static u_int32_t rnd = 0;
6027 static u_int64_t old_runtime;
91447636 6028 static unsigned int cur_cnt, old_cnt;
39236c6e 6029 u_int64_t now_sec;
91447636 6030 struct inpcb *inp = NULL;
3a60a9f5 6031 struct tcpcb *tp;
2d21ac55
A
6032
6033 if ((head->so_options & SO_ACCEPTCONN) == 0)
39236c6e
A
6034 return (0);
6035
6036 if (TAILQ_EMPTY(&head->so_incomp))
6037 return (0);
6038
813fb2f6 6039 so_acquire_accept_list(head, NULL);
5ba3f43e 6040 socket_unlock(head, 0);
813fb2f6 6041
39037602 6042 /*
39236c6e
A
6043 * Check if there is any socket in the incomp queue
6044 * that is closed because of a reset from the peer and is
6045 * waiting to be garbage collected. If so, pick that as
6046 * the victim
6047 */
6048 TAILQ_FOREACH_SAFE(so, &head->so_incomp, so_list, sonext) {
6049 inp = sotoinpcb(so);
6050 tp = intotcpcb(inp);
6051 if (tp != NULL && tp->t_state == TCPS_CLOSED &&
6052 so->so_head != NULL &&
6053 (so->so_state & (SS_INCOMP|SS_CANTSENDMORE|SS_CANTRCVMORE)) ==
6054 (SS_INCOMP|SS_CANTSENDMORE|SS_CANTRCVMORE)) {
39037602
A
6055 /*
6056 * The listen socket is already locked but we
39236c6e
A
6057 * can lock this socket here without lock ordering
6058 * issues because it is in the incomp queue and
6059 * is not visible to others.
6060 */
5ba3f43e 6061 if (socket_try_lock(so)) {
39236c6e
A
6062 so->so_usecount++;
6063 goto found_victim;
6064 } else {
6065 continue;
6066 }
6067 }
6068 }
2d21ac55
A
6069
6070 so = TAILQ_FIRST(&head->so_incomp);
2d21ac55 6071
39236c6e
A
6072 now_sec = net_uptime();
6073 if ((i = (now_sec - old_runtime)) != 0) {
6074 old_runtime = now_sec;
91447636
A
6075 old_cnt = cur_cnt / i;
6076 cur_cnt = 0;
6077 }
39037602 6078
91447636 6079 qlen = head->so_incqlen;
39236c6e
A
6080 if (rnd == 0)
6081 rnd = RandomULong();
6082
91447636
A
6083 if (++cur_cnt > qlen || old_cnt > qlen) {
6084 rnd = (314159 * rnd + 66329) & 0xffff;
6085 j = ((qlen + 1) * rnd) >> 16;
6086
6087 while (j-- && so)
6088 so = TAILQ_NEXT(so, so_list);
6089 }
2d21ac55 6090 /* Find a connection that is not already closing (or being served) */
91447636
A
6091 while (so) {
6092 inp = (struct inpcb *)so->so_pcb;
39037602 6093
2d21ac55
A
6094 sonext = TAILQ_NEXT(so, so_list);
6095
5ba3f43e 6096 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
39037602 6097 /*
39236c6e 6098 * Avoid the issue of a socket being accepted
39037602
A
6099 * by one input thread and being dropped by
6100 * another input thread. If we can't get a hold
6101 * on this mutex, then grab the next socket in
39236c6e 6102 * line.
2d21ac55 6103 */
5ba3f43e 6104 if (socket_try_lock(so)) {
2d21ac55 6105 so->so_usecount++;
39037602 6106 if ((so->so_usecount == 2) &&
39236c6e
A
6107 (so->so_state & SS_INCOMP) &&
6108 !(so->so_flags & SOF_INCOMP_INPROGRESS)) {
2d21ac55 6109 break;
39236c6e 6110 } else {
39037602
A
6111 /*
6112 * don't use if being accepted or
39236c6e
A
6113 * used in any other way
6114 */
2d21ac55 6115 in_pcb_checkstate(inp, WNT_RELEASE, 1);
5ba3f43e 6116 socket_unlock(so, 1);
2d21ac55 6117 }
39236c6e 6118 } else {
39037602
A
6119 /*
6120 * do not try to lock the inp in
6121 * in_pcb_checkstate because the lock
39236c6e 6122 * is already held in some other thread.
b0d623f7
A
6123 * Only drop the inp_wntcnt reference.
6124 */
6125 in_pcb_checkstate(inp, WNT_RELEASE, 1);
6126 }
2d21ac55
A
6127 }
6128 so = sonext;
91447636 6129 }
39236c6e 6130 if (so == NULL) {
813fb2f6
A
6131 socket_lock(head, 0);
6132 so_release_accept_list(head);
39236c6e
A
6133 return (0);
6134 }
2d21ac55 6135
2d21ac55
A
6136 /* Makes sure socket is still in the right state to be discarded */
6137
91447636 6138 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
5ba3f43e 6139 socket_unlock(so, 1);
813fb2f6
A
6140 socket_lock(head, 0);
6141 so_release_accept_list(head);
39236c6e 6142 return (0);
91447636 6143 }
2d21ac55 6144
39236c6e 6145found_victim:
2d21ac55 6146 if (so->so_usecount != 2 || !(so->so_state & SS_INCOMP)) {
6d2010ae 6147 /* do not discard: that socket is being accepted */
5ba3f43e 6148 socket_unlock(so, 1);
813fb2f6
A
6149 socket_lock(head, 0);
6150 so_release_accept_list(head);
39236c6e 6151 return (0);
2d21ac55
A
6152 }
6153
813fb2f6 6154 socket_lock(head, 0);
6d2010ae 6155 TAILQ_REMOVE(&head->so_incomp, so, so_list);
d190cdc3
A
6156 head->so_incqlen--;
6157 head->so_qlen--;
6158 so->so_state &= ~SS_INCOMP;
6159 so->so_flags |= SOF_OVERFLOW;
6160 so->so_head = NULL;
813fb2f6 6161 so_release_accept_list(head);
5ba3f43e 6162 socket_unlock(head, 0);
91447636 6163
5ba3f43e 6164 socket_lock_assert_owned(so);
3a60a9f5 6165 tp = sototcpcb(so);
6d2010ae
A
6166
6167 tcp_close(tp);
6d2010ae 6168 if (inp->inp_wantcnt > 0 && inp->inp_wantcnt != WNT_STOPUSING) {
39037602 6169 /*
39236c6e 6170 * Some one has a wantcnt on this pcb. Since WNT_ACQUIRE
6d2010ae
A
6171 * doesn't require a lock, it could have happened while
6172 * we are holding the lock. This pcb will have to
6173 * be garbage collected later.
6174 * Release the reference held for so_incomp queue
6175 */
d190cdc3 6176 VERIFY(so->so_usecount > 0);
6d2010ae 6177 so->so_usecount--;
5ba3f43e 6178 socket_unlock(so, 1);
6d2010ae 6179 } else {
39037602
A
6180 /*
6181 * Unlock this socket and leave the reference on.
6182 * We need to acquire the pcbinfo lock in order to
6183 * fully dispose it off
6d2010ae 6184 */
5ba3f43e 6185 socket_unlock(so, 0);
6d2010ae 6186
39236c6e 6187 lck_rw_lock_exclusive(tcbinfo.ipi_lock);
6d2010ae 6188
5ba3f43e 6189 socket_lock(so, 0);
6d2010ae 6190 /* Release the reference held for so_incomp queue */
d190cdc3 6191 VERIFY(so->so_usecount > 0);
6d2010ae
A
6192 so->so_usecount--;
6193
39037602
A
6194 if (so->so_usecount != 1 ||
6195 (inp->inp_wantcnt > 0 &&
39236c6e 6196 inp->inp_wantcnt != WNT_STOPUSING)) {
39037602
A
6197 /*
6198 * There is an extra wantcount or usecount
6199 * that must have been added when the socket
6200 * was unlocked. This socket will have to be
39236c6e 6201 * garbage collected later
6d2010ae 6202 */
5ba3f43e 6203 socket_unlock(so, 1);
6d2010ae 6204 } else {
6d2010ae 6205 /* Drop the reference held for this function */
d190cdc3 6206 VERIFY(so->so_usecount > 0);
6d2010ae
A
6207 so->so_usecount--;
6208
6209 in_pcbdispose(inp);
6210 }
39236c6e 6211 lck_rw_done(tcbinfo.ipi_lock);
6d2010ae 6212 }
3a60a9f5 6213 tcpstat.tcps_drops++;
6d2010ae 6214
5ba3f43e 6215 socket_lock(head, 0);
6d2010ae
A
6216 return(1);
6217}
6218
6219/* Set background congestion control on a socket */
6220void
6221tcp_set_background_cc(struct socket *so)
6222{
6223 tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
6224}
6225
6226/* Set foreground congestion control on a socket */
6227void
6228tcp_set_foreground_cc(struct socket *so)
6229{
fe8ab488
A
6230 if (tcp_use_newreno)
6231 tcp_set_new_cc(so, TCP_CC_ALGO_NEWRENO_INDEX);
6232 else
6233 tcp_set_new_cc(so, TCP_CC_ALGO_CUBIC_INDEX);
6d2010ae
A
6234}
6235
6236static void
6237tcp_set_new_cc(struct socket *so, uint16_t cc_index)
6238{
6239 struct inpcb *inp = sotoinpcb(so);
6240 struct tcpcb *tp = intotcpcb(inp);
39236c6e 6241 u_char old_cc_index = 0;
6d2010ae
A
6242 if (tp->tcp_cc_index != cc_index) {
6243
6244 old_cc_index = tp->tcp_cc_index;
6245
6246 if (CC_ALGO(tp)->cleanup != NULL)
6247 CC_ALGO(tp)->cleanup(tp);
6248 tp->tcp_cc_index = cc_index;
6249
fe8ab488
A
6250 tcp_cc_allocate_state(tp);
6251
6252 if (CC_ALGO(tp)->switch_to != NULL)
6253 CC_ALGO(tp)->switch_to(tp, old_cc_index);
6254
6255 tcp_ccdbg_trace(tp, NULL, TCP_CC_CHANGE_ALGO);
6d2010ae 6256 }
91447636
A
6257}
6258
316670eb
A
6259void
6260tcp_set_recv_bg(struct socket *so)
6261{
6262 if (!IS_TCP_RECV_BG(so))
39037602 6263 so->so_flags1 |= SOF1_TRAFFIC_MGT_TCP_RECVBG;
39236c6e
A
6264
6265 /* Unset Large Receive Offload on background sockets */
6266 so_set_lro(so, SO_TC_BK);
316670eb
A
6267}
6268
6269void
6270tcp_clear_recv_bg(struct socket *so)
6271{
6272 if (IS_TCP_RECV_BG(so))
39037602 6273 so->so_flags1 &= ~(SOF1_TRAFFIC_MGT_TCP_RECVBG);
39236c6e 6274
39037602
A
6275 /*
6276 * Set/unset use of Large Receive Offload depending on
39236c6e
A
6277 * the traffic class
6278 */
6279 so_set_lro(so, so->so_traffic_class);
316670eb
A
6280}
6281
6282void
6283inp_fc_unthrottle_tcp(struct inpcb *inp)
6284{
6285 struct tcpcb *tp = inp->inp_ppcb;
6286 /*
6287 * Back off the slow-start threshold and enter
6288 * congestion avoidance phase
6289 */
6290 if (CC_ALGO(tp)->pre_fr != NULL)
6291 CC_ALGO(tp)->pre_fr(tp);
6292
6293 tp->snd_cwnd = tp->snd_ssthresh;
3e170ce0 6294 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
316670eb
A
6295 /*
6296 * Restart counting for ABC as we changed the
6297 * congestion window just now.
6298 */
6299 tp->t_bytes_acked = 0;
6300
6301 /* Reset retransmit shift as we know that the reason
39037602 6302 * for delay in sending a packet is due to flow
316670eb
A
6303 * control on the outgoing interface. There is no need
6304 * to backoff retransmit timer.
6305 */
39037602 6306 TCP_RESET_REXMT_STATE(tp);
316670eb
A
6307
6308 /*
6309 * Start the output stream again. Since we are
6310 * not retransmitting data, do not reset the
6311 * retransmit timer or rtt calculation.
6312 */
6313 tcp_output(tp);
6314}
39037602 6315
8ad349bb
A
6316static int
6317tcp_getstat SYSCTL_HANDLER_ARGS
6318{
2d21ac55 6319#pragma unused(oidp, arg1, arg2)
8ad349bb
A
6320
6321 int error;
5ba3f43e
A
6322 struct tcpstat *stat;
6323 stat = &tcpstat;
6324#if !CONFIG_EMBEDDED
39236c6e
A
6325 proc_t caller = PROC_NULL;
6326 proc_t caller_parent = PROC_NULL;
6327 char command_name[MAXCOMLEN + 1] = "";
6328 char parent_name[MAXCOMLEN + 1] = "";
5ba3f43e 6329 struct tcpstat zero_stat;
39236c6e
A
6330 if ((caller = proc_self()) != PROC_NULL) {
6331 /* get process name */
6332 strlcpy(command_name, caller->p_comm, sizeof(command_name));
6333
6334 /* get parent process name if possible */
6335 if ((caller_parent = proc_find(caller->p_ppid)) != PROC_NULL) {
6336 strlcpy(parent_name, caller_parent->p_comm,
6337 sizeof(parent_name));
6338 proc_rele(caller_parent);
6339 }
6340
6341 if ((escape_str(command_name, strlen(command_name),
6342 sizeof(command_name)) == 0) &&
6343 (escape_str(parent_name, strlen(parent_name),
6344 sizeof(parent_name)) == 0)) {
6345 kern_asl_msg(LOG_DEBUG, "messagetracer",
6346 5,
6347 "com.apple.message.domain",
6348 "com.apple.kernel.tcpstat", /* 1 */
6349 "com.apple.message.signature",
6350 "tcpstat", /* 2 */
6351 "com.apple.message.signature2", command_name, /* 3 */
6352 "com.apple.message.signature3", parent_name, /* 4 */
6353 "com.apple.message.summarize", "YES", /* 5 */
6354 NULL);
6355 }
6356 }
6357 if (caller != PROC_NULL)
6358 proc_rele(caller);
5ba3f43e
A
6359 if (tcp_disable_access_to_stats &&
6360 !kauth_cred_issuser(kauth_cred_get())) {
6361 bzero(&zero_stat, sizeof(zero_stat));
6362 stat = &zero_stat;
6363 }
6364
6365#endif /* !CONFIG_EMBEDDED */
39236c6e 6366
8ad349bb
A
6367 if (req->oldptr == 0) {
6368 req->oldlen= (size_t)sizeof(struct tcpstat);
6369 }
6370
5ba3f43e 6371 error = SYSCTL_OUT(req, stat, MIN(sizeof (tcpstat), req->oldlen));
8ad349bb
A
6372
6373 return (error);
6374
6375}
6376
39236c6e
A
6377/*
6378 * Checksum extended TCP header and data.
6379 */
6380int
6381tcp_input_checksum(int af, struct mbuf *m, struct tcphdr *th, int off, int tlen)
6382{
6383 struct ifnet *ifp = m->m_pkthdr.rcvif;
6384
6385 switch (af) {
6386 case AF_INET: {
6387 struct ip *ip = mtod(m, struct ip *);
6388 struct ipovly *ipov = (struct ipovly *)ip;
6389
6390 if (m->m_pkthdr.pkt_flags & PKTF_SW_LRO_DID_CSUM)
6391 return (0);
6392
5ba3f43e
A
6393 /* ip_stripoptions() must have been called before we get here */
6394 ASSERT((ip->ip_hl << 2) == sizeof (*ip));
6395
39236c6e
A
6396 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
6397 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
6398 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
6399 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6400 th->th_sum = m->m_pkthdr.csum_rx_val;
6401 } else {
5ba3f43e
A
6402 uint32_t sum = m->m_pkthdr.csum_rx_val;
6403 uint32_t start = m->m_pkthdr.csum_rx_start;
6404 int32_t trailer = (m_pktlen(m) - (off + tlen));
39236c6e
A
6405
6406 /*
6407 * Perform 1's complement adjustment of octets
6408 * that got included/excluded in the hardware-
6409 * calculated checksum value. Ignore cases
5ba3f43e
A
6410 * where the value already includes the entire
6411 * IP header span, as the sum for those octets
6412 * would already be 0 by the time we get here;
6413 * IP has already performed its header checksum
6414 * checks. If we do need to adjust, restore
6415 * the original fields in the IP header when
6416 * computing the adjustment value. Also take
6417 * care of any trailing bytes and subtract out
6418 * their partial sum.
39236c6e 6419 */
5ba3f43e 6420 ASSERT(trailer >= 0);
39236c6e 6421 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
5ba3f43e
A
6422 ((start != 0 && start != off) || trailer)) {
6423 uint32_t swbytes = (uint32_t)trailer;
6424
39236c6e 6425 if (start < off) {
5ba3f43e
A
6426 ip->ip_len += sizeof (*ip);
6427#if BYTE_ORDER != BIG_ENDIAN
39236c6e
A
6428 HTONS(ip->ip_len);
6429 HTONS(ip->ip_off);
5ba3f43e 6430#endif /* BYTE_ORDER != BIG_ENDIAN */
39236c6e 6431 }
39236c6e 6432 /* callee folds in sum */
5ba3f43e
A
6433 sum = m_adj_sum16(m, start, off,
6434 tlen, sum);
6435 if (off > start)
6436 swbytes += (off - start);
6437 else
6438 swbytes += (start - off);
6439
39236c6e 6440 if (start < off) {
5ba3f43e 6441#if BYTE_ORDER != BIG_ENDIAN
39236c6e
A
6442 NTOHS(ip->ip_off);
6443 NTOHS(ip->ip_len);
5ba3f43e
A
6444#endif /* BYTE_ORDER != BIG_ENDIAN */
6445 ip->ip_len -= sizeof (*ip);
39236c6e 6446 }
5ba3f43e
A
6447
6448 if (swbytes != 0)
6449 tcp_in_cksum_stats(swbytes);
6450 if (trailer != 0)
6451 m_adj(m, -trailer);
39236c6e
A
6452 }
6453
6454 /* callee folds in sum */
6455 th->th_sum = in_pseudo(ip->ip_src.s_addr,
6456 ip->ip_dst.s_addr,
6457 sum + htonl(tlen + IPPROTO_TCP));
6458 }
6459 th->th_sum ^= 0xffff;
6460 } else {
6461 uint16_t ip_sum;
6462 int len;
6463 char b[9];
6464
6465 bcopy(ipov->ih_x1, b, sizeof (ipov->ih_x1));
6466 bzero(ipov->ih_x1, sizeof (ipov->ih_x1));
6467 ip_sum = ipov->ih_len;
6468 ipov->ih_len = (u_short)tlen;
6469#if BYTE_ORDER != BIG_ENDIAN
6470 HTONS(ipov->ih_len);
6471#endif
6472 len = sizeof (struct ip) + tlen;
6473 th->th_sum = in_cksum(m, len);
6474 bcopy(b, ipov->ih_x1, sizeof (ipov->ih_x1));
6475 ipov->ih_len = ip_sum;
6476
6477 tcp_in_cksum_stats(len);
6478 }
6479 break;
6480 }
6481#if INET6
6482 case AF_INET6: {
6483 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
6484
6485 if (m->m_pkthdr.pkt_flags & PKTF_SW_LRO_DID_CSUM)
6486 return (0);
6487
6488 if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
6489 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
6490 (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
6491 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
6492 th->th_sum = m->m_pkthdr.csum_rx_val;
6493 } else {
5ba3f43e
A
6494 uint32_t sum = m->m_pkthdr.csum_rx_val;
6495 uint32_t start = m->m_pkthdr.csum_rx_start;
6496 int32_t trailer = (m_pktlen(m) - (off + tlen));
39236c6e
A
6497
6498 /*
6499 * Perform 1's complement adjustment of octets
6500 * that got included/excluded in the hardware-
5ba3f43e
A
6501 * calculated checksum value. Also take care
6502 * of any trailing bytes and subtract out their
6503 * partial sum.
39236c6e 6504 */
5ba3f43e 6505 ASSERT(trailer >= 0);
39236c6e 6506 if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
5ba3f43e
A
6507 (start != off || trailer != 0)) {
6508 uint16_t s = 0, d = 0;
6509 uint32_t swbytes = (uint32_t)trailer;
39236c6e
A
6510
6511 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
6512 s = ip6->ip6_src.s6_addr16[1];
6513 ip6->ip6_src.s6_addr16[1] = 0 ;
6514 }
6515 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
6516 d = ip6->ip6_dst.s6_addr16[1];
6517 ip6->ip6_dst.s6_addr16[1] = 0;
6518 }
6519
6520 /* callee folds in sum */
5ba3f43e
A
6521 sum = m_adj_sum16(m, start, off,
6522 tlen, sum);
6523 if (off > start)
6524 swbytes += (off - start);
6525 else
6526 swbytes += (start - off);
39236c6e
A
6527
6528 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src))
6529 ip6->ip6_src.s6_addr16[1] = s;
6530 if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst))
6531 ip6->ip6_dst.s6_addr16[1] = d;
5ba3f43e
A
6532
6533 if (swbytes != 0)
6534 tcp_in6_cksum_stats(swbytes);
6535 if (trailer != 0)
6536 m_adj(m, -trailer);
39236c6e
A
6537 }
6538
6539 th->th_sum = in6_pseudo(
6540 &ip6->ip6_src, &ip6->ip6_dst,
6541 sum + htonl(tlen + IPPROTO_TCP));
6542 }
6543 th->th_sum ^= 0xffff;
6544 } else {
6545 tcp_in6_cksum_stats(tlen);
6546 th->th_sum = in6_cksum(m, IPPROTO_TCP, off, tlen);
6547 }
6548 break;
6549 }
6550#endif /* INET6 */
6551 default:
6552 VERIFY(0);
6553 /* NOTREACHED */
6554 }
6555
6556 if (th->th_sum != 0) {
6557 tcpstat.tcps_rcvbadsum++;
6558 IF_TCP_STATINC(ifp, badformat);
6559 return (-1);
6560 }
6561
6562 return (0);
6563}
6564
fe8ab488 6565SYSCTL_PROC(_net_inet_tcp, TCPCTL_STATS, stats,
3e170ce0
A
6566 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, tcp_getstat,
6567 "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
8ad349bb 6568
2d21ac55
A
6569static int
6570sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
6571{
6572#pragma unused(arg1, arg2)
6573
6574 int error, val = tcprexmtthresh;
6575
6576 error = sysctl_handle_int(oidp, &val, 0, req);
6577 if (error || !req->newptr)
6578 return (error);
6579
6580 /*
6581 * Constrain the number of duplicate ACKs
39037602 6582 * to consider for TCP fast retransmit
2d21ac55
A
6583 * to either 2 or 3
6584 */
6585
6586 if (val < 2 || val > 3)
6587 return (EINVAL);
6588
6589 tcprexmtthresh = val;
6590
6591 return (0);
6592}
91447636 6593
3e170ce0
A
6594SYSCTL_PROC(_net_inet_tcp, OID_AUTO, rexmt_thresh, CTLTYPE_INT | CTLFLAG_RW |
6595 CTLFLAG_LOCKED, &tcprexmtthresh, 0, &sysctl_rexmtthresh, "I",
6596 "Duplicate ACK Threshold for Fast Retransmit");