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