xref: /xnu-11215.81.4/bsd/netinet/tcp_input.c (revision d4514f0bc1d3f944c22d92e68b646ac3fb40d452)
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 || tcp_sent_tlp_retrans(tp)) &&
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 as a tail loss probe retransmission, 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 (tcp_sent_tlp_retrans(tp) && 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 | TF_L4S_ENABLED | TF_L4S_DISABLED));
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 			if (tp->t_flagsext & (TF_L4S_ENABLED | TF_L4S_DISABLED)) {
2860 				tcp_set_foreground_cc(so);
2861 			}
2862 			tp->t_inpcb->inp_flags2 |=
2863 			    tp0->t_inpcb->inp_flags2 & INP2_KEEPALIVE_OFFLOAD;
2864 
2865 			/* now drop the reference on the listener */
2866 			socket_unlock(oso, 1);
2867 
2868 			tcp_set_max_rwinscale(tp, so);
2869 
2870 #if CONTENT_FILTER
2871 			if (check_cfil) {
2872 				int error = cfil_sock_attach(so2, SA(&to2), SA(&from), CFS_CONNECTION_DIR_IN);
2873 				if (error != 0) {
2874 					TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " cfil_sock_attach failed");
2875 					goto drop;
2876 				}
2877 			}
2878 #endif /* CONTENT_FILTER */
2879 
2880 			KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END, 0, 0, 0, 0, 0);
2881 		}
2882 	}
2883 	socket_lock_assert_owned(so);
2884 
2885 	/*
2886 	 * Packet accounting should not be done on listening socket
2887 	 */
2888 	if (th->th_flags & TH_SYN) {
2889 		(void) os_add_overflow(1, tp->t_syn_rcvd, &tp->t_syn_rcvd);
2890 	}
2891 	if (th->th_flags & TH_FIN) {
2892 		(void) os_add_overflow(1, tp->t_fin_rcvd, &tp->t_fin_rcvd);
2893 	}
2894 	if (th->th_flags & TH_RST) {
2895 		(void) os_add_overflow(1, tp->t_rst_rcvd, &tp->t_rst_rcvd);
2896 	}
2897 	TCP_LOG_TH_FLAGS(TCP_LOG_HDR, th, tp, false, ifp);
2898 
2899 	if (net_mpklog_enabled && (m->m_pkthdr.rcvif->if_xflags & IFXF_MPK_LOG)) {
2900 		MPKL_TCP_INPUT(tcp_mpkl_log_object,
2901 		    ntohs(tp->t_inpcb->inp_lport), ntohs(tp->t_inpcb->inp_fport),
2902 		    th->th_seq, th->th_ack, tlen, thflags,
2903 		    so->last_pid, so->so_log_seqn++);
2904 	}
2905 
2906 	if (tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
2907 		/*
2908 		 * Evaluate the rate of arrival of packets to see if the
2909 		 * receiver can reduce the ack traffic. The algorithm to
2910 		 * stretch acks will be enabled if the connection meets
2911 		 * certain criteria defined in tcp_stretch_ack_enable function.
2912 		 */
2913 		if ((tp->t_flagsext & TF_RCVUNACK_WAITSS) != 0) {
2914 			TCP_INC_VAR(tp->rcv_waitforss, segment_count);
2915 		}
2916 		if (tcp_stretch_ack_enable(tp, thflags)) {
2917 			tp->t_flags |= TF_STRETCHACK;
2918 			tp->t_flagsext &= ~(TF_RCVUNACK_WAITSS);
2919 			tp->rcv_waitforss = 0;
2920 		} else {
2921 			tp->t_flags &= ~(TF_STRETCHACK);
2922 		}
2923 		if (TSTMP_GT(tp->rcv_unackwin - (tcp_rcvunackwin >> 1), tcp_now)) {
2924 			tp->rcv_by_unackhalfwin += (tlen + off);
2925 			tp->rcv_by_unackwin += (tlen + off);
2926 		} else {
2927 			tp->rcv_unackwin = tcp_now + tcp_rcvunackwin;
2928 			tp->rcv_by_unackwin = tp->rcv_by_unackhalfwin + tlen + off;
2929 			tp->rcv_by_unackhalfwin = tlen + off;
2930 		}
2931 	}
2932 
2933 	if (TCP_L4S_ENABLED(tp) && TCP_ACC_ECN_ON(tp)) {
2934 		/* Reset the state used for AccECN processing */
2935 		tp->t_aecn.accecn_processed = 0;
2936 	}
2937 
2938 	if (tp->t_state == TCPS_ESTABLISHED && BYTES_ACKED(th, tp) > 0) {
2939 		if (CC_ALGO(tp)->set_bytes_acked != NULL) {
2940 			CC_ALGO(tp)->set_bytes_acked(tp, BYTES_ACKED(th, tp));
2941 		}
2942 		if (tp->ecn_flags & TE_SENDIPECT) {
2943 			/*
2944 			 * Data sent with ECT has been acknowledged, calculate
2945 			 * packets approx. by dividing by MSS. This is done to
2946 			 * count MSS sized packets in case packets are aggregated
2947 			 * by GRO/LRO.
2948 			 */
2949 			uint32_t bytes_acked = tcp_round_to(BYTES_ACKED(th, tp), tp->t_maxseg);
2950 			tp->t_ecn_capable_packets_acked += max(1, (bytes_acked / tp->t_maxseg));
2951 		}
2952 	}
2953 
2954 	/* Accurate ECN has different semantics for TH_CWR. */
2955 	if (!TCP_ACC_ECN_ON(tp)) {
2956 		/*
2957 		 * Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
2958 		 * bother doing extensive checks for state and whatnot.
2959 		 */
2960 		if (thflags & TH_CWR) {
2961 			tp->ecn_flags &= ~TE_SENDECE;
2962 			tp->t_ecn_recv_cwr++;
2963 		}
2964 	}
2965 
2966 	/*
2967 	 * Accurate ECN feedback for Data Receiver,
2968 	 * Process IP ECN bits and update r.cep for CE marked pure ACKs
2969 	 * or valid data packets
2970 	 */
2971 	uint8_t ace = tcp_get_ace(th);
2972 	if (TCP_ACC_ECN_ON(tp) && tp->t_state == TCPS_ESTABLISHED) {
2973 		/* Update receive side counters */
2974 		if (tlen == 0 || (tlen > 0 &&
2975 		    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2976 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd))) {
2977 			tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
2978 		}
2979 
2980 		/* Test for ACE bleaching, initial value of ace should be non-zero */
2981 		if (th->th_seq == tp->iss + 1 && ace == 0) {
2982 			tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_ace_bleaching_detected;
2983 		}
2984 	} else {
2985 		/*
2986 		 * Explicit Congestion Notification - Flag that we need to send ECE if
2987 		 *	+ The IP Congestion experienced flag was set.
2988 		 *	+ Socket is in established state
2989 		 *	+ We negotiated ECN in the TCP setup
2990 		 *	+ This isn't a pure ack (tlen > 0)
2991 		 *	+ The data is in the valid window
2992 		 *
2993 		 *	TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
2994 		 */
2995 		if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
2996 		    TCP_ECN_ENABLED(tp) && tlen > 0 &&
2997 		    SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2998 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
2999 			tp->t_ecn_recv_ce++;
3000 			tcpstat.tcps_ecn_recv_ce++;
3001 			INP_INC_IFNET_STAT(inp, ecn_recv_ce);
3002 			/* Mark this connection as it received CE from network */
3003 			tp->ecn_flags |= TE_RECV_ECN_CE;
3004 			tp->ecn_flags |= TE_SENDECE;
3005 		}
3006 	}
3007 
3008 	/*
3009 	 * If we received an explicit notification of congestion in
3010 	 * ip tos ecn bits or by the CWR bit in TCP header flags, reset
3011 	 * the ack-stretching state. We need to handle ECN notification if
3012 	 * an ECN setup SYN was sent even once.
3013 	 */
3014 	if (tp->t_state == TCPS_ESTABLISHED &&
3015 	    (tp->ecn_flags & TE_SETUPSENT) &&
3016 	    (ip_ecn == IPTOS_ECN_CE || (thflags & TH_CWR))) {
3017 		tcp_reset_stretch_ack(tp);
3018 		tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
3019 		CLEAR_IAJ_STATE(tp);
3020 	}
3021 
3022 	if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
3023 	    !TCP_ECN_ENABLED(tp) && !(tp->ecn_flags & TE_CEHEURI_SET)) {
3024 		tcpstat.tcps_ecn_fallback_ce++;
3025 		tcp_heuristic_ecn_aggressive(tp);
3026 		tp->ecn_flags |= TE_CEHEURI_SET;
3027 	}
3028 
3029 	if (tp->t_state == TCPS_ESTABLISHED && TCP_ECN_ENABLED(tp) &&
3030 	    ip_ecn == IPTOS_ECN_CE && !(tp->ecn_flags & TE_CEHEURI_SET)) {
3031 		if (inp->inp_stat->rxpackets < ECN_MIN_CE_PROBES) {
3032 			tp->t_ecn_recv_ce_pkt++;
3033 		} else if (tp->t_ecn_recv_ce_pkt > ECN_MAX_CE_RATIO) {
3034 			tcpstat.tcps_ecn_fallback_ce++;
3035 			tcp_heuristic_ecn_aggressive(tp);
3036 			tp->ecn_flags |= TE_CEHEURI_SET;
3037 			INP_INC_IFNET_STAT(inp, ecn_fallback_ce);
3038 		} else {
3039 			/* We tracked the first ECN_MIN_CE_PROBES segments, we
3040 			 * now know that the path is good.
3041 			 */
3042 			tp->ecn_flags |= TE_CEHEURI_SET;
3043 		}
3044 	}
3045 
3046 	/* Update rcvtime as a new segment was received on the connection */
3047 	tp->t_rcvtime = tcp_now;
3048 
3049 	/*
3050 	 * Segment received on connection.
3051 	 * Reset idle time and keep-alive timer.
3052 	 */
3053 	if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3054 		tcp_keepalive_reset(tp);
3055 
3056 		if (tp->t_mpsub) {
3057 			mptcp_reset_keepalive(tp);
3058 		}
3059 	}
3060 
3061 	/*
3062 	 * Process options if not in LISTEN state,
3063 	 * else do it below (after getting remote address).
3064 	 */
3065 	if (tp->t_state != TCPS_LISTEN && optp) {
3066 		tcp_dooptions(tp, optp, optlen, th, &to);
3067 	}
3068 #if MPTCP
3069 	if (tp->t_state != TCPS_LISTEN && (so->so_flags & SOF_MP_SUBFLOW)) {
3070 		mptcp_insert_rmap(tp, m, th);
3071 	}
3072 #endif /* MPTCP */
3073 	if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
3074 		if (!(thflags & TH_ACK) ||
3075 		    (SEQ_GT(th->th_ack, tp->iss) &&
3076 		    SEQ_LEQ(th->th_ack, tp->snd_max))) {
3077 			tcp_finalize_options(tp, &to, ifscope);
3078 		}
3079 	}
3080 
3081 #if TRAFFIC_MGT
3082 	/*
3083 	 * Compute inter-packet arrival jitter. According to RFC 3550,
3084 	 * inter-packet arrival jitter is defined as the difference in
3085 	 * packet spacing at the receiver compared to the sender for a
3086 	 * pair of packets. When two packets of maximum segment size come
3087 	 * one after the other with consecutive sequence numbers, we
3088 	 * consider them as packets sent together at the sender and use
3089 	 * them as a pair to compute inter-packet arrival jitter. This
3090 	 * metric indicates the delay induced by the network components due
3091 	 * to queuing in edge/access routers.
3092 	 */
3093 	if (tp->t_state == TCPS_ESTABLISHED &&
3094 	    (thflags & (TH_SYN | TH_FIN | TH_RST | TH_URG | TH_ACK | TH_ECE | TH_PUSH)) == TH_ACK &&
3095 	    ((tp->t_flags & TF_NEEDFIN) == 0) &&
3096 	    ((to.to_flags & TOF_TS) == 0 ||
3097 	    TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
3098 	    th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
3099 		int seg_size = tlen;
3100 		if (tp->iaj_pktcnt <= IAJ_IGNORE_PKTCNT) {
3101 			TCP_INC_VAR(tp->iaj_pktcnt, segment_count);
3102 		}
3103 
3104 		if (tp->iaj_size == 0 || seg_size > tp->iaj_size ||
3105 		    (seg_size == tp->iaj_size && tp->iaj_rcv_ts == 0)) {
3106 			/*
3107 			 * State related to inter-arrival jitter is
3108 			 * uninitialized or we are trying to find a good
3109 			 * first packet to start computing the metric
3110 			 */
3111 			update_iaj_state(tp, seg_size, 0);
3112 		} else {
3113 			if (seg_size == tp->iaj_size) {
3114 				/*
3115 				 * Compute inter-arrival jitter taking
3116 				 * this packet as the second packet
3117 				 */
3118 				compute_iaj(tp);
3119 			}
3120 			if (seg_size < tp->iaj_size) {
3121 				/*
3122 				 * There is a smaller packet in the stream.
3123 				 * Some times the maximum size supported
3124 				 * on a path can change if there is a new
3125 				 * link with smaller MTU. The receiver will
3126 				 * not know about this change. If there
3127 				 * are too many packets smaller than
3128 				 * iaj_size, we try to learn the iaj_size
3129 				 * again.
3130 				 */
3131 				TCP_INC_VAR(tp->iaj_small_pkt, segment_count);
3132 				if (tp->iaj_small_pkt > RESET_IAJ_SIZE_THRESH) {
3133 					update_iaj_state(tp, seg_size, 1);
3134 				} else {
3135 					CLEAR_IAJ_STATE(tp);
3136 				}
3137 			} else {
3138 				update_iaj_state(tp, seg_size, 0);
3139 			}
3140 		}
3141 	} else {
3142 		CLEAR_IAJ_STATE(tp);
3143 	}
3144 #endif /* TRAFFIC_MGT */
3145 
3146 	/*
3147 	 * Header prediction: check for the two common cases
3148 	 * of a uni-directional data xfer.  If the packet has
3149 	 * no control flags, is in-sequence, the window didn't
3150 	 * change and we're not retransmitting, it's a
3151 	 * candidate.  If the length is zero and the ack moved
3152 	 * forward, we're the sender side of the xfer.  Just
3153 	 * free the data acked & wake any higher level process
3154 	 * that was blocked waiting for space.  If the length
3155 	 * is non-zero and the ack didn't move, we're the
3156 	 * receiver side.  If we're getting packets in-order
3157 	 * (the reassembly queue is empty), add the data to
3158 	 * the socket buffer and note that we need a delayed ack.
3159 	 * Make sure that the hidden state-flags are also off.
3160 	 * Since we check for TCPS_ESTABLISHED above, it can only
3161 	 * be TH_NEEDSYN.
3162 	 */
3163 	if (tp->t_state == TCPS_ESTABLISHED &&
3164 	    !(so->so_state & SS_CANTRCVMORE) &&
3165 	    (thflags & TH_FLAGS) == TH_ACK &&
3166 	    ((tp->t_flags & TF_NEEDFIN) == 0) &&
3167 	    ((to.to_flags & TOF_TS) == 0 ||
3168 	    TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
3169 	    th->th_seq == tp->rcv_nxt &&
3170 	    tiwin && tiwin == tp->snd_wnd &&
3171 	    tp->snd_nxt == tp->snd_max) {
3172 		/*
3173 		 * If last ACK falls within this segment's sequence numbers,
3174 		 * record the timestamp.
3175 		 * NOTE that the test is modified according to the latest
3176 		 * proposal of the [email protected] list (Braden 1993/04/26).
3177 		 */
3178 		if ((to.to_flags & TOF_TS) != 0 &&
3179 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
3180 			tp->ts_recent_age = tcp_now;
3181 			tp->ts_recent = to.to_tsval;
3182 		}
3183 
3184 		/*
3185 		 * We increment t_unacksegs_ce for both data segments
3186 		 * and pure ACKs for Accurate ECN
3187 		 */
3188 		if (TCP_ACC_ECN_ON(tp) && ip_ecn == IPTOS_ECN_CE) {
3189 			TCP_INC_VAR(tp->t_unacksegs_ce, segment_count);
3190 		}
3191 
3192 		if (tlen == 0) {
3193 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
3194 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
3195 			    tp->snd_cwnd >= tp->snd_ssthresh &&
3196 			    (!IN_FASTRECOVERY(tp) &&
3197 			    ((!(SACK_ENABLED(tp)) &&
3198 			    tp->t_dupacks < tp->t_rexmtthresh) ||
3199 			    (SACK_ENABLED(tp) && to.to_nsacks == 0 &&
3200 			    TAILQ_EMPTY(&tp->snd_holes))))) {
3201 				/*
3202 				 * this is a pure ack for outstanding data.
3203 				 */
3204 				++tcpstat.tcps_predack;
3205 
3206 				tcp_bad_rexmt_check(tp, th, &to);
3207 
3208 				/* Recalculate the RTT */
3209 				tcp_compute_rtt(tp, &to, th);
3210 
3211 				VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
3212 				acked = BYTES_ACKED(th, tp);
3213 				tcpstat.tcps_rcvackpack++;
3214 				tcpstat.tcps_rcvackbyte += acked;
3215 
3216 				/* TE_SENDIPECT is only set when L4S sysctl is enabled */
3217 				if (TCP_ACC_ECN_ON(tp) && (tp->ecn_flags & TE_SENDIPECT)) {
3218 					if (!TCP_L4S_ENABLED(tp)) {
3219 						os_log_error(OS_LOG_DEFAULT, "TE_SENDIPECT flag is set but TCP_L4S_ENABLED is not");
3220 					}
3221 					uint32_t pkts_acked = tcp_packets_this_ack(tp, acked);
3222 					tp->total_ect_packets_acked += pkts_acked;
3223 
3224 					bool newly_acked_time = false;
3225 					if (acked == 0 && (to.to_flags & TOF_TS) != 0 && to.to_tsecr != 0 &&
3226 					    TSTMP_GT(to.to_tsecr, tp->t_last_ack_tsecr)) {
3227 						newly_acked_time = true;
3228 					}
3229 					if (acked > 0 || newly_acked_time) {
3230 						tcp_process_accecn(tp, &to, th, pkts_acked, ace);
3231 					}
3232 				}
3233 
3234 				/*
3235 				 * Process sent segments used for RACK, called after RTT is computed
3236 				 * RACK reordering window doesn't need to be updated until we process
3237 				 * DSACK.
3238 				 */
3239 				if (TCP_RACK_ENABLED(tp)) {
3240 					tcp_segs_doack(tp, th->th_ack, &to);
3241 					if (SEQ_LT(tp->snd_fack, th->th_ack)) {
3242 						/*
3243 						 * We update snd_fack here for RACK only as it is updated
3244 						 * and used differently for SACK. This should be done after
3245 						 * ACK processing of segments which checks for reordering.
3246 						 * Also, we don't compare with highest_sacked_seq here as this
3247 						 * is the fast path with no SACK blocks.
3248 						 */
3249 						tp->snd_fack = th->th_ack;
3250 					}
3251 				}
3252 
3253 				/*
3254 				 * Handle an ack that is in sequence during
3255 				 * congestion avoidance phase. The
3256 				 * calculations in this function
3257 				 * assume that snd_una is not updated yet.
3258 				 */
3259 				if (CC_ALGO(tp)->congestion_avd != NULL) {
3260 					CC_ALGO(tp)->congestion_avd(tp, th);
3261 				}
3262 				tcp_ccdbg_trace(tp, th, TCP_CC_INSEQ_ACK_RCVD);
3263 				sbdrop(&so->so_snd, acked);
3264 				tcp_sbsnd_trim(&so->so_snd);
3265 
3266 				if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
3267 				    SEQ_LEQ(th->th_ack, tp->snd_recover)) {
3268 					tp->snd_recover = th->th_ack - 1;
3269 				}
3270 
3271 				tcp_update_snd_una(tp, th->th_ack);
3272 
3273 				TCP_RESET_REXMT_STATE(tp);
3274 
3275 				/*
3276 				 * pull snd_wl2 up to prevent seq wrap relative
3277 				 * to th_ack.
3278 				 */
3279 				tp->snd_wl2 = th->th_ack;
3280 
3281 				if (tp->t_dupacks > 0) {
3282 					tp->t_dupacks = 0;
3283 					tp->t_rexmtthresh = tcprexmtthresh;
3284 				}
3285 
3286 				tp->sackhint.sack_bytes_acked = 0;
3287 
3288 				/*
3289 				 * If all outstanding data are acked, stop
3290 				 * retransmit timer, otherwise restart timer
3291 				 * using current (possibly backed-off) value.
3292 				 * If process is waiting for space,
3293 				 * wakeup/selwakeup/signal.  If data
3294 				 * are ready to send, let tcp_output
3295 				 * decide between more output or persist.
3296 				 */
3297 				if (tp->snd_una == tp->snd_max) {
3298 					tp->t_timer[TCPT_REXMT] = 0;
3299 					tp->t_timer[TCPT_PTO] = 0;
3300 					tp->t_timer[TCPT_REORDER] = 0;
3301 					tcp_rack_reset_segs_retransmitted(tp);
3302 				} else if (tp->t_timer[TCPT_PERSIST] == 0) {
3303 					tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
3304 				}
3305 				if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
3306 				    !TCP_DSACK_SEQ_IN_WINDOW(tp,
3307 				    tp->t_dsack_lastuna, tp->snd_una)) {
3308 					tcp_rxtseg_clean(tp);
3309 				}
3310 
3311 				if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
3312 				    tp->t_bwmeas != NULL) {
3313 					tcp_bwmeas_check(tp);
3314 				}
3315 
3316 				write_wakeup = 1;
3317 				if (!SLIST_EMPTY(&tp->t_notify_ack)) {
3318 					tcp_notify_acknowledgement(tp, so);
3319 				}
3320 
3321 				if ((so->so_snd.sb_cc) || (tp->t_flags & TF_ACKNOW)) {
3322 					(void) tcp_output(tp);
3323 				}
3324 
3325 				tcp_tfo_rcv_ack(tp, th);
3326 
3327 				m_freem(m);
3328 
3329 				tcp_check_timer_state(tp);
3330 
3331 				tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3332 
3333 				socket_unlock(so, 1);
3334 				KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3335 				return;
3336 			}
3337 		} else if (th->th_ack == tp->snd_una && LIST_EMPTY(&tp->t_segq) &&
3338 		    tlen <= tcp_sbspace(tp)) {
3339 			/*
3340 			 * this is a pure, in-sequence data packet
3341 			 * with nothing on the reassembly queue and
3342 			 * we have enough buffer space to take it.
3343 			 */
3344 
3345 			/* Clean receiver SACK report if present */
3346 			if (SACK_ENABLED(tp) && tp->rcv_numsacks) {
3347 				tcp_clean_sackreport(tp);
3348 			}
3349 			++tcpstat.tcps_preddat;
3350 			tp->rcv_nxt += tlen;
3351 			/* Update highest received sequence and its timestamp */
3352 			if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
3353 				tp->rcv_high = tp->rcv_nxt;
3354 				if (to.to_flags & TOF_TS) {
3355 					tp->tsv_high = to.to_tsval;
3356 				}
3357 			}
3358 
3359 			/*
3360 			 * Pull snd_wl1 up to prevent seq wrap relative to
3361 			 * th_seq.
3362 			 */
3363 			tp->snd_wl1 = th->th_seq;
3364 			/*
3365 			 * Pull rcv_up up to prevent seq wrap relative to
3366 			 * rcv_nxt.
3367 			 */
3368 			tp->rcv_up = tp->rcv_nxt;
3369 			TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
3370 			tcpstat.tcps_rcvbyte += tlen;
3371 			if (nstat_collect) {
3372 				INP_ADD_STAT(inp, ifnet_count_type,
3373 				    rxpackets, 1);
3374 				INP_ADD_STAT(inp, ifnet_count_type, rxbytes,
3375 				    tlen);
3376 				inp_set_activity_bitmap(inp);
3377 			}
3378 
3379 			/* Calculate the RTT on the receiver */
3380 			tcp_compute_rcv_rtt(tp, &to, th);
3381 
3382 			tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
3383 			if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.data_rcvd != NULL) {
3384 				tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
3385 			}
3386 
3387 			/*
3388 			 * Add data to socket buffer.
3389 			 */
3390 			so_recv_data_stat(so, m, 0);
3391 			m_adj(m, drop_hdrlen);  /* delayed header drop */
3392 
3393 			if (isipv6) {
3394 				memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
3395 				ip6 = (struct ip6_hdr *)&saved_hdr[0];
3396 			} else {
3397 				memcpy(&saved_hdr, ip, ip->ip_hl << 2);
3398 				ip = (struct ip *)&saved_hdr[0];
3399 			}
3400 			memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
3401 
3402 			if (th->th_flags & TH_PUSH) {
3403 				tp->t_flagsext |= TF_LAST_IS_PSH;
3404 			} else {
3405 				tp->t_flagsext &= ~TF_LAST_IS_PSH;
3406 			}
3407 
3408 			if (sbappendstream_rcvdemux(so, m)) {
3409 				mptcp_handle_input(so);
3410 				read_wakeup = 1;
3411 			}
3412 			th = &saved_tcphdr;
3413 
3414 			if (isipv6) {
3415 				KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3416 				    (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
3417 				    th->th_seq, th->th_ack, th->th_win);
3418 			} else {
3419 				KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
3420 				    (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
3421 				    th->th_seq, th->th_ack, th->th_win);
3422 			}
3423 			TCP_INC_VAR(tp->t_unacksegs, segment_count);
3424 			if (DELAY_ACK(tp, th)) {
3425 				if ((tp->t_flags & TF_DELACK) == 0) {
3426 					tp->t_flags |= TF_DELACK;
3427 					tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3428 				}
3429 			} else {
3430 				tp->t_flags |= TF_ACKNOW;
3431 				tcp_output(tp);
3432 			}
3433 
3434 			tcp_adaptive_rwtimo_check(tp, tlen);
3435 
3436 			if (tlen > 0) {
3437 				tcp_tfo_rcv_data(tp);
3438 			}
3439 
3440 			tcp_check_timer_state(tp);
3441 
3442 			tcp_handle_wakeup(so, read_wakeup, write_wakeup);
3443 
3444 			socket_unlock(so, 1);
3445 			KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
3446 			return;
3447 		}
3448 	}
3449 
3450 	/*
3451 	 * Calculate amount of space in receive window,
3452 	 * and then do TCP input processing.
3453 	 * Receive window is amount of space in rcv queue,
3454 	 * but not less than advertised window.
3455 	 */
3456 	socket_lock_assert_owned(so);
3457 	win = tcp_sbspace(tp);
3458 	if (win < 0) {
3459 		win = 0;
3460 	} else { /* clip rcv window to 4K for modems */
3461 		if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0) {
3462 			win = min(win, slowlink_wsize);
3463 		}
3464 	}
3465 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
3466 #if MPTCP
3467 	/*
3468 	 * Ensure that the subflow receive window isn't greater
3469 	 * than the connection level receive window.
3470 	 */
3471 	if ((tp->t_mpflags & TMPF_MPTCP_TRUE) && (mp_tp = tptomptp(tp))) {
3472 		socket_lock_assert_owned(mptetoso(mp_tp->mpt_mpte));
3473 		int64_t recwin_conn = (int64_t)(mp_tp->mpt_rcvadv - mp_tp->mpt_rcvnxt);
3474 
3475 		VERIFY(recwin_conn < INT32_MAX && recwin_conn > INT32_MIN);
3476 		if (recwin_conn > 0 && tp->rcv_wnd > (uint32_t)recwin_conn) {
3477 			tp->rcv_wnd = (uint32_t)recwin_conn;
3478 			tcpstat.tcps_mp_reducedwin++;
3479 		}
3480 	}
3481 #endif /* MPTCP */
3482 
3483 	switch (tp->t_state) {
3484 	/*
3485 	 * Initialize tp->rcv_nxt, and tp->irs, select an initial
3486 	 * tp->iss, and send a segment:
3487 	 *		<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3488 	 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
3489 	 * Fill in remote peer address fields if not previously specified.
3490 	 * Enter SYN_RECEIVED state, and process any other fields of this
3491 	 * segment in this state.
3492 	 */
3493 	case TCPS_LISTEN: {
3494 		struct sockaddr_in *sin;
3495 		struct sockaddr_in6 *sin6;
3496 		int error = 0;
3497 
3498 		socket_lock_assert_owned(so);
3499 
3500 		/* Clear the logging flags inherited from the listening socket */
3501 		inp->inp_log_flags = 0;
3502 		inp->inp_flags2 |= INP2_LOGGED_SUMMARY;
3503 
3504 		if (__improbable(inp->inp_flags2 & INP2_BIND_IN_PROGRESS)) {
3505 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN bind in progress");
3506 			goto drop;
3507 		}
3508 		inp_enter_bind_in_progress(so);
3509 
3510 		if (isipv6) {
3511 			sin6 = kalloc_type(struct sockaddr_in6, Z_NOWAIT | Z_ZERO);
3512 			if (sin6 == NULL) {
3513 				error = ENOMEM;
3514 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3515 				goto pcbconnect_done;
3516 			}
3517 			sin6->sin6_family = AF_INET6;
3518 			sin6->sin6_len = sizeof(*sin6);
3519 			sin6->sin6_addr = ip6->ip6_src;
3520 			sin6->sin6_port = th->th_sport;
3521 			if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
3522 				sin6->sin6_scope_id = ip6_input_getsrcifscope(m);
3523 			}
3524 			laddr6 = inp->in6p_laddr;
3525 			uint32_t lifscope = inp->inp_lifscope;
3526 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
3527 				inp->in6p_laddr = ip6->ip6_dst;
3528 				inp->inp_lifscope = in6_addr2scopeid(ifp, &inp->in6p_laddr);
3529 				in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3530 			}
3531 			if ((error = in6_pcbconnect(inp, SA(sin6), kernel_proc)) != 0) {
3532 				inp->in6p_laddr = laddr6;
3533 				kfree_type(struct sockaddr_in6, sin6);
3534 				inp->inp_lifscope = lifscope;
3535 				in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
3536 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in6_pcbconnect failed");
3537 				goto pcbconnect_done;
3538 			}
3539 			kfree_type(struct sockaddr_in6, sin6);
3540 		} else {
3541 			socket_lock_assert_owned(so);
3542 			sin = kalloc_type(struct sockaddr_in, Z_NOWAIT);
3543 			if (sin == NULL) {
3544 				error = ENOMEM;
3545 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "LISTEN kalloc_type failed");
3546 				goto pcbconnect_done;
3547 			}
3548 			sin->sin_family = AF_INET;
3549 			sin->sin_len = sizeof(*sin);
3550 			sin->sin_addr = ip->ip_src;
3551 			sin->sin_port = th->th_sport;
3552 			bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
3553 			laddr = inp->inp_laddr;
3554 			if (inp->inp_laddr.s_addr == INADDR_ANY) {
3555 				inp->inp_laddr = ip->ip_dst;
3556 			}
3557 			if ((error = in_pcbconnect(inp, SA(sin), kernel_proc, IFSCOPE_NONE, NULL)) != 0) {
3558 				inp->inp_laddr = laddr;
3559 				kfree_type(struct sockaddr_in, sin);
3560 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, " LISTEN in_pcbconnect failed");
3561 				goto pcbconnect_done;
3562 			}
3563 			kfree_type(struct sockaddr_in, sin);
3564 		}
3565 pcbconnect_done:
3566 		inp_exit_bind_in_progress(so);
3567 		if (error != 0) {
3568 			goto drop;
3569 		}
3570 
3571 		tcp_dooptions(tp, optp, optlen, th, &to);
3572 		tcp_finalize_options(tp, &to, ifscope);
3573 
3574 		if (TFO_ENABLED(tp) && tcp_tfo_syn(tp, &to)) {
3575 			isconnected = TRUE;
3576 		}
3577 
3578 		if (iss) {
3579 			tp->iss = iss;
3580 		} else {
3581 			tp->iss = tcp_new_isn(tp);
3582 		}
3583 		tp->irs = th->th_seq;
3584 		tcp_sendseqinit(tp);
3585 		tcp_rcvseqinit(tp);
3586 		tp->snd_recover = tp->snd_una;
3587 		/*
3588 		 * Initialization of the tcpcb for transaction;
3589 		 *   set SND.WND = SEG.WND,
3590 		 *   initialize CCsend and CCrecv.
3591 		 */
3592 		tp->snd_wnd = tiwin;    /* initial send-window */
3593 		tp->max_sndwnd = tp->snd_wnd;
3594 		tp->t_flags |= TF_ACKNOW;
3595 		tp->t_unacksegs = 0;
3596 		tp->t_unacksegs_ce = 0;
3597 		DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
3598 		    struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
3599 		TCP_LOG_STATE(tp, TCPS_SYN_RECEIVED);
3600 		tp->t_state = TCPS_SYN_RECEIVED;
3601 		tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
3602 		    TCP_CONN_KEEPINIT(tp));
3603 		tp->t_connect_time = tcp_now;
3604 		dropsocket = 0;         /* committed to socket */
3605 
3606 		if (inp->inp_flowhash == 0) {
3607 			inp_calc_flowhash(inp);
3608 			ASSERT(inp->inp_flowhash != 0);
3609 		}
3610 		/* update flowinfo - RFC 6437 */
3611 		if (inp->inp_flow == 0 &&
3612 		    inp->in6p_flags & IN6P_AUTOFLOWLABEL) {
3613 			inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
3614 			inp->inp_flow |=
3615 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
3616 		}
3617 
3618 		/* reset the incomp processing flag */
3619 		so->so_flags &= ~(SOF_INCOMP_INPROGRESS);
3620 		tcpstat.tcps_accepts++;
3621 
3622 		int ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
3623 		tcp_input_process_accecn_syn(tp, ace_flags, ip_ecn);
3624 
3625 		/*
3626 		 * The address and connection state are finalized
3627 		 */
3628 		TCP_LOG_CONNECT(tp, false, 0);
3629 
3630 		tcp_add_fsw_flow(tp, ifp);
3631 
3632 		goto trimthenstep6;
3633 	}
3634 
3635 	/*
3636 	 * If the state is SYN_RECEIVED and the seg contains an ACK,
3637 	 * but not for our SYN/ACK, send a RST.
3638 	 */
3639 	case TCPS_SYN_RECEIVED:
3640 		if ((thflags & TH_ACK) &&
3641 		    (SEQ_LEQ(th->th_ack, tp->snd_una) ||
3642 		    SEQ_GT(th->th_ack, tp->snd_max))) {
3643 			IF_TCP_STATINC(ifp, ooopacket);
3644 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad ACK");
3645 			goto dropwithreset;
3646 		}
3647 
3648 		/*
3649 		 * In SYN_RECEIVED state, if we recv some SYNS with
3650 		 * window scale and others without, window scaling should
3651 		 * be disabled. Otherwise the window advertised will be
3652 		 * lower if we assume scaling and the other end does not.
3653 		 */
3654 		if ((thflags & TH_SYN) &&
3655 		    (tp->irs == th->th_seq) &&
3656 		    !(to.to_flags & TOF_SCALE)) {
3657 			tp->t_flags &= ~TF_RCVD_SCALE;
3658 		}
3659 		break;
3660 
3661 	/*
3662 	 * If the state is SYN_SENT:
3663 	 *	if seg contains an ACK, but not for our SYN, drop the input.
3664 	 *	if seg contains a RST, then drop the connection.
3665 	 *	if seg does not contain SYN, then drop it.
3666 	 * Otherwise this is an acceptable SYN segment
3667 	 *	initialize tp->rcv_nxt and tp->irs
3668 	 *	if seg contains ack then advance tp->snd_una
3669 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
3670 	 *	arrange for segment to be acked (eventually)
3671 	 *	continue processing rest of data/controls, beginning with URG
3672 	 */
3673 	case TCPS_SYN_SENT:
3674 		if ((thflags & TH_ACK) &&
3675 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
3676 		    SEQ_GT(th->th_ack, tp->snd_max))) {
3677 			IF_TCP_STATINC(ifp, ooopacket);
3678 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT bad ACK");
3679 			goto dropwithreset;
3680 		}
3681 		if (thflags & TH_RST) {
3682 			if ((thflags & TH_ACK) != 0) {
3683 				if (TFO_ENABLED(tp) &&
3684 				    !(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE)) {
3685 					tcp_heuristic_tfo_rst(tp);
3686 				}
3687 				if ((tp->ecn_flags & (TE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_SETUPSENT ||
3688 				    (tp->ecn_flags & (TE_ACE_SETUPSENT | TE_RCVD_SYN_RST)) == TE_ACE_SETUPSENT) {
3689 					/*
3690 					 * On local connections, send
3691 					 * non-ECN syn one time before
3692 					 * dropping the connection
3693 					 */
3694 					if (tp->t_flags & TF_LOCAL) {
3695 						tp->ecn_flags |= TE_RCVD_SYN_RST;
3696 						drop_reason = DROP_REASON_TCP_RST;
3697 						goto drop;
3698 					} else {
3699 						tcp_heuristic_ecn_synrst(tp);
3700 					}
3701 				}
3702 				soevent(so,
3703 				    (SO_FILT_HINT_LOCKED |
3704 				    SO_FILT_HINT_CONNRESET));
3705 				tp = tcp_drop(tp, ECONNREFUSED);
3706 			}
3707 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT got RST");
3708 			drop_reason = DROP_REASON_TCP_RST;
3709 			goto drop;
3710 		}
3711 		if ((thflags & TH_SYN) == 0) {
3712 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_SENT no SYN");
3713 			goto drop;
3714 		}
3715 		tp->snd_wnd = th->th_win;       /* initial send window */
3716 		tp->max_sndwnd = tp->snd_wnd;
3717 
3718 		tp->irs = th->th_seq;
3719 		tcp_rcvseqinit(tp);
3720 		if (thflags & TH_ACK) {
3721 			/* Client processes SYN-ACK */
3722 			tcpstat.tcps_connects++;
3723 
3724 			const uint32_t ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
3725 
3726 			if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE)) {
3727 				/* Receiving Any|0|1 is classic ECN-setup SYN-ACK */
3728 				tp->ecn_flags |= TE_SETUPRECEIVED;
3729 				if (TCP_ECN_ENABLED(tp)) {
3730 					tcp_heuristic_ecn_success(tp);
3731 					tcpstat.tcps_ecn_client_success++;
3732 				}
3733 
3734 				if (tp->ecn_flags & TE_ACE_SETUPSENT) {
3735 					/*
3736 					 * Sent AccECN SYN but received classic ECN SYN-ACK
3737 					 * Set classic ECN related flags
3738 					 */
3739 					tp->ecn_flags |= (TE_SETUPSENT | TE_SENDIPECT);
3740 					tp->ecn_flags &= ~TE_ACE_SETUPSENT;
3741 					if (tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_enabled) {
3742 						tp->t_client_accecn_state = tcp_connection_client_classic_ecn_available;
3743 					}
3744 				}
3745 			} else if (TCP_ACC_ECN_ENABLED(tp) && ace_flags != 0 &&
3746 			    ace_flags != TH_ACE) {
3747 				/* Initialize sender side packet & byte counters */
3748 				tp->t_aecn.t_snd_ce_packets = 5;
3749 				tp->t_aecn.t_snd_ect1_bytes = tp->t_aecn.t_snd_ect0_bytes = 1;
3750 				tp->t_aecn.t_snd_ce_bytes = 0;
3751 				tp->ecn_flags |= TE_ACE_FINAL_ACK_3WHS;
3752 				/*
3753 				 * Client received AccECN SYN-ACK that reflects the state (ECN)
3754 				 * in which SYN packet was delivered. This helps to detect if
3755 				 * there was mangling of the SYN packet on the path. Currently, we
3756 				 * only send Not-ECT on SYN packets. So, we should set Not-ECT in
3757 				 * all packets if we receive any encoding other than 0|TH_CWR|0.
3758 				 * If 0|0|0 and 1|1|1 were received, fail Accurate ECN negotiation
3759 				 * by not setting TE_ACE_SETUPRECEIVED.
3760 				 */
3761 				uint32_t ecn_flags = TE_ACE_SETUPRECEIVED;
3762 				if (TCP_L4S_ENABLED(tp)) {
3763 					ecn_flags |= TE_SENDIPECT;
3764 				}
3765 				switch (ace_flags) {
3766 				case (0 | TH_CWR | 0):
3767 					/* Non-ECT SYN was delivered */
3768 					tp->ecn_flags |= ecn_flags;
3769 					tcpstat.tcps_ecn_ace_syn_not_ect++;
3770 					tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success;
3771 					break;
3772 				case (0 | TH_CWR | TH_ECE):
3773 					/* ECT1 SYN was delivered */
3774 					tp->ecn_flags |= ecn_flags;
3775 					/* Mangling detected, set Non-ECT on outgoing packets */
3776 					tp->ecn_flags &= ~TE_SENDIPECT;
3777 					tcpstat.tcps_ecn_ace_syn_ect1++;
3778 					tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success_ect_mangling_detected;
3779 					break;
3780 				case (TH_AE | 0 | 0):
3781 					/* ECT0 SYN was delivered */
3782 					tp->ecn_flags |= ecn_flags;
3783 					/* Mangling detected, set Non-ECT on outgoing packets */
3784 					tp->ecn_flags &= ~TE_SENDIPECT;
3785 					tcpstat.tcps_ecn_ace_syn_ect0++;
3786 					tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success_ect_mangling_detected;
3787 					break;
3788 				case (TH_AE | TH_CWR | 0):
3789 					/* CE SYN was delivered */
3790 					tp->ecn_flags |= ecn_flags;
3791 					/* Mangling detected, set Non-ECT on outgoing packets */
3792 					tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_success_ect_mangling_detected;
3793 					tp->ecn_flags &= ~TE_SENDIPECT;
3794 					/*
3795 					 * Although we don't send ECT SYN yet, it is possible that
3796 					 * a network element changed Not-ECT to ECT and later there
3797 					 * was congestion at another network element that set it to CE.
3798 					 * To keep it simple, we will consider this as a congestion event
3799 					 * for the congestion controller.
3800 					 * If a TCP client in AccECN mode receives CE feedback in the TCP
3801 					 * flags of a SYN/ACK, it MUST NOT increment s.cep.
3802 					 */
3803 					tp->snd_cwnd = 2 * tp->t_maxseg;
3804 					tcpstat.tcps_ecn_ace_syn_ce++;
3805 					break;
3806 				default:
3807 					break;
3808 				}
3809 				if (TCP_ECN_ENABLED(tp)) {
3810 					tcp_heuristic_ecn_success(tp);
3811 					tcpstat.tcps_ecn_client_success++;
3812 				}
3813 				/*
3814 				 * A TCP client in AccECN mode MUST feed back which of the 4
3815 				 * possible values of the IP-ECN field that was received in the
3816 				 * SYN/ACK. Set the setup flag for final ACK accordingly.
3817 				 * We will initialize r.cep, r.e1b, r.e0b first and then increment
3818 				 * if CE was set on the IP-ECN field of the SYN-ACK.
3819 				 */
3820 				tp->t_aecn.t_rcv_ce_packets = 5;
3821 				tp->t_aecn.t_rcv_ect0_bytes = tp->t_aecn.t_rcv_ect1_bytes = 1;
3822 				tp->t_aecn.t_rcv_ce_bytes = 0;
3823 
3824 				/* Increment packet & byte counters based on IP-ECN */
3825 				tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
3826 
3827 				switch (ip_ecn) {
3828 				case IPTOS_ECN_NOTECT:
3829 					/* Not-ECT SYN-ACK was received */
3830 					tp->ecn_flags |= TE_ACE_SETUP_NON_ECT;
3831 					break;
3832 				case IPTOS_ECN_ECT1:
3833 					/* ECT1 SYN-ACK was received */
3834 					tp->ecn_flags |= TE_ACE_SETUP_ECT1;
3835 					break;
3836 				case IPTOS_ECN_ECT0:
3837 					/* ECT0 SYN-ACK was received */
3838 					tp->ecn_flags |= TE_ACE_SETUP_ECT0;
3839 					break;
3840 				case IPTOS_ECN_CE:
3841 					tp->ecn_flags |= TE_ACE_SETUP_CE;
3842 					break;
3843 				}
3844 				/* Update the time for this newly SYN-ACK packet */
3845 				if ((to.to_flags & TOF_TS) != 0 && (to.to_tsecr != 0) &&
3846 				    (tp->t_last_ack_tsecr == 0 || TSTMP_GEQ(to.to_tsecr, tp->t_last_ack_tsecr))) {
3847 					tp->t_last_ack_tsecr = to.to_tsecr;
3848 				}
3849 			} else {
3850 				if ((tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) &&
3851 				    tp->t_rxtshift == 0) {
3852 					tcp_heuristic_ecn_success(tp);
3853 					tcpstat.tcps_ecn_not_supported++;
3854 				}
3855 				if ((tp->ecn_flags & (TE_SETUPSENT | TE_ACE_SETUPSENT)) &&
3856 				    tp->t_rxtshift > 0) {
3857 					tcp_heuristic_ecn_loss(tp);
3858 				}
3859 
3860 				/* non-ECN-setup SYN-ACK */
3861 				tp->ecn_flags &= ~TE_SENDIPECT;
3862 				/*
3863 				 * If Accurate ECN SYN was retransmitted twice and non-ECN SYN-ACK
3864 				 * was received, then we consider it as Accurate ECN blackholing
3865 				 */
3866 				if ((tp->ecn_flags & TE_LOST_SYN) && tp->t_rxtshift <= 2 &&
3867 				    tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_enabled) {
3868 					tp->t_client_accecn_state = tcp_connection_client_accurate_ecn_negotiation_blackholed;
3869 				}
3870 				/*
3871 				 * If SYN wasn't retransmitted twice yet, the server supports neither classic nor
3872 				 * accurate ECN SYN-ACK. Accurate ECN should already be disabled for both half connections
3873 				 * as TE_ACE_SETUPRECEIVED flag is not set.
3874 				 */
3875 				if (tp->t_client_accecn_state == tcp_connection_client_accurate_ecn_feature_enabled) {
3876 					tp->t_client_accecn_state = tcp_connection_client_ecn_not_available;
3877 				}
3878 			}
3879 
3880 			/* Do window scaling on this connection? */
3881 			if (TCP_WINDOW_SCALE_ENABLED(tp)) {
3882 				tp->snd_scale = tp->requested_s_scale;
3883 				tp->rcv_scale = tp->request_r_scale;
3884 			}
3885 
3886 			uint32_t recwin = min(tp->rcv_wnd, TCP_MAXWIN << tp->rcv_scale);
3887 			if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.get_rlwin != NULL) {
3888 				/* For a LBE receiver, also use rledbat_win */
3889 				uint32_t rledbat_win = tcp_cc_rledbat.get_rlwin(tp);
3890 				if (rledbat_win > 0) {
3891 					recwin = min(recwin, rledbat_win);
3892 				}
3893 			}
3894 			tp->rcv_adv += recwin;
3895 
3896 			tp->snd_una++;          /* SYN is acked */
3897 			if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
3898 				tp->snd_nxt = tp->snd_una;
3899 			}
3900 
3901 			/*
3902 			 * We have sent more in the SYN than what is being
3903 			 * acked. (e.g., TFO)
3904 			 * We should restart the sending from what the receiver
3905 			 * has acknowledged immediately.
3906 			 */
3907 			if (SEQ_GT(tp->snd_nxt, th->th_ack)) {
3908 				/*
3909 				 * rdar://problem/33214601
3910 				 * There is a middlebox that acks all but one
3911 				 * byte and still drops the data.
3912 				 */
3913 				if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
3914 				    (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
3915 				    tp->snd_max == th->th_ack + 1 &&
3916 				    tp->snd_max > tp->snd_una + 1) {
3917 					tcp_heuristic_tfo_middlebox(tp);
3918 
3919 					so->so_error = ENODATA;
3920 					soevent(so,
3921 					    (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MP_SUB_ERROR));
3922 
3923 					tp->t_tfo_stats |= TFO_S_ONE_BYTE_PROXY;
3924 				}
3925 
3926 				tp->snd_max = tp->snd_nxt = th->th_ack;
3927 			}
3928 
3929 			/*
3930 			 * If there's data, delay ACK; if there's also a FIN
3931 			 * ACKNOW will be turned on later.
3932 			 */
3933 			TCP_INC_VAR(tp->t_unacksegs, segment_count);
3934 			if (TCP_ACC_ECN_ON(tp) && ip_ecn == IPTOS_ECN_CE) {
3935 				TCP_INC_VAR(tp->t_unacksegs_ce, segment_count);
3936 			}
3937 			if (DELAY_ACK(tp, th) && tlen != 0) {
3938 				if ((tp->t_flags & TF_DELACK) == 0) {
3939 					tp->t_flags |= TF_DELACK;
3940 					tp->t_timer[TCPT_DELACK] = OFFSET_FROM_START(tp, tcp_delack);
3941 				}
3942 			} else {
3943 				tp->t_flags |= TF_ACKNOW;
3944 			}
3945 			/*
3946 			 * Received <SYN,ACK> in SYN_SENT[*] state.
3947 			 * Transitions:
3948 			 *	SYN_SENT  --> ESTABLISHED
3949 			 *	SYN_SENT* --> FIN_WAIT_1
3950 			 */
3951 			tp->t_starttime = tcp_now;
3952 			tcp_sbrcv_tstmp_check(tp);
3953 			if (tp->t_flags & TF_NEEDFIN) {
3954 				DTRACE_TCP4(state__change, void, NULL,
3955 				    struct inpcb *, inp,
3956 				    struct tcpcb *, tp, int32_t,
3957 				    TCPS_FIN_WAIT_1);
3958 				TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
3959 				tp->t_state = TCPS_FIN_WAIT_1;
3960 				tp->t_flags &= ~TF_NEEDFIN;
3961 				thflags &= ~TH_SYN;
3962 
3963 				TCP_LOG_CONNECTION_SUMMARY(tp);
3964 			} else {
3965 				DTRACE_TCP4(state__change, void, NULL,
3966 				    struct inpcb *, inp, struct tcpcb *,
3967 				    tp, int32_t, TCPS_ESTABLISHED);
3968 				TCP_LOG_STATE(tp, TCPS_ESTABLISHED);
3969 				tp->t_state = TCPS_ESTABLISHED;
3970 				tp->t_timer[TCPT_KEEP] =
3971 				    OFFSET_FROM_START(tp,
3972 				    TCP_CONN_KEEPIDLE(tp));
3973 				if (nstat_collect) {
3974 					nstat_route_connect_success(
3975 						inp->inp_route.ro_rt);
3976 				}
3977 				TCP_LOG_CONNECTED(tp, 0);
3978 				/*
3979 				 * The SYN is acknowledged but una is not
3980 				 * updated yet. So pass the value of
3981 				 * ack to compute sndbytes correctly
3982 				 */
3983 				inp_count_sndbytes(inp, th->th_ack);
3984 			}
3985 			tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
3986 #if MPTCP
3987 			/*
3988 			 * Do not send the connect notification for additional
3989 			 * subflows until ACK for 3-way handshake arrives.
3990 			 */
3991 			if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
3992 			    (tp->t_mpflags & TMPF_SENT_JOIN)) {
3993 				isconnected = FALSE;
3994 			} else
3995 #endif /* MPTCP */
3996 			isconnected = TRUE;
3997 
3998 			if ((tp->t_tfo_flags & (TFO_F_COOKIE_REQ | TFO_F_COOKIE_SENT)) ||
3999 			    (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT)) {
4000 				tcp_tfo_synack(tp, &to);
4001 
4002 				if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
4003 				    SEQ_LT(tp->snd_una, th->th_ack)) {
4004 					tp->t_tfo_stats |= TFO_S_SYN_DATA_ACKED;
4005 					tcpstat.tcps_tfo_syn_data_acked++;
4006 #if MPTCP
4007 					if (so->so_flags & SOF_MP_SUBFLOW) {
4008 						so->so_flags1 |= SOF1_TFO_REWIND;
4009 					}
4010 #endif
4011 					tcp_tfo_rcv_probe(tp, tlen);
4012 				}
4013 			}
4014 		} else {
4015 			/*
4016 			 *  Received initial SYN in SYN-SENT[*] state => simul-
4017 			 *  taneous open.
4018 			 *  Do 3-way handshake:
4019 			 *        SYN-SENT -> SYN-RECEIVED
4020 			 *        SYN-SENT* -> SYN-RECEIVED*
4021 			 */
4022 			tp->t_flags |= TF_ACKNOW;
4023 			tp->t_timer[TCPT_REXMT] = 0;
4024 			DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
4025 			    struct tcpcb *, tp, int32_t, TCPS_SYN_RECEIVED);
4026 			TCP_LOG_STATE(tp, TCPS_SYN_RECEIVED);
4027 			tp->t_state = TCPS_SYN_RECEIVED;
4028 
4029 			/*
4030 			 * During simultaneous open, TFO should not be used.
4031 			 * So, we disable it here, to prevent that data gets
4032 			 * sent on the SYN/ACK.
4033 			 */
4034 			tcp_disable_tfo(tp);
4035 		}
4036 
4037 trimthenstep6:
4038 		/*
4039 		 * Advance th->th_seq to correspond to first data byte.
4040 		 * If data, trim to stay within window,
4041 		 * dropping FIN if necessary.
4042 		 */
4043 		th->th_seq++;
4044 		if (tlen > tp->rcv_wnd) {
4045 			todrop = tlen - tp->rcv_wnd;
4046 			m_adj(m, -todrop);
4047 			tlen = tp->rcv_wnd;
4048 			thflags &= ~TH_FIN;
4049 			tcpstat.tcps_rcvpackafterwin++;
4050 			tcpstat.tcps_rcvbyteafterwin += todrop;
4051 		}
4052 		tp->snd_wl1 = th->th_seq - 1;
4053 		tp->rcv_up = th->th_seq;
4054 		/*
4055 		 *  Client side of transaction: already sent SYN and data.
4056 		 *  If the remote host used T/TCP to validate the SYN,
4057 		 *  our data will be ACK'd; if so, enter normal data segment
4058 		 *  processing in the middle of step 5, ack processing.
4059 		 *  Otherwise, goto step 6.
4060 		 */
4061 		if (thflags & TH_ACK) {
4062 			goto process_ACK;
4063 		}
4064 		goto step6;
4065 	/*
4066 	 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
4067 	 *      do normal processing.
4068 	 *
4069 	 * NB: Leftover from RFC1644 T/TCP.  Cases to be reused later.
4070 	 */
4071 	case TCPS_LAST_ACK:
4072 	case TCPS_CLOSING:
4073 	case TCPS_TIME_WAIT:
4074 		break;  /* continue normal processing */
4075 
4076 	/* Received a SYN while connection is already established.
4077 	 * This is a "half open connection and other anomalies" described
4078 	 * in RFC793 page 34, send an ACK so the remote reset the connection
4079 	 * or recovers by adjusting its sequence numbering. Sending an ACK is
4080 	 * in accordance with RFC 5961 Section 4.2
4081 	 *
4082 	 * For Accurate ECN, if we receive a packet with SYN in ESTABLISHED
4083 	 * state, we don't send the handshake encoding.
4084 	 */
4085 	case TCPS_ESTABLISHED:
4086 		if (thflags & TH_SYN && tlen <= 0) {
4087 			/* Drop the packet silently if we have reached the limit */
4088 			if (tcp_is_ack_ratelimited(tp)) {
4089 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
4090 				goto drop;
4091 			} else {
4092 				/* Send challenge ACK */
4093 				tcpstat.tcps_synchallenge++;
4094 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
4095 				goto dropafterack;
4096 			}
4097 		}
4098 		break;
4099 	}
4100 
4101 	/*
4102 	 * States other than LISTEN or SYN_SENT.
4103 	 * First check the RST flag and sequence number since reset segments
4104 	 * are exempt from the timestamp and connection count tests.  This
4105 	 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
4106 	 * below which allowed reset segments in half the sequence space
4107 	 * to fall though and be processed (which gives forged reset
4108 	 * segments with a random sequence number a 50 percent chance of
4109 	 * killing a connection).
4110 	 * Then check timestamp, if present.
4111 	 * Then check the connection count, if present.
4112 	 * Then check that at least some bytes of segment are within
4113 	 * receive window.  If segment begins before rcv_nxt,
4114 	 * drop leading data (and SYN); if nothing left, just ack.
4115 	 *
4116 	 *
4117 	 * If the RST bit is set, check the sequence number to see
4118 	 * if this is a valid reset segment.
4119 	 * RFC 793 page 37:
4120 	 *   In all states except SYN-SENT, all reset (RST) segments
4121 	 *   are validated by checking their SEQ-fields.  A reset is
4122 	 *   valid if its sequence number is in the window.
4123 	 * Note: this does not take into account delayed ACKs, so
4124 	 *   we should test against last_ack_sent instead of rcv_nxt.
4125 	 *   The sequence number in the reset segment is normally an
4126 	 *   echo of our outgoing acknowlegement numbers, but some hosts
4127 	 *   send a reset with the sequence number at the rightmost edge
4128 	 *   of our receive window, and we have to handle this case.
4129 	 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
4130 	 *   that brute force RST attacks are possible.  To combat this,
4131 	 *   we use a much stricter check while in the ESTABLISHED state,
4132 	 *   only accepting RSTs where the sequence number is equal to
4133 	 *   last_ack_sent.  In all other states (the states in which a
4134 	 *   RST is more likely), the more permissive check is used.
4135 	 * RFC 5961 Section 3.2: if the RST bit is set, sequence # is
4136 	 *    within the receive window and last_ack_sent == seq,
4137 	 *    then reset the connection. Otherwise if the seq doesn't
4138 	 *    match last_ack_sent, TCP must send challenge ACK. Perform
4139 	 *    rate limitation when sending the challenge ACK.
4140 	 * If we have multiple segments in flight, the intial reset
4141 	 * segment sequence numbers will be to the left of last_ack_sent,
4142 	 * but they will eventually catch up.
4143 	 * In any case, it never made sense to trim reset segments to
4144 	 * fit the receive window since RFC 1122 says:
4145 	 *   4.2.2.12  RST Segment: RFC-793 Section 3.4
4146 	 *
4147 	 *    A TCP SHOULD allow a received RST segment to include data.
4148 	 *
4149 	 *    DISCUSSION
4150 	 *         It has been suggested that a RST segment could contain
4151 	 *         ASCII text that encoded and explained the cause of the
4152 	 *         RST.  No standard has yet been established for such
4153 	 *         data.
4154 	 *
4155 	 * If the reset segment passes the sequence number test examine
4156 	 * the state:
4157 	 *    SYN_RECEIVED STATE:
4158 	 *	If passive open, return to LISTEN state.
4159 	 *	If active open, inform user that connection was refused.
4160 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
4161 	 *	Inform user that connection was reset, and close tcb.
4162 	 *    CLOSING, LAST_ACK STATES:
4163 	 *	Close the tcb.
4164 	 *    TIME_WAIT STATE:
4165 	 *	Drop the segment - see Stevens, vol. 2, p. 964 and
4166 	 *      RFC 1337.
4167 	 *
4168 	 *      Radar 4803931: Allows for the case where we ACKed the FIN but
4169 	 *                     there is already a RST in flight from the peer.
4170 	 *                     In that case, accept the RST for non-established
4171 	 *                     state if it's one off from last_ack_sent.
4172 	 *
4173 	 * Also be lenient in closing states to allow last_ack_sent and also
4174 	 * last_ack_sent - 1 in case there is a lot of delay upstream
4175 	 * and it is an older segment that is triggering the RST
4176 	 */
4177 	if (thflags & TH_RST) {
4178 		if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
4179 		    SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
4180 		    ((tp->rcv_wnd == 0 || tp->t_state >= TCPS_CLOSE_WAIT) &&
4181 		    ((tp->last_ack_sent == th->th_seq) ||
4182 		    (tp->last_ack_sent - 1 == th->th_seq)))) {
4183 			if (tp->last_ack_sent == th->th_seq || tp->last_ack_sent - 1 == th->th_seq) {
4184 				switch (tp->t_state) {
4185 				case TCPS_SYN_RECEIVED:
4186 					IF_TCP_STATINC(ifp, rstinsynrcv);
4187 					so->so_error = ECONNREFUSED;
4188 					goto close;
4189 
4190 				case TCPS_ESTABLISHED:
4191 					if ((TCP_ECN_ENABLED(tp) || TCP_ACC_ECN_ON(tp)) &&
4192 					    tp->snd_una == tp->iss + 1 &&
4193 					    SEQ_GT(tp->snd_max, tp->snd_una)) {
4194 						/*
4195 						 * If the first data packet on an
4196 						 * ECN connection, receives a RST
4197 						 * increment the heuristic
4198 						 */
4199 						tcp_heuristic_ecn_droprst(tp);
4200 					}
4201 					OS_FALLTHROUGH;
4202 				case TCPS_FIN_WAIT_1:
4203 				case TCPS_CLOSE_WAIT:
4204 				case TCPS_FIN_WAIT_2:
4205 					so->so_error = ECONNRESET;
4206 close:
4207 					soevent(so,
4208 					    (SO_FILT_HINT_LOCKED |
4209 					    SO_FILT_HINT_CONNRESET));
4210 
4211 					tcpstat.tcps_drops++;
4212 					tp = tcp_close(tp);
4213 					break;
4214 
4215 				case TCPS_CLOSING:
4216 				case TCPS_LAST_ACK:
4217 					tp = tcp_close(tp);
4218 					break;
4219 
4220 				case TCPS_TIME_WAIT:
4221 					break;
4222 				}
4223 			} else {
4224 				tcpstat.tcps_badrst++;
4225 				/* Drop if we have reached the ACK limit */
4226 				if (tcp_is_ack_ratelimited(tp)) {
4227 					TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 rate limited");
4228 					goto drop;
4229 				} else {
4230 					/* Send challenge ACK */
4231 					tcpstat.tcps_rstchallenge++;
4232 					TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "ESTABLISHED rfc5961 challenge ACK");
4233 					goto dropafterack;
4234 				}
4235 			}
4236 		}
4237 		goto drop;
4238 	}
4239 
4240 	/*
4241 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
4242 	 * and it's less than ts_recent, drop it.
4243 	 */
4244 	if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
4245 	    TSTMP_LT(to.to_tsval, tp->ts_recent)) {
4246 		/* Check to see if ts_recent is over 24 days old.  */
4247 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
4248 			/*
4249 			 * Invalidate ts_recent.  If this segment updates
4250 			 * ts_recent, the age will be reset later and ts_recent
4251 			 * will get a valid value.  If it does not, setting
4252 			 * ts_recent to zero will at least satisfy the
4253 			 * requirement that zero be placed in the timestamp
4254 			 * echo reply when ts_recent isn't valid.  The
4255 			 * age isn't reset until we get a valid ts_recent
4256 			 * because we don't want out-of-order segments to be
4257 			 * dropped when ts_recent is old.
4258 			 */
4259 			tp->ts_recent = 0;
4260 		} else {
4261 			tcpstat.tcps_rcvduppack++;
4262 			tcpstat.tcps_rcvdupbyte += tlen;
4263 			tp->t_pawsdrop++;
4264 			tcpstat.tcps_pawsdrop++;
4265 
4266 			/*
4267 			 * PAWS-drop when ECN is being used? That indicates
4268 			 * that ECT-marked packets take a different path, with
4269 			 * different congestion-characteristics.
4270 			 *
4271 			 * Only fallback when we did send less than 2GB as PAWS
4272 			 * really has no reason to kick in earlier.
4273 			 */
4274 			if ((TCP_ECN_ENABLED(tp) || TCP_ACC_ECN_ON(tp)) &&
4275 			    inp->inp_stat->rxbytes < 2147483648) {
4276 				INP_INC_IFNET_STAT(inp, ecn_fallback_reorder);
4277 				tcpstat.tcps_ecn_fallback_reorder++;
4278 				tcp_heuristic_ecn_aggressive(tp);
4279 			}
4280 
4281 			if (nstat_collect) {
4282 				nstat_route_rx(tp->t_inpcb->inp_route.ro_rt,
4283 				    1, tlen, NSTAT_RX_FLAG_DUPLICATE);
4284 				INP_ADD_STAT(inp, ifnet_count_type,
4285 				    rxpackets, 1);
4286 				INP_ADD_STAT(inp, ifnet_count_type,
4287 				    rxbytes, tlen);
4288 				tp->t_stat.rxduplicatebytes += tlen;
4289 				inp_set_activity_bitmap(inp);
4290 			}
4291 			if (tlen > 0) {
4292 				goto dropafterack;
4293 			}
4294 			goto drop;
4295 		}
4296 	}
4297 
4298 	/*
4299 	 * In the SYN-RECEIVED state, validate that the packet belongs to
4300 	 * this connection before trimming the data to fit the receive
4301 	 * window.  Check the sequence number versus IRS since we know
4302 	 * the sequence numbers haven't wrapped.  This is a partial fix
4303 	 * for the "LAND" DoS attack.
4304 	 */
4305 	if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
4306 		IF_TCP_STATINC(ifp, dospacket);
4307 		TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SYN_RECEIVED bad SEQ");
4308 		goto dropwithreset;
4309 	}
4310 
4311 	/*
4312 	 * Check if there is old data at the beginning of the window
4313 	 * i.e. the sequence number is before rcv_nxt
4314 	 */
4315 	todrop = tp->rcv_nxt - th->th_seq;
4316 	if (todrop > 0) {
4317 		boolean_t is_syn_set = FALSE;
4318 
4319 		if (thflags & TH_SYN) {
4320 			is_syn_set = TRUE;
4321 			thflags &= ~TH_SYN;
4322 			th->th_seq++;
4323 			if (th->th_urp > 1) {
4324 				th->th_urp--;
4325 			} else {
4326 				thflags &= ~TH_URG;
4327 			}
4328 			todrop--;
4329 		}
4330 		/*
4331 		 * Following if statement from Stevens, vol. 2, p. 960.
4332 		 * The amount of duplicate data is greater than or equal
4333 		 * to the size of the segment - entire segment is duplicate
4334 		 */
4335 		if (todrop > tlen
4336 		    || (todrop == tlen && (thflags & TH_FIN) == 0)) {
4337 			/*
4338 			 * Any valid FIN must be to the left of the window.
4339 			 * At this point the FIN must be a duplicate or out
4340 			 * of sequence; drop it.
4341 			 */
4342 			thflags &= ~TH_FIN;
4343 
4344 			/*
4345 			 * Send an ACK to resynchronize and drop any data.
4346 			 * But keep on processing for RST or ACK.
4347 			 *
4348 			 * If the SYN bit was originally set, then only send
4349 			 * an ACK if we are not rate-limiting this connection.
4350 			 */
4351 			if (is_syn_set) {
4352 				if (!tcp_is_ack_ratelimited(tp)) {
4353 					tcpstat.tcps_synchallenge++;
4354 					tp->t_flags |= TF_ACKNOW;
4355 				}
4356 			} else {
4357 				tp->t_flags |= TF_ACKNOW;
4358 			}
4359 
4360 			if (todrop == 1) {
4361 				/* This could be a keepalive */
4362 				soevent(so, SO_FILT_HINT_LOCKED |
4363 				    SO_FILT_HINT_KEEPALIVE);
4364 			}
4365 			todrop = tlen;
4366 			tcpstat.tcps_rcvduppack++;
4367 			tcpstat.tcps_rcvdupbyte += todrop;
4368 		} else {
4369 			tcpstat.tcps_rcvpartduppack++;
4370 			tcpstat.tcps_rcvpartdupbyte += todrop;
4371 		}
4372 
4373 		if (todrop > 1) {
4374 			/*
4375 			 * Note the duplicate data sequence space so that
4376 			 * it can be reported in DSACK option.
4377 			 */
4378 			tp->t_dsack_lseq = th->th_seq;
4379 			tp->t_dsack_rseq = th->th_seq + todrop;
4380 			tp->t_flags |= TF_ACKNOW;
4381 		}
4382 		if (nstat_collect) {
4383 			nstat_route_rx(tp->t_inpcb->inp_route.ro_rt, 1,
4384 			    todrop, NSTAT_RX_FLAG_DUPLICATE);
4385 			INP_ADD_STAT(inp, ifnet_count_type, rxpackets, 1);
4386 			INP_ADD_STAT(inp, ifnet_count_type, rxbytes, todrop);
4387 			tp->t_stat.rxduplicatebytes += todrop;
4388 			inp_set_activity_bitmap(inp);
4389 		}
4390 		drop_hdrlen += todrop;  /* drop from the top afterwards */
4391 		th->th_seq += todrop;
4392 		tlen -= todrop;
4393 		if (th->th_urp > todrop) {
4394 			th->th_urp -= todrop;
4395 		} else {
4396 			thflags &= ~TH_URG;
4397 			th->th_urp = 0;
4398 		}
4399 	}
4400 
4401 	/*
4402 	 * If new data are received on a connection after the user
4403 	 * processes are gone, then RST the other end.
4404 	 * Send also a RST when we received a data segment after we've
4405 	 * sent our FIN when the socket is defunct.
4406 	 * Note that an MPTCP subflow socket would have SS_NOFDREF set
4407 	 * by default. So, if it's an MPTCP-subflow we rather check the
4408 	 * MPTCP-level's socket state for SS_NOFDREF.
4409 	 */
4410 	if (tlen) {
4411 		boolean_t close_it = FALSE;
4412 
4413 		if (!(so->so_flags & SOF_MP_SUBFLOW) && (so->so_state & SS_NOFDREF) &&
4414 		    tp->t_state > TCPS_CLOSE_WAIT) {
4415 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_NOFDREF");
4416 			close_it = TRUE;
4417 		}
4418 
4419 		if ((so->so_flags & SOF_MP_SUBFLOW) && (mptetoso(tptomptp(tp)->mpt_mpte)->so_state & SS_NOFDREF) &&
4420 		    tp->t_state > TCPS_CLOSE_WAIT) {
4421 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_MP_SUBFLOW SS_NOFDREF");
4422 			close_it = TRUE;
4423 		}
4424 
4425 		if ((so->so_flags & SOF_DEFUNCT) && tp->t_state > TCPS_FIN_WAIT_1) {
4426 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SOF_DEFUNCT");
4427 			close_it = TRUE;
4428 		}
4429 
4430 		if (so->so_state & SS_CANTRCVMORE) {
4431 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "SS_CANTRCVMORE");
4432 			close_it = TRUE;
4433 		}
4434 
4435 		if (close_it) {
4436 			tp = tcp_close(tp);
4437 			tcpstat.tcps_rcvafterclose++;
4438 			IF_TCP_STATINC(ifp, cleanup);
4439 			goto dropwithreset;
4440 		}
4441 	}
4442 
4443 	/*
4444 	 * If segment ends after window, drop trailing data
4445 	 * (and PUSH and FIN); if nothing left, just ACK.
4446 	 */
4447 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
4448 	if (todrop > 0) {
4449 		tcpstat.tcps_rcvpackafterwin++;
4450 		if (todrop >= tlen) {
4451 			tcpstat.tcps_rcvbyteafterwin += tlen;
4452 			/*
4453 			 * If a new connection request is received
4454 			 * while in TIME_WAIT, drop the old connection
4455 			 * and start over if the sequence numbers
4456 			 * are above the previous ones.
4457 			 */
4458 			if (thflags & TH_SYN &&
4459 			    tp->t_state == TCPS_TIME_WAIT &&
4460 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
4461 				iss = tcp_new_isn(tp);
4462 				tp = tcp_close(tp);
4463 				socket_unlock(so, 1);
4464 				goto findpcb;
4465 			}
4466 			/*
4467 			 * If window is closed can only take segments at
4468 			 * window edge, and have to drop data and PUSH from
4469 			 * incoming segments.  Continue processing, but
4470 			 * remember to ack.  Otherwise, drop segment
4471 			 * and ack.
4472 			 */
4473 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
4474 				tp->t_flags |= TF_ACKNOW;
4475 				tcpstat.tcps_rcvwinprobe++;
4476 			} else {
4477 				goto dropafterack;
4478 			}
4479 		} else {
4480 			tcpstat.tcps_rcvbyteafterwin += todrop;
4481 		}
4482 		m_adj(m, -todrop);
4483 		tlen -= todrop;
4484 		thflags &= ~(TH_PUSH | TH_FIN);
4485 	}
4486 
4487 	/*
4488 	 * If last ACK falls within this segment's sequence numbers,
4489 	 * record its timestamp.
4490 	 * NOTE:
4491 	 * 1) That the test incorporates suggestions from the latest
4492 	 *    proposal of the [email protected] list (Braden 1993/04/26).
4493 	 * 2) That updating only on newer timestamps interferes with
4494 	 *    our earlier PAWS tests, so this check should be solely
4495 	 *    predicated on the sequence space of this segment.
4496 	 * 3) That we modify the segment boundary check to be
4497 	 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
4498 	 *    instead of RFC1323's
4499 	 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
4500 	 *    This modified check allows us to overcome RFC1323's
4501 	 *    limitations as described in Stevens TCP/IP Illustrated
4502 	 *    Vol. 2 p.869. In such cases, we can still calculate the
4503 	 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
4504 	 */
4505 	if ((to.to_flags & TOF_TS) != 0 &&
4506 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
4507 	    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
4508 	    ((thflags & (TH_SYN | TH_FIN)) != 0))) {
4509 		tp->ts_recent_age = tcp_now;
4510 		tp->ts_recent = to.to_tsval;
4511 	}
4512 
4513 	/*
4514 	 * Stevens: If a SYN is in the window, then this is an
4515 	 * error and we send an RST and drop the connection.
4516 	 *
4517 	 * RFC 5961 Section 4.2
4518 	 * Send challenge ACK for any SYN in synchronized state
4519 	 * Perform rate limitation in doing so.
4520 	 */
4521 	if (thflags & TH_SYN) {
4522 		if (!tcp_syn_data_valid(tp, th, tlen)) {
4523 			tcpstat.tcps_badsyn++;
4524 			/* Drop if we have reached ACK limit */
4525 			if (tcp_is_ack_ratelimited(tp)) {
4526 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN rate limited");
4527 				goto drop;
4528 			} else {
4529 				/* Send challenge ACK */
4530 				tcpstat.tcps_synchallenge++;
4531 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad SYN challenge ack");
4532 				goto dropafterack;
4533 			}
4534 		} else {
4535 			/*
4536 			 * Received SYN (/ACK) with data.
4537 			 * Move sequence number along to process the data.
4538 			 */
4539 			th->th_seq++;
4540 			thflags &= ~TH_SYN;
4541 		}
4542 	}
4543 
4544 	/*
4545 	 * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
4546 	 * flag is on (half-synchronized state), then queue data for
4547 	 * later processing; else drop segment and return.
4548 	 */
4549 	if ((thflags & TH_ACK) == 0) {
4550 		if (tp->t_state == TCPS_SYN_RECEIVED) {
4551 			if ((TFO_ENABLED(tp))) {
4552 				/*
4553 				 * So, we received a valid segment while in
4554 				 * SYN-RECEIVED.
4555 				 * As this cannot be an RST (see that if a bit
4556 				 * higher), and it does not have the ACK-flag
4557 				 * set, we want to retransmit the SYN/ACK.
4558 				 * Thus, we have to reset snd_nxt to snd_una to
4559 				 * trigger the going back to sending of the
4560 				 * SYN/ACK. This is more consistent with the
4561 				 * behavior of tcp_output(), which expects
4562 				 * to send the segment that is pointed to by
4563 				 * snd_nxt.
4564 				 */
4565 				tp->snd_nxt = tp->snd_una;
4566 
4567 				/*
4568 				 * We need to make absolutely sure that we are
4569 				 * going to reply upon a duplicate SYN-segment.
4570 				 */
4571 				if (th->th_flags & TH_SYN) {
4572 					needoutput = 1;
4573 				}
4574 			}
4575 			/* Process this same as newly received Accurate ECN SYN */
4576 			int ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
4577 			tcp_input_process_accecn_syn(tp, ace_flags, ip_ecn);
4578 
4579 			goto step6;
4580 		} else if (tp->t_flags & TF_ACKNOW) {
4581 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4582 			goto dropafterack;
4583 		} else {
4584 			TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "bad ACK");
4585 			goto drop;
4586 		}
4587 	}
4588 
4589 	/*
4590 	 * Ack processing.
4591 	 */
4592 
4593 	switch (tp->t_state) {
4594 	/*
4595 	 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
4596 	 * ESTABLISHED state and continue processing.
4597 	 * The ACK was checked above.
4598 	 */
4599 	case TCPS_SYN_RECEIVED:
4600 
4601 		tcpstat.tcps_connects++;
4602 
4603 		/* Do window scaling? */
4604 		if (TCP_WINDOW_SCALE_ENABLED(tp)) {
4605 			tp->snd_scale = tp->requested_s_scale;
4606 			tp->rcv_scale = tp->request_r_scale;
4607 			tp->snd_wnd = th->th_win << tp->snd_scale;
4608 			tp->max_sndwnd = tp->snd_wnd;
4609 			tiwin = tp->snd_wnd;
4610 		}
4611 		/*
4612 		 * Make transitions:
4613 		 *      SYN-RECEIVED  -> ESTABLISHED
4614 		 *      SYN-RECEIVED* -> FIN-WAIT-1
4615 		 */
4616 		tp->t_starttime = tcp_now;
4617 		tcp_sbrcv_tstmp_check(tp);
4618 		if (tp->t_flags & TF_NEEDFIN) {
4619 			DTRACE_TCP4(state__change, void, NULL,
4620 			    struct inpcb *, inp,
4621 			    struct tcpcb *, tp, int32_t, TCPS_FIN_WAIT_1);
4622 			TCP_LOG_STATE(tp, TCPS_FIN_WAIT_1);
4623 			tp->t_state = TCPS_FIN_WAIT_1;
4624 			tp->t_flags &= ~TF_NEEDFIN;
4625 
4626 			TCP_LOG_CONNECTION_SUMMARY(tp);
4627 		} else {
4628 			DTRACE_TCP4(state__change, void, NULL,
4629 			    struct inpcb *, inp,
4630 			    struct tcpcb *, tp, int32_t, TCPS_ESTABLISHED);
4631 			TCP_LOG_STATE(tp, TCPS_ESTABLISHED);
4632 			tp->t_state = TCPS_ESTABLISHED;
4633 			tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
4634 			    TCP_CONN_KEEPIDLE(tp));
4635 			if (nstat_collect) {
4636 				nstat_route_connect_success(
4637 					tp->t_inpcb->inp_route.ro_rt);
4638 			}
4639 			TCP_LOG_CONNECTED(tp, 0);
4640 			/*
4641 			 * The SYN is acknowledged but una is not updated
4642 			 * yet. So pass the value of ack to compute
4643 			 * sndbytes correctly
4644 			 */
4645 			inp_count_sndbytes(inp, th->th_ack);
4646 		}
4647 		tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
4648 
4649 		VERIFY(LIST_EMPTY(&tp->t_segq));
4650 		tp->snd_wl1 = th->th_seq - 1;
4651 
4652 		/*
4653 		 * AccECN server in SYN-RCVD state received an ACK with
4654 		 * SYN=0, process handshake encoding present in the ACK for SYN-ACK
4655 		 * and update receive side counters.
4656 		 */
4657 		if (TCP_ACC_ECN_ON(tp) && (thflags & (TH_SYN | TH_ACK)) == TH_ACK) {
4658 			const uint32_t ace_flags = ((th->th_x2 << 8) | thflags) & TH_ACE;
4659 			if (tlen == 0 && to.to_nsacks == 0) {
4660 				/*
4661 				 * ACK for SYN-ACK reflects the state (ECN) in which SYN-ACK packet
4662 				 * was delivered. Use Table 4 of Accurate ECN draft to decode only
4663 				 * when a pure ACK with no SACK block is received.
4664 				 * 0|0|0 will fail Accurate ECN negotiation and disable ECN.
4665 				 */
4666 				switch (ace_flags) {
4667 				case (0 | TH_CWR | 0):
4668 					/* Non-ECT SYN-ACK was delivered */
4669 					tp->t_aecn.t_snd_ce_packets = 5;
4670 					if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4671 						tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success;
4672 					}
4673 					break;
4674 				case (0 | TH_CWR | TH_ECE):
4675 					/* ECT1 SYN-ACK was delivered, mangling detected */
4676 					OS_FALLTHROUGH;
4677 				case (TH_AE | 0 | 0):
4678 					/* ECT0 SYN-ACK was delivered, mangling detected */
4679 					tp->t_aecn.t_snd_ce_packets = 5;
4680 					if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4681 						tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success_ect_mangling_detected;
4682 					}
4683 					break;
4684 				case (TH_AE | TH_CWR | 0):
4685 					/*
4686 					 * CE SYN-ACK was delivered, even though mangling happened,
4687 					 * CE could indicate congestion at a node after mangling occured.
4688 					 * Set cwnd to 2 segments
4689 					 */
4690 					tp->t_aecn.t_snd_ce_packets = 6;
4691 					tp->snd_cwnd = 2 * tp->t_maxseg;
4692 					if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4693 						tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success_ect_mangling_detected;
4694 					}
4695 					break;
4696 				case (0 | 0 | 0):
4697 					/* Disable ECN, as ACE fields were zeroed */
4698 					tp->ecn_flags &= ~(TE_SETUPRECEIVED | TE_SENDIPECT |
4699 					    TE_SENDCWR | TE_ACE_SETUPRECEIVED);
4700 					/*
4701 					 * Since last ACK has no ECN flag set and TE_LOST_SYNACK is set, this is in response
4702 					 * to the second (non-ECN setup) SYN-ACK retransmission. In such a case, we assume
4703 					 * that AccECN SYN-ACK was blackholed.
4704 					 */
4705 					if ((tp->ecn_flags & TE_LOST_SYNACK) && tp->t_rxtshift <= 2 &&
4706 					    (tp->t_server_accecn_state == tcp_connection_server_classic_ecn_requested ||
4707 					    tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested)) {
4708 						tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_blackholed;
4709 					}
4710 					/*
4711 					 * SYN-ACK hasn't been retransmitted twice yet, so this could likely mean bleaching of ACE
4712 					 * on the path from client to server on last ACK.
4713 					 */
4714 					if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4715 						tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_ace_bleaching_detected;
4716 					}
4717 					break;
4718 				default:
4719 					/* Unused values for forward compatibility */
4720 					tp->t_aecn.t_snd_ce_packets = 5;
4721 					break;
4722 				}
4723 				/* Update the time for this newly received last ACK */
4724 				if ((to.to_flags & TOF_TS) != 0 && (to.to_tsecr != 0) &&
4725 				    (tp->t_last_ack_tsecr == 0 || TSTMP_GEQ(to.to_tsecr, tp->t_last_ack_tsecr))) {
4726 					tp->t_last_ack_tsecr = to.to_tsecr;
4727 				}
4728 			} else if (to.to_nsacks == 0) {
4729 				/*
4730 				 * If 3rd ACK is lost, we won't receive the last ACK
4731 				 * encoding. We will move the server to AccECN mode
4732 				 * regardless.
4733 				 */
4734 				tp->t_aecn.t_snd_ce_packets = 5;
4735 				if (tp->t_server_accecn_state == tcp_connection_server_accurate_ecn_requested) {
4736 					tp->t_server_accecn_state = tcp_connection_server_accurate_ecn_negotiation_success;
4737 				}
4738 			}
4739 			/* Increment receive side counters based on IP-ECN */
4740 			tcp_input_ip_ecn(tp, inp, (uint32_t)tlen, (uint32_t)segment_count, ip_ecn);
4741 		}
4742 
4743 #if MPTCP
4744 		/*
4745 		 * Do not send the connect notification for additional subflows
4746 		 * until ACK for 3-way handshake arrives.
4747 		 */
4748 		if ((!(tp->t_mpflags & TMPF_MPTCP_TRUE)) &&
4749 		    (tp->t_mpflags & TMPF_SENT_JOIN)) {
4750 			isconnected = FALSE;
4751 		} else
4752 #endif /* MPTCP */
4753 		isconnected = TRUE;
4754 		if ((tp->t_tfo_flags & TFO_F_COOKIE_VALID)) {
4755 			/* Done this when receiving the SYN */
4756 			isconnected = FALSE;
4757 
4758 			OSDecrementAtomic(&tcp_tfo_halfcnt);
4759 
4760 			/* Panic if something has gone terribly wrong. */
4761 			VERIFY(tcp_tfo_halfcnt >= 0);
4762 
4763 			tp->t_tfo_flags &= ~TFO_F_COOKIE_VALID;
4764 		}
4765 
4766 		/*
4767 		 * In case there is data in the send-queue (e.g., TFO is being
4768 		 * used, or connectx+data has been done), then if we would
4769 		 * "FALLTHROUGH", we would handle this ACK as if data has been
4770 		 * acknowledged. But, we have to prevent this. And this
4771 		 * can be prevented by increasing snd_una by 1, so that the
4772 		 * SYN is not considered as data (snd_una++ is actually also
4773 		 * done in SYN_SENT-state as part of the regular TCP stack).
4774 		 *
4775 		 * In case there is data on this ack as well, the data will be
4776 		 * handled by the label "dodata" right after step6.
4777 		 */
4778 		if (so->so_snd.sb_cc) {
4779 			tp->snd_una++;  /* SYN is acked */
4780 			if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
4781 				tp->snd_nxt = tp->snd_una;
4782 			}
4783 
4784 			/*
4785 			 * No duplicate-ACK handling is needed. So, we
4786 			 * directly advance to processing the ACK (aka,
4787 			 * updating the RTT estimation,...)
4788 			 *
4789 			 * But, we first need to handle eventual SACKs,
4790 			 * because TFO will start sending data with the
4791 			 * SYN/ACK, so it might be that the client
4792 			 * includes a SACK with its ACK.
4793 			 */
4794 			if (SACK_ENABLED(tp) &&
4795 			    (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4796 				tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &highest_sacked_seq);
4797 			}
4798 
4799 			goto process_ACK;
4800 		}
4801 
4802 		OS_FALLTHROUGH;
4803 
4804 	/*
4805 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
4806 	 * ACKs.  If the ack is in the range
4807 	 *	tp->snd_una < th->th_ack <= tp->snd_max
4808 	 * then advance tp->snd_una to th->th_ack and drop
4809 	 * data from the retransmission queue.  If this ACK reflects
4810 	 * more up to date window information we update our window information.
4811 	 */
4812 	case TCPS_ESTABLISHED:
4813 	case TCPS_FIN_WAIT_1:
4814 	case TCPS_FIN_WAIT_2:
4815 	case TCPS_CLOSE_WAIT:
4816 	case TCPS_CLOSING:
4817 	case TCPS_LAST_ACK:
4818 	case TCPS_TIME_WAIT:
4819 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
4820 			tcpstat.tcps_rcvacktoomuch++;
4821 			if (tcp_is_ack_ratelimited(tp)) {
4822 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 rcvacktoomuch");
4823 				goto drop;
4824 			} else {
4825 				goto dropafterack;
4826 			}
4827 		}
4828 		if (SEQ_LT(th->th_ack, tp->snd_una - tp->max_sndwnd)) {
4829 			if (tcp_is_ack_ratelimited(tp)) {
4830 				TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "rfc5961 bad ACK");
4831 				goto drop;
4832 			} else {
4833 				goto dropafterack;
4834 			}
4835 		}
4836 		if (SACK_ENABLED(tp) && to.to_nsacks > 0) {
4837 			recvd_dsack = tcp_sack_process_dsack(tp, &to, th, &dsack_tlp);
4838 			/*
4839 			 * If DSACK is received and this packet has no
4840 			 * other SACK information, it can be dropped.
4841 			 * We do not want to treat it as a duplicate ack.
4842 			 */
4843 			if (recvd_dsack &&
4844 			    SEQ_LEQ(th->th_ack, tp->snd_una) &&
4845 			    to.to_nsacks == 0) {
4846 				tcp_bad_rexmt_check(tp, th, &to);
4847 				goto drop;
4848 			}
4849 		}
4850 
4851 		if (SACK_ENABLED(tp) &&
4852 		    (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes))) {
4853 			tcp_sack_doack(tp, &to, th, &sack_bytes_acked, &highest_sacked_seq);
4854 		}
4855 
4856 		if (TCP_RACK_ENABLED(tp)) {
4857 			/* If DSACK was received (not due to TLP), then update the reordering window */
4858 			if (recvd_dsack && !dsack_tlp) {
4859 				tp->rack.dsack_round_seen = 1;
4860 			}
4861 			tcp_rack_update_reordering_window(tp, th->th_ack);
4862 		}
4863 
4864 #if MPTCP
4865 		if (tp->t_mpuna && SEQ_GEQ(th->th_ack, tp->t_mpuna)) {
4866 			if (tp->t_mpflags & TMPF_PREESTABLISHED) {
4867 				/* MP TCP establishment succeeded */
4868 				tp->t_mpuna = 0;
4869 				if (tp->t_mpflags & TMPF_JOINED_FLOW) {
4870 					if (tp->t_mpflags & TMPF_SENT_JOIN) {
4871 						tp->t_mpflags &=
4872 						    ~TMPF_PREESTABLISHED;
4873 						tp->t_mpflags |=
4874 						    TMPF_MPTCP_TRUE;
4875 
4876 						tp->t_timer[TCPT_JACK_RXMT] = 0;
4877 						tp->t_mprxtshift = 0;
4878 						isconnected = TRUE;
4879 					} else {
4880 						isconnected = FALSE;
4881 					}
4882 				} else {
4883 					isconnected = TRUE;
4884 				}
4885 			}
4886 		}
4887 #endif /* MPTCP */
4888 
4889 		tcp_tfo_rcv_ack(tp, th);
4890 
4891 		/*
4892 		 * If we have outstanding data (other than
4893 		 * a window probe), this is a completely
4894 		 * duplicate ack and the ack is the biggest we've seen.
4895 		 *
4896 		 * Need to accommodate a change in window on duplicate acks
4897 		 * to allow operating systems that update window during
4898 		 * recovery with SACK
4899 		 */
4900 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
4901 			/*
4902 			 * Update snd_fack when new SACK blocks are received
4903 			 * without advancing the ACK
4904 			 */
4905 			if (TCP_RACK_ENABLED(tp) && sack_bytes_acked > 0 &&
4906 			    SEQ_LT(tp->snd_fack, highest_sacked_seq)) {
4907 				tp->snd_fack = highest_sacked_seq;
4908 			}
4909 
4910 			/*
4911 			 * Process AccECN feedback here for control packets
4912 			 * that don't have s/acked bytes
4913 			 */
4914 			if (TCP_ACC_ECN_ON(tp) && (tp->ecn_flags & TE_SENDIPECT) &&
4915 			    (sack_bytes_acked == 0)) {
4916 				tp->total_ect_packets_acked += 1;
4917 
4918 				bool newly_acked_time = false;
4919 				if (acked == 0 && (to.to_flags & TOF_TS) != 0 && to.to_tsecr != 0 &&
4920 				    TSTMP_GT(to.to_tsecr, tp->t_last_ack_tsecr)) {
4921 					newly_acked_time = true;
4922 				}
4923 				if (newly_acked_time) {
4924 					tcp_process_accecn(tp, &to, th, 1, ace);
4925 				}
4926 			}
4927 
4928 			if (tlen == 0 && (tiwin == tp->snd_wnd ||
4929 			    (to.to_nsacks > 0 && sack_bytes_acked > 0))) {
4930 				uint32_t old_dupacks;
4931 				/*
4932 				 * If both ends send FIN at the same time,
4933 				 * then the ack will be a duplicate ack
4934 				 * but we have to process the FIN. Check
4935 				 * for this condition and process the FIN
4936 				 * instead of the dupack
4937 				 */
4938 				if ((thflags & TH_FIN) &&
4939 				    !TCPS_HAVERCVDFIN(tp->t_state)) {
4940 					break;
4941 				}
4942 process_dupack:
4943 				old_dupacks = tp->t_dupacks;
4944 #if MPTCP
4945 				/*
4946 				 * MPTCP options that are ignored must
4947 				 * not be treated as duplicate ACKs.
4948 				 */
4949 				if (to.to_flags & TOF_MPTCP) {
4950 					goto drop;
4951 				}
4952 
4953 				if ((isconnected) && (tp->t_mpflags & TMPF_JOINED_FLOW)) {
4954 					break;
4955 				}
4956 #endif /* MPTCP */
4957 				/*
4958 				 * If a duplicate acknowledgement was seen
4959 				 * after ECN, it indicates packet loss in
4960 				 * addition to ECN. Reset INRECOVERY flag
4961 				 * so that we can process partial acks
4962 				 * correctly
4963 				 */
4964 				if (tp->ecn_flags & TE_INRECOVERY) {
4965 					tp->ecn_flags &= ~TE_INRECOVERY;
4966 				}
4967 
4968 				tcpstat.tcps_rcvdupack++;
4969 				if (SACK_ENABLED(tp)) {
4970 					tp->t_dupacks += max(1, sack_bytes_acked / tp->t_maxseg);
4971 				} else {
4972 					++tp->t_dupacks;
4973 				}
4974 
4975 				tp->sackhint.sack_bytes_acked += sack_bytes_acked;
4976 
4977 				if (sack_bytes_acked > 0 && TCP_ACC_ECN_ON(tp) &&
4978 				    (tp->ecn_flags & TE_SENDIPECT) && tp->t_state == TCPS_ESTABLISHED) {
4979 					uint32_t pkts_sacked = tcp_packets_this_ack(tp, sack_bytes_acked);
4980 					tp->total_ect_packets_acked += pkts_sacked;
4981 					tcp_process_accecn(tp, &to, th, pkts_sacked, ace);
4982 				}
4983 				/*
4984 				 * Check if we need to reset the limit on
4985 				 * early retransmit
4986 				 */
4987 				if (tp->t_early_rexmt_count > 0 &&
4988 				    TSTMP_GEQ(tcp_now,
4989 				    (tp->t_early_rexmt_win +
4990 				    TCP_EARLY_REXMT_WIN))) {
4991 					tp->t_early_rexmt_count = 0;
4992 				}
4993 
4994 				/*
4995 				 * Is early retransmit needed? We check for
4996 				 * this when the connection is waiting for
4997 				 * duplicate acks to enter fast recovery.
4998 				 */
4999 				if (!IN_FASTRECOVERY(tp)) {
5000 					tcp_early_rexmt_check(tp, th);
5001 				}
5002 
5003 				/*
5004 				 * Detect loss based on RACK during dupACK processing to mark lost
5005 				 * segments before tcp_output is called for retransmission
5006 				 */
5007 				if (TCP_RACK_ENABLED(tp) && tcp_rack_detect_loss_and_arm_timer(tp, tp->t_dupacks)) {
5008 					rack_loss_detected = true;
5009 				}
5010 				/*
5011 				 * Below are four different processing of (dup) ACKs,
5012 				 * 1. Not a valid dup ACK
5013 				 * 2. More than 3 dup ACKs but already in Fast Recovery
5014 				 * 3. Entered Fast Recovery for the first time
5015 				 * 4. Received less than 3 dup ACKs, evaluate if we can do Limited Transmit
5016 				 */
5017 				if (tp->t_timer[TCPT_REXMT] == 0 ||
5018 				    (th->th_ack != tp->snd_una && sack_bytes_acked == 0)) {
5019 					/*
5020 					 * No outstanding data and ACK is not a duplicate as it is
5021 					 * less than snd_una but not equal to it.
5022 					 */
5023 					tp->t_dupacks = 0;
5024 					tp->t_rexmtthresh = tcprexmtthresh;
5025 				} else if ((!TCP_RACK_ENABLED(tp) && tp->t_dupacks > tp->t_rexmtthresh && old_dupacks >= tp->t_rexmtthresh) ||
5026 				    IN_FASTRECOVERY(tp)) {
5027 					/*
5028 					 * We are already in Fast Recovery and t_dupacks is greater than retransmit threshold.
5029 					 * Increase the cwnd by 1MSS if allowed
5030 					 */
5031 
5032 					/*
5033 					 * If this connection was seeing packet
5034 					 * reordering, then recovery might be
5035 					 * delayed to disambiguate between
5036 					 * reordering and loss
5037 					 */
5038 					if (SACK_ENABLED(tp) && !IN_FASTRECOVERY(tp) &&
5039 					    (tp->t_flagsext &
5040 					    (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) ==
5041 					    (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
5042 						/*
5043 						 * Since the SACK information is already
5044 						 * updated, this ACK will be dropped
5045 						 */
5046 						break;
5047 					}
5048 
5049 					/*
5050 					 * Dup acks mean that packets have left the
5051 					 * network (they're now cached at the receiver)
5052 					 * so bump cwnd by the amount in the receiver
5053 					 * to keep a constant cwnd packets in the
5054 					 * network.
5055 					 */
5056 					if (SACK_ENABLED(tp) && IN_FASTRECOVERY(tp)) {
5057 						int awnd;
5058 
5059 						/*
5060 						 * Compute the amount of data in flight first.
5061 						 * We can inject new data into the pipe iff
5062 						 * we have less than snd_ssthres worth of data in
5063 						 * flight.
5064 						 */
5065 						awnd = (tp->snd_nxt - tp->snd_fack) + tp->sackhint.sack_bytes_rexmit;
5066 						if (awnd < tp->snd_ssthresh) {
5067 							tp->snd_cwnd += tp->t_maxseg;
5068 							if (tp->snd_cwnd > tp->snd_ssthresh) {
5069 								tp->snd_cwnd = tp->snd_ssthresh;
5070 							}
5071 						}
5072 					} else {
5073 						tp->snd_cwnd += tp->t_maxseg;
5074 					}
5075 
5076 					/* Process any window updates */
5077 					if (tiwin > tp->snd_wnd) {
5078 						tcp_update_window(tp, thflags,
5079 						    th, tiwin, tlen);
5080 					}
5081 					tcp_ccdbg_trace(tp, th,
5082 					    TCP_CC_IN_FASTRECOVERY);
5083 
5084 					(void) tcp_output(tp);
5085 
5086 					goto drop;
5087 				} else if (rack_loss_detected || (!TCP_RACK_ENABLED(tp) && tp->t_dupacks >= tp->t_rexmtthresh)) {
5088 					/*
5089 					 * Currently not in Fast Recovery and received 3 or more dupacks.
5090 					 * Enter Fast Recovery, retransmit segment and set
5091 					 * cwnd to sshthresh if SACK is enabled.
5092 					 */
5093 					tcp_seq onxt = tp->snd_nxt;
5094 
5095 					/*
5096 					 * If we're doing sack, check to
5097 					 * see if we're already in sack
5098 					 * recovery. If we're not doing sack,
5099 					 * check to see if we're in newreno
5100 					 * recovery.
5101 					 */
5102 					if (SACK_ENABLED(tp)) {
5103 						if (IN_FASTRECOVERY(tp)) {
5104 							tp->t_dupacks = 0;
5105 							break;
5106 						} else if (tp->t_flagsext & TF_DELAY_RECOVERY) {
5107 							break;
5108 						}
5109 					} else {
5110 						if (SEQ_LEQ(th->th_ack, tp->snd_recover)) {
5111 							tp->t_dupacks = 0;
5112 							break;
5113 						}
5114 					}
5115 					if (tp->t_flags & TF_SENTFIN) {
5116 						tp->snd_recover = tp->snd_max - 1;
5117 					} else {
5118 						tp->snd_recover = tp->snd_max;
5119 					}
5120 					tp->t_timer[TCPT_PTO] = 0;
5121 					tp->t_rtttime = 0;
5122 
5123 					/*
5124 					 * If the connection has seen pkt
5125 					 * reordering, delay recovery until
5126 					 * it is clear that the packet
5127 					 * was lost.
5128 					 */
5129 					if (SACK_ENABLED(tp) &&
5130 					    (tp->t_flagsext &
5131 					    (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
5132 					    == TF_PKTS_REORDERED &&
5133 					    !IN_FASTRECOVERY(tp) &&
5134 					    tp->t_reorderwin > 0 &&
5135 					    (tp->t_state == TCPS_ESTABLISHED ||
5136 					    tp->t_state == TCPS_FIN_WAIT_1)) {
5137 						tp->t_timer[TCPT_DELAYFR] =
5138 						    OFFSET_FROM_START(tp,
5139 						    tp->t_reorderwin);
5140 						tp->t_flagsext |= TF_DELAY_RECOVERY;
5141 						tcpstat.tcps_delay_recovery++;
5142 						tcp_ccdbg_trace(tp, th,
5143 						    TCP_CC_DELAY_FASTRECOVERY);
5144 						break;
5145 					}
5146 
5147 					tcp_rexmt_save_state(tp);
5148 					/*
5149 					 * If the current tcp cc module has
5150 					 * defined a hook for tasks to run
5151 					 * before entering FR, call it
5152 					 */
5153 					if (CC_ALGO(tp)->pre_fr != NULL) {
5154 						CC_ALGO(tp)->pre_fr(tp);
5155 					}
5156 					ENTER_FASTRECOVERY(tp);
5157 					tp->t_timer[TCPT_REXMT] = 0;
5158 					if (!TCP_ACC_ECN_ON(tp) && TCP_ECN_ENABLED(tp)) {
5159 						tp->ecn_flags |= TE_SENDCWR;
5160 					}
5161 
5162 					if (SACK_ENABLED(tp)) {
5163 						if (TCP_RACK_ENABLED(tp)) {
5164 							tcpstat.tcps_rack_recovery_episode++;
5165 							tp->t_rack_recovery_episode++;
5166 						} else {
5167 							tcpstat.tcps_sack_recovery_episode++;
5168 							tp->t_sack_recovery_episode++;
5169 						}
5170 
5171 						tp->snd_cwnd = tp->snd_ssthresh;
5172 						tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
5173 
5174 						/* Process any window updates */
5175 						if (tiwin > tp->snd_wnd) {
5176 							tcp_update_window(tp, thflags, th, tiwin, tlen);
5177 						}
5178 
5179 						tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
5180 						(void) tcp_output(tp);
5181 						goto drop;
5182 					}
5183 					tp->snd_nxt = th->th_ack;
5184 					tp->snd_cwnd = tp->t_maxseg;
5185 
5186 					/* cwnd is validated after pre_fr() */
5187 					tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
5188 
5189 					/* Process any window updates */
5190 					if (tiwin > tp->snd_wnd) {
5191 						tcp_update_window(tp, thflags, th, tiwin, tlen);
5192 					}
5193 
5194 					(void) tcp_output(tp);
5195 					if (tp->t_flagsext & TF_CWND_NONVALIDATED) {
5196 						tcp_cc_adjust_nonvalidated_cwnd(tp);
5197 					} else {
5198 						tp->snd_cwnd = tp->snd_ssthresh + tp->t_maxseg * tp->t_dupacks;
5199 					}
5200 					if (SEQ_GT(onxt, tp->snd_nxt)) {
5201 						tp->snd_nxt = onxt;
5202 					}
5203 
5204 					tcp_ccdbg_trace(tp, th, TCP_CC_ENTER_FASTRECOVERY);
5205 					goto drop;
5206 				} else if (ALLOW_LIMITED_TRANSMIT(tp) &&
5207 				    (!(SACK_ENABLED(tp)) || sack_bytes_acked > 0) &&
5208 				    (so->so_snd.sb_cc - (tp->snd_max - tp->snd_una)) > 0) {
5209 					u_int32_t incr = (tp->t_maxseg * tp->t_dupacks);
5210 
5211 					/* Use Limited Transmit algorithm on the first two
5212 					 * duplicate acks when there is new data to transmit
5213 					 */
5214 					tp->snd_cwnd += incr;
5215 					tcpstat.tcps_limited_txt++;
5216 					(void) tcp_output(tp);
5217 
5218 					tcp_ccdbg_trace(tp, th, TCP_CC_LIMITED_TRANSMIT);
5219 
5220 					/* Reset snd_cwnd back to normal */
5221 					tp->snd_cwnd -= incr;
5222 				}
5223 			}
5224 			break;
5225 		}
5226 		/*
5227 		 * If the congestion window was inflated to account
5228 		 * for the other side's cached packets, retract it.
5229 		 */
5230 		if (IN_FASTRECOVERY(tp)) {
5231 			if (SEQ_LT(th->th_ack, tp->snd_recover)) {
5232 				/*
5233 				 * If we received an ECE and entered
5234 				 * recovery, the subsequent ACKs should
5235 				 * not be treated as partial acks.
5236 				 */
5237 				if (tp->ecn_flags & TE_INRECOVERY) {
5238 					goto process_ACK;
5239 				}
5240 				/* RACK doesn't require inflating cwnd */
5241 				if (!TCP_RACK_ENABLED(tp)) {
5242 					if (SACK_ENABLED(tp)) {
5243 						tcp_sack_partialack(tp, th);
5244 					} else {
5245 						tcp_newreno_partial_ack(tp, th);
5246 					}
5247 					tcp_ccdbg_trace(tp, th, TCP_CC_PARTIAL_ACK);
5248 				}
5249 			} else {
5250 				if (tcp_cubic_minor_fixes) {
5251 					exiting_fr = 1;
5252 				}
5253 				EXIT_FASTRECOVERY(tp);
5254 				if (CC_ALGO(tp)->post_fr != NULL) {
5255 					CC_ALGO(tp)->post_fr(tp, th);
5256 				}
5257 
5258 				if (TCP_RACK_ENABLED(tp)) {
5259 					tcp_rack_update_reordering_win_persist(tp);
5260 				}
5261 
5262 				tp->t_pipeack = 0;
5263 				tcp_clear_pipeack_state(tp);
5264 				tcp_ccdbg_trace(tp, th,
5265 				    TCP_CC_EXIT_FASTRECOVERY);
5266 			}
5267 		} else if ((tp->t_flagsext &
5268 		    (TF_PKTS_REORDERED | TF_DELAY_RECOVERY))
5269 		    == (TF_PKTS_REORDERED | TF_DELAY_RECOVERY)) {
5270 			/*
5271 			 * If the ack acknowledges upto snd_recover or if
5272 			 * it acknowledges all the snd holes, exit
5273 			 * recovery and cancel the timer. Otherwise,
5274 			 * this is a partial ack. Wait for recovery timer
5275 			 * to enter recovery. The snd_holes have already
5276 			 * been updated.
5277 			 */
5278 			if (SEQ_GEQ(th->th_ack, tp->snd_recover) ||
5279 			    TAILQ_EMPTY(&tp->snd_holes)) {
5280 				tp->t_timer[TCPT_DELAYFR] = 0;
5281 				tp->t_flagsext &= ~TF_DELAY_RECOVERY;
5282 				EXIT_FASTRECOVERY(tp);
5283 				tcp_ccdbg_trace(tp, th,
5284 				    TCP_CC_EXIT_FASTRECOVERY);
5285 			}
5286 		} else {
5287 			/*
5288 			 * We were not in fast recovery. Reset the
5289 			 * duplicate ack counter.
5290 			 */
5291 			tp->t_dupacks = 0;
5292 			tp->t_rexmtthresh = tcprexmtthresh;
5293 		}
5294 
5295 process_ACK:
5296 		VERIFY(SEQ_GEQ(th->th_ack, tp->snd_una));
5297 		acked = BYTES_ACKED(th, tp);
5298 		tcpstat.tcps_rcvackpack++;
5299 		tcpstat.tcps_rcvackbyte += acked;
5300 
5301 		/*
5302 		 * If the last packet was a retransmit, make sure
5303 		 * it was not spurious.
5304 		 *
5305 		 * This will also take care of congestion window
5306 		 * adjustment if a last packet was recovered due to a
5307 		 * tail loss probe.
5308 		 */
5309 		tcp_bad_rexmt_check(tp, th, &to);
5310 
5311 		/* Recalculate the RTT */
5312 		tcp_compute_rtt(tp, &to, th);
5313 
5314 		/*
5315 		 * If all outstanding data is acked, stop retransmit
5316 		 * timer and remember to restart (more output or persist).
5317 		 * If there is more data to be acked, restart retransmit
5318 		 * timer, using current (possibly backed-off) value.
5319 		 */
5320 		TCP_RESET_REXMT_STATE(tp);
5321 		TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
5322 		    tp->t_rttmin, TCPTV_REXMTMAX,
5323 		    TCP_ADD_REXMTSLOP(tp));
5324 		if (th->th_ack == tp->snd_max) {
5325 			tp->t_timer[TCPT_REXMT] = 0;
5326 			tp->t_timer[TCPT_PTO] = 0;
5327 			tp->t_timer[TCPT_REORDER] = 0;
5328 			tcp_rack_reset_segs_retransmitted(tp);
5329 			needoutput = 1;
5330 		} else if (tp->t_timer[TCPT_PERSIST] == 0) {
5331 			tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp,
5332 			    tp->t_rxtcur);
5333 		}
5334 
5335 		if ((prev_t_state == TCPS_SYN_SENT ||
5336 		    prev_t_state == TCPS_SYN_RECEIVED) &&
5337 		    tp->t_state == TCPS_ESTABLISHED) {
5338 			TCP_LOG_RTT_INFO(tp);
5339 		}
5340 
5341 		/*
5342 		 * If no data (only SYN) was ACK'd, skip rest of ACK
5343 		 * processing.
5344 		 */
5345 		if (acked == 0) {
5346 			goto step6;
5347 		}
5348 
5349 		/*
5350 		 * Process sent segments used for RACK as we need to update
5351 		 * RACK state before loss detection. Update snd_fack only
5352 		 * after ACK processing which performs reordering detection.
5353 		 */
5354 		if (TCP_RACK_ENABLED(tp)) {
5355 			tcp_segs_doack(tp, th->th_ack, &to);
5356 			if (SEQ_LT(tp->snd_fack, highest_sacked_seq)) {
5357 				tp->snd_fack = highest_sacked_seq;
5358 			}
5359 			if (SEQ_LT(tp->snd_fack, th->th_ack)) {
5360 				tp->snd_fack = th->th_ack;
5361 			}
5362 		}
5363 		/*
5364 		 * When outgoing data has been acked (except the SYN+data), we
5365 		 * mark this connection as "sending good" for TFO.
5366 		 */
5367 		if ((tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
5368 		    !(tp->t_tfo_flags & TFO_F_NO_SNDPROBING) &&
5369 		    !(th->th_flags & TH_SYN)) {
5370 			tp->t_tfo_flags |= TFO_F_NO_SNDPROBING;
5371 		}
5372 
5373 		if ((tp->ecn_flags & TE_SENDIPECT)) {
5374 			/*
5375 			 * draft-ietf-tcpm-accurate-ecn-28
5376 			 * Accurate ECN feedback processing for data sender,
5377 			 * Process peer's feedback in received TCP thflags and update s.cep
5378 			 * Since SYN-ACK has a special encoding, exclude it from below.
5379 			 * Only perform it before CC is called and snd_una is updated.
5380 			 */
5381 			if (TCP_ACC_ECN_ON(tp) && !(thflags & TH_SYN)) {
5382 				/*
5383 				 * For a server in SYN_RECEIVED state (that switched to
5384 				 * ESTABLISHED in this ACK, exclude processing the last ACK
5385 				 */
5386 				if (th->th_ack == tp->iss + 1) {
5387 					acked = 0;
5388 				}
5389 				uint32_t pkts_acked = tcp_packets_this_ack(tp, acked);
5390 				tp->total_ect_packets_acked += pkts_acked;
5391 				/*
5392 				 * Calculate newly_acked_time used for AccECN feedback parsing
5393 				 * for data sender if ACK acknowledges packets without data
5394 				 * if reordering happens and certain packets have same TS.
5395 				 * Right now, we consider that new time was ACKed if the TS
5396 				 * was GT previous value, but we need to think about how to
5397 				 * differentiate between reordering and wrapping when TS is same
5398 				 * as previous value.
5399 				 */
5400 				bool newly_acked_time = false;
5401 				if (acked == 0 && sack_bytes_acked == 0 &&
5402 				    (to.to_flags & TOF_TS) != 0 && to.to_tsecr != 0 &&
5403 				    (tp->t_last_ack_tsecr == 0 || TSTMP_GT(to.to_tsecr, tp->t_last_ack_tsecr))) {
5404 					newly_acked_time = true;
5405 				}
5406 				/*
5407 				 * Update s.cep if bytes have been newly S/ACKed
5408 				 * otherwise, this ACK has already been superseded.
5409 				 */
5410 				if (acked > 0 || sack_bytes_acked > 0 || newly_acked_time) {
5411 					tcp_process_accecn(tp, &to, th, pkts_acked, ace);
5412 				}
5413 			} else if (TCP_ECN_ENABLED(tp) && (thflags & TH_ECE)) {
5414 				/*
5415 				 * For classic ECN, congestion event is receiving TH_ECE.
5416 				 * Reduce the congestion window if we haven't
5417 				 * done so.
5418 				 */
5419 				if (!IN_FASTRECOVERY(tp)) {
5420 					/*
5421 					 * Although we enter Fast Recovery in the below function
5422 					 * we exit it immediately below as th_ack >= snd_recover
5423 					 */
5424 					tcp_enter_fast_recovery(tp);
5425 					tp->ecn_flags |= (TE_INRECOVERY | TE_SENDCWR);
5426 					/*
5427 					 * Also note that the connection received
5428 					 * ECE atleast once. We increment
5429 					 * t_ecn_capable_packets_marked when we first
5430 					 * enter fast recovery.
5431 					 */
5432 					tp->ecn_flags |= TE_RECV_ECN_ECE;
5433 					INP_INC_IFNET_STAT(inp, ecn_recv_ece);
5434 					tcpstat.tcps_ecn_recv_ece++;
5435 					tp->t_ecn_capable_packets_marked++;
5436 					tcp_ccdbg_trace(tp, th, TCP_CC_ECN_RCVD);
5437 				}
5438 			}
5439 		}
5440 
5441 		/*
5442 		 * When new data is acked, open the congestion window.
5443 		 * The specifics of how this is achieved are up to the
5444 		 * congestion control algorithm in use for this connection.
5445 		 *
5446 		 * The calculations in this function assume that snd_una is
5447 		 * not updated yet.
5448 		 */
5449 		if (!IN_FASTRECOVERY(tp) && !exiting_fr) {
5450 			if (CC_ALGO(tp)->ack_rcvd != NULL) {
5451 				CC_ALGO(tp)->ack_rcvd(tp, th);
5452 			}
5453 			tcp_ccdbg_trace(tp, th, TCP_CC_ACK_RCVD);
5454 		}
5455 		if (acked > so->so_snd.sb_cc) {
5456 			tp->snd_wnd -= so->so_snd.sb_cc;
5457 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
5458 			ourfinisacked = 1;
5459 		} else {
5460 			sbdrop(&so->so_snd, acked);
5461 			tcp_sbsnd_trim(&so->so_snd);
5462 			tp->snd_wnd -= acked;
5463 			ourfinisacked = 0;
5464 		}
5465 		/* detect una wraparound */
5466 		if (!IN_FASTRECOVERY(tp) &&
5467 		    SEQ_GT(tp->snd_una, tp->snd_recover) &&
5468 		    SEQ_LEQ(th->th_ack, tp->snd_recover)) {
5469 			tp->snd_recover = th->th_ack - 1;
5470 		}
5471 
5472 		if (IN_FASTRECOVERY(tp) &&
5473 		    SEQ_GEQ(th->th_ack, tp->snd_recover)) {
5474 			EXIT_FASTRECOVERY(tp);
5475 			if (TCP_RACK_ENABLED(tp)) {
5476 				tcp_rack_update_reordering_win_persist(tp);
5477 			}
5478 		}
5479 
5480 		tcp_update_snd_una(tp, th->th_ack);
5481 
5482 		if (SACK_ENABLED(tp)) {
5483 			if (SEQ_GT(tp->snd_una, tp->snd_recover)) {
5484 				tp->snd_recover = tp->snd_una;
5485 			}
5486 		}
5487 		if (SEQ_LT(tp->snd_nxt, tp->snd_una)) {
5488 			tp->snd_nxt = tp->snd_una;
5489 		}
5490 
5491 		/*
5492 		 * Detect loss based on RACK during ACK processing to mark lost
5493 		 * segments and call tcp_output. Rest of the ACK processing can
5494 		 * continue after that.
5495 		 */
5496 		if (TCP_RACK_ENABLED(tp) && tcp_rack_detect_loss_and_arm_timer(tp, 0)) {
5497 			if (!IN_FASTRECOVERY(tp)) {
5498 				tcp_enter_fast_recovery(tp);
5499 				tcpstat.tcps_rack_recovery_episode++;
5500 				tp->t_rack_recovery_episode++;
5501 			}
5502 			tcp_output(tp);
5503 		}
5504 
5505 		if (!SLIST_EMPTY(&tp->t_rxt_segments) &&
5506 		    !TCP_DSACK_SEQ_IN_WINDOW(tp, tp->t_dsack_lastuna,
5507 		    tp->snd_una)) {
5508 			tcp_rxtseg_clean(tp);
5509 		}
5510 		if ((tp->t_flagsext & TF_MEASURESNDBW) != 0 &&
5511 		    tp->t_bwmeas != NULL) {
5512 			tcp_bwmeas_check(tp);
5513 		}
5514 
5515 		write_wakeup = 1;
5516 
5517 		if (!SLIST_EMPTY(&tp->t_notify_ack)) {
5518 			tcp_notify_acknowledgement(tp, so);
5519 		}
5520 
5521 		switch (tp->t_state) {
5522 		/*
5523 		 * In FIN_WAIT_1 STATE in addition to the processing
5524 		 * for the ESTABLISHED state if our FIN is now acknowledged
5525 		 * then enter FIN_WAIT_2.
5526 		 */
5527 		case TCPS_FIN_WAIT_1:
5528 			if (ourfinisacked) {
5529 				/*
5530 				 * If we can't receive any more
5531 				 * data, then closing user can proceed.
5532 				 * Starting the TCPT_2MSL timer is contrary to the
5533 				 * specification, but if we don't get a FIN
5534 				 * we'll hang forever.
5535 				 */
5536 				DTRACE_TCP4(state__change, void, NULL,
5537 				    struct inpcb *, inp,
5538 				    struct tcpcb *, tp,
5539 				    int32_t, TCPS_FIN_WAIT_2);
5540 				TCP_LOG_STATE(tp, TCPS_FIN_WAIT_2);
5541 				tp->t_state = TCPS_FIN_WAIT_2;
5542 				if (so->so_state & SS_CANTRCVMORE) {
5543 					isconnected = FALSE;
5544 					isdisconnected = TRUE;
5545 					tcp_set_finwait_timeout(tp);
5546 				}
5547 				/*
5548 				 * fall through and make sure we also recognize
5549 				 * data ACKed with the FIN
5550 				 */
5551 			}
5552 			break;
5553 
5554 		/*
5555 		 * In CLOSING STATE in addition to the processing for
5556 		 * the ESTABLISHED state if the ACK acknowledges our FIN
5557 		 * then enter the TIME-WAIT state, otherwise ignore
5558 		 * the segment.
5559 		 */
5560 		case TCPS_CLOSING:
5561 			if (ourfinisacked) {
5562 				DTRACE_TCP4(state__change, void, NULL,
5563 				    struct inpcb *, inp,
5564 				    struct tcpcb *, tp,
5565 				    int32_t, TCPS_TIME_WAIT);
5566 				TCP_LOG_STATE(tp, TCPS_TIME_WAIT);
5567 				tp->t_state = TCPS_TIME_WAIT;
5568 				tcp_canceltimers(tp);
5569 				if (tp->t_flagsext & TF_NOTIMEWAIT) {
5570 					tp->t_flags |= TF_CLOSING;
5571 				} else {
5572 					add_to_time_wait(tp, 2 * tcp_msl);
5573 				}
5574 				isconnected = FALSE;
5575 				isdisconnected = TRUE;
5576 			}
5577 			break;
5578 
5579 		/*
5580 		 * In LAST_ACK, we may still be waiting for data to drain
5581 		 * and/or to be acked, as well as for the ack of our FIN.
5582 		 * If our FIN is now acknowledged, delete the TCB,
5583 		 * enter the closed state and return.
5584 		 */
5585 		case TCPS_LAST_ACK:
5586 			if (ourfinisacked) {
5587 				tp = tcp_close(tp);
5588 				goto drop;
5589 			}
5590 			break;
5591 
5592 		/*
5593 		 * In TIME_WAIT state the only thing that should arrive
5594 		 * is a retransmission of the remote FIN.  Acknowledge
5595 		 * it and restart the finack timer.
5596 		 */
5597 		case TCPS_TIME_WAIT:
5598 			add_to_time_wait(tp, 2 * tcp_msl);
5599 			goto dropafterack;
5600 		}
5601 
5602 		/*
5603 		 * If there is a SACK option on the ACK and we
5604 		 * haven't seen any duplicate acks before, count
5605 		 * it as a duplicate ack even if the cumulative
5606 		 * ack is advanced. If the receiver delayed an
5607 		 * ack and detected loss afterwards, then the ack
5608 		 * will advance cumulative ack and will also have
5609 		 * a SACK option. So counting it as one duplicate
5610 		 * ack is ok.
5611 		 */
5612 		if (tp->t_state == TCPS_ESTABLISHED &&
5613 		    SACK_ENABLED(tp) && sack_bytes_acked > 0 &&
5614 		    to.to_nsacks > 0 && tp->t_dupacks == 0 &&
5615 		    SEQ_LEQ(th->th_ack, tp->snd_una) && tlen == 0 &&
5616 		    !(tp->t_flagsext & TF_PKTS_REORDERED)) {
5617 			tcpstat.tcps_sack_ackadv++;
5618 			goto process_dupack;
5619 		}
5620 	}
5621 
5622 step6:
5623 	/*
5624 	 * Update window information.
5625 	 */
5626 	if (tcp_update_window(tp, thflags, th, tiwin, tlen)) {
5627 		needoutput = 1;
5628 	}
5629 
5630 	/*
5631 	 * Process segments with URG.
5632 	 */
5633 	if ((thflags & TH_URG) && th->th_urp &&
5634 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5635 		/*
5636 		 * This is a kludge, but if we receive and accept
5637 		 * random urgent pointers, we'll crash in
5638 		 * soreceive.  It's hard to imagine someone
5639 		 * actually wanting to send this much urgent data.
5640 		 */
5641 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
5642 			th->th_urp = 0;                 /* XXX */
5643 			thflags &= ~TH_URG;             /* XXX */
5644 			goto dodata;                    /* XXX */
5645 		}
5646 		/*
5647 		 * If this segment advances the known urgent pointer,
5648 		 * then mark the data stream.  This should not happen
5649 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
5650 		 * a FIN has been received from the remote side.
5651 		 * In these states we ignore the URG.
5652 		 *
5653 		 * According to RFC961 (Assigned Protocols),
5654 		 * the urgent pointer points to the last octet
5655 		 * of urgent data.  We continue, however,
5656 		 * to consider it to indicate the first octet
5657 		 * of data past the urgent section as the original
5658 		 * spec states (in one of two places).
5659 		 */
5660 		if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
5661 			tp->rcv_up = th->th_seq + th->th_urp;
5662 			so->so_oobmark = so->so_rcv.sb_cc +
5663 			    (tp->rcv_up - tp->rcv_nxt) - 1;
5664 			if (so->so_oobmark == 0) {
5665 				so->so_state |= SS_RCVATMARK;
5666 			}
5667 			sohasoutofband(so);
5668 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
5669 		}
5670 		/*
5671 		 * Remove out of band data so doesn't get presented to user.
5672 		 * This can happen independent of advancing the URG pointer,
5673 		 * but if two URG's are pending at once, some out-of-band
5674 		 * data may creep in... ick.
5675 		 */
5676 		if (th->th_urp <= (u_int32_t)tlen
5677 #if SO_OOBINLINE
5678 		    && (so->so_options & SO_OOBINLINE) == 0
5679 #endif
5680 		    ) {
5681 			tcp_pulloutofband(so, th, m,
5682 			    drop_hdrlen);       /* hdr drop is delayed */
5683 		}
5684 	} else {
5685 		/*
5686 		 * If no out of band data is expected,
5687 		 * pull receive urgent pointer along
5688 		 * with the receive window.
5689 		 */
5690 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up)) {
5691 			tp->rcv_up = tp->rcv_nxt;
5692 		}
5693 	}
5694 dodata:
5695 
5696 	/* Set socket's connect or disconnect state correcly before doing data.
5697 	 * The following might unlock the socket if there is an upcall or a socket
5698 	 * filter.
5699 	 */
5700 	if (isconnected) {
5701 		soisconnected(so);
5702 	} else if (isdisconnected) {
5703 		soisdisconnected(so);
5704 	}
5705 
5706 	/* Let's check the state of pcb just to make sure that it did not get closed
5707 	 * when we unlocked above
5708 	 */
5709 	if (inp->inp_state == INPCB_STATE_DEAD) {
5710 		/* Just drop the packet that we are processing and return */
5711 		TCP_LOG_DROP_PCB(TCP_LOG_HDR, th, tp, false, "INPCB_STATE_DEAD");
5712 		goto drop;
5713 	}
5714 
5715 	/*
5716 	 * Process the segment text, merging it into the TCP sequencing queue,
5717 	 * and arranging for acknowledgment of receipt if necessary.
5718 	 * This process logically involves adjusting tp->rcv_wnd as data
5719 	 * is presented to the user (this happens in tcp_usrreq.c,
5720 	 * case PRU_RCVD).  If a FIN has already been received on this
5721 	 * connection then we just ignore the text.
5722 	 *
5723 	 * If we are in SYN-received state and got a valid TFO cookie, we want
5724 	 * to process the data.
5725 	 */
5726 	if ((tlen || (thflags & TH_FIN)) &&
5727 	    TCPS_HAVERCVDFIN(tp->t_state) == 0 &&
5728 	    (TCPS_HAVEESTABLISHED(tp->t_state) ||
5729 	    (tp->t_state == TCPS_SYN_RECEIVED &&
5730 	    (tp->t_tfo_flags & TFO_F_COOKIE_VALID)))) {
5731 		tcp_seq save_start = th->th_seq;
5732 		tcp_seq save_end = th->th_seq + tlen;
5733 		m_adj(m, drop_hdrlen);  /* delayed header drop */
5734 		/*
5735 		 * Insert segment which includes th into TCP reassembly queue
5736 		 * with control block tp.  Set thflags to whether reassembly now
5737 		 * includes a segment with FIN.  This handles the common case
5738 		 * inline (segment is the next to be received on an established
5739 		 * connection, and the queue is empty), avoiding linkage into
5740 		 * and removal from the queue and repetition of various
5741 		 * conversions.
5742 		 * Set DELACK for segments received in order, but ack
5743 		 * immediately when segments are out of order (so
5744 		 * fast retransmit can work).
5745 		 */
5746 		if (th->th_seq == tp->rcv_nxt && LIST_EMPTY(&tp->t_segq)) {
5747 			TCP_INC_VAR(tp->t_unacksegs, segment_count);
5748 
5749 			/* Calculate the RTT on the receiver */
5750 			tcp_compute_rcv_rtt(tp, &to, th);
5751 
5752 			if (DELAY_ACK(tp, th) &&
5753 			    ((tp->t_flags & TF_ACKNOW) == 0)) {
5754 				if ((tp->t_flags & TF_DELACK) == 0) {
5755 					tp->t_flags |= TF_DELACK;
5756 					tp->t_timer[TCPT_DELACK] =
5757 					    OFFSET_FROM_START(tp, tcp_delack);
5758 				}
5759 			} else {
5760 				tp->t_flags |= TF_ACKNOW;
5761 			}
5762 			tp->rcv_nxt += tlen;
5763 			/* Update highest received sequence and its timestamp */
5764 			if (SEQ_LT(tp->rcv_high, tp->rcv_nxt)) {
5765 				tp->rcv_high = tp->rcv_nxt;
5766 				if (to.to_flags & TOF_TS) {
5767 					tp->tsv_high = to.to_tsval;
5768 				}
5769 			}
5770 
5771 			thflags = th->th_flags & TH_FIN;
5772 			TCP_INC_VAR(tcpstat.tcps_rcvpack, segment_count);
5773 			tcpstat.tcps_rcvbyte += tlen;
5774 			if (nstat_collect) {
5775 				INP_ADD_STAT(inp, ifnet_count_type,
5776 				    rxpackets, 1);
5777 				INP_ADD_STAT(inp, ifnet_count_type,
5778 				    rxbytes, tlen);
5779 				inp_set_activity_bitmap(inp);
5780 			}
5781 			tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5782 			if (TCP_USE_RLEDBAT(tp, so) &&
5783 			    tcp_cc_rledbat.data_rcvd != NULL) {
5784 				tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5785 			}
5786 
5787 			so_recv_data_stat(so, m, drop_hdrlen);
5788 
5789 			if (isipv6) {
5790 				memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5791 				ip6 = (struct ip6_hdr *)&saved_hdr[0];
5792 			} else {
5793 				memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5794 				ip = (struct ip *)&saved_hdr[0];
5795 			}
5796 			memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5797 
5798 			if (th->th_flags & TH_PUSH) {
5799 				tp->t_flagsext |= TF_LAST_IS_PSH;
5800 			} else {
5801 				tp->t_flagsext &= ~TF_LAST_IS_PSH;
5802 			}
5803 
5804 			if (sbappendstream_rcvdemux(so, m)) {
5805 				read_wakeup = 1;
5806 			}
5807 			th = &saved_tcphdr;
5808 		} else {
5809 			if (isipv6) {
5810 				memcpy(&saved_hdr, ip6, sizeof(struct ip6_hdr));
5811 				ip6 = (struct ip6_hdr *)&saved_hdr[0];
5812 			} else {
5813 				memcpy(&saved_hdr, ip, ip->ip_hl << 2);
5814 				ip = (struct ip *)&saved_hdr[0];
5815 			}
5816 
5817 			/* Update highest received sequence and its timestamp */
5818 			if (SEQ_LT(tp->rcv_high, th->th_seq + tlen)) {
5819 				tp->rcv_high = th->th_seq + tlen;
5820 				if (to.to_flags & TOF_TS) {
5821 					tp->tsv_high = to.to_tsval;
5822 				}
5823 			}
5824 
5825 			/*
5826 			 * Calculate the RTT on the receiver,
5827 			 * even if OOO segment is received.
5828 			 */
5829 			tcp_compute_rcv_rtt(tp, &to, th);
5830 
5831 			if (tcp_autotune_reorder) {
5832 				tcp_sbrcv_grow(tp, &so->so_rcv, &to, tlen);
5833 			}
5834 			if (TCP_USE_RLEDBAT(tp, so) &&
5835 			    tcp_cc_rledbat.data_rcvd != NULL) {
5836 				tcp_cc_rledbat.data_rcvd(tp, th, &to, tlen);
5837 			}
5838 
5839 			memcpy(&saved_tcphdr, th, sizeof(struct tcphdr));
5840 			thflags = tcp_reass(tp, th, &tlen, m, ifp, &read_wakeup);
5841 			th = &saved_tcphdr;
5842 			tp->t_flags |= TF_ACKNOW;
5843 		}
5844 
5845 		if ((tlen > 0 || (th->th_flags & TH_FIN)) && SACK_ENABLED(tp)) {
5846 			if (th->th_flags & TH_FIN) {
5847 				save_end++;
5848 			}
5849 			tcp_update_sack_list(tp, save_start, save_end);
5850 		}
5851 
5852 		tcp_adaptive_rwtimo_check(tp, tlen);
5853 
5854 		if (tlen > 0) {
5855 			tcp_tfo_rcv_data(tp);
5856 		}
5857 
5858 		if (tp->t_flags & TF_DELACK) {
5859 			if (isipv6) {
5860 				KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5861 				    (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
5862 				    th->th_seq, th->th_ack, th->th_win);
5863 			} else {
5864 				KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
5865 				    (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
5866 				    th->th_seq, th->th_ack, th->th_win);
5867 			}
5868 		}
5869 	} else {
5870 		if ((so->so_flags & SOF_MP_SUBFLOW) && tlen == 0 &&
5871 		    (m->m_pkthdr.pkt_flags & PKTF_MPTCP_DFIN) &&
5872 		    (m->m_pkthdr.pkt_flags & PKTF_MPTCP)) {
5873 			m_adj(m, drop_hdrlen);  /* delayed header drop */
5874 			/*
5875 			 * 0-length DATA_FIN. The rlen is actually 0. We special-case the
5876 			 * byte consumed by the dfin in mptcp_input and mptcp_reass_present
5877 			 */
5878 			m->m_pkthdr.mp_rlen = 0;
5879 			mptcp_input(tptomptp(tp)->mpt_mpte, m);
5880 			tp->t_flags |= TF_ACKNOW;
5881 		} else {
5882 			m_freem(m);
5883 		}
5884 		thflags &= ~TH_FIN;
5885 	}
5886 	/*
5887 	 * We increment t_unacksegs_ce for both data segments and pure ACKs
5888 	 * No need to increment if a FIN has already been received.
5889 	 */
5890 	if (TCP_ACC_ECN_ON(tp) && TCPS_HAVEESTABLISHED(tp->t_state) &&
5891 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5892 		if (ip_ecn == IPTOS_ECN_CE) {
5893 			TCP_INC_VAR(tp->t_unacksegs_ce, segment_count);
5894 		}
5895 		/*
5896 		 * Send an ACK immediately if there is a change in IP ECN
5897 		 * from non-CE to CE.
5898 		 * If new data is delivered, then ACK for every 2 CE marks,
5899 		 * otherwise ACK for every 3 CE marks
5900 		 */
5901 		if ((ip_ecn == IPTOS_ECN_CE && ip_ecn != tp->t_prev_ip_ecn) ||
5902 		    (tp->t_unacksegs_ce >= 2 && tp->last_ack_sent != tp->rcv_nxt) ||
5903 		    tp->t_unacksegs_ce >= 3) {
5904 			tp->t_flags |= TF_ACKNOW;
5905 		}
5906 		tp->t_prev_ip_ecn = ip_ecn;
5907 	}
5908 	/*
5909 	 * If FIN is received ACK the FIN and let the user know
5910 	 * that the connection is closing.
5911 	 */
5912 	if (thflags & TH_FIN) {
5913 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
5914 			socantrcvmore(so);
5915 			/*
5916 			 * If connection is half-synchronized
5917 			 * (ie NEEDSYN flag on) then delay ACK,
5918 			 * so it may be piggybacked when SYN is sent.
5919 			 * Otherwise, since we received a FIN then no
5920 			 * more input can be expected, send ACK now.
5921 			 */
5922 			TCP_INC_VAR(tp->t_unacksegs, segment_count);
5923 			tp->t_flags |= TF_ACKNOW;
5924 			tp->rcv_nxt++;
5925 		}
5926 		switch (tp->t_state) {
5927 		/*
5928 		 * In SYN_RECEIVED and ESTABLISHED STATES
5929 		 * enter the CLOSE_WAIT state.
5930 		 */
5931 		case TCPS_SYN_RECEIVED:
5932 			tp->t_starttime = tcp_now;
5933 			OS_FALLTHROUGH;
5934 		case TCPS_ESTABLISHED:
5935 			DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5936 			    struct tcpcb *, tp, int32_t, TCPS_CLOSE_WAIT);
5937 			TCP_LOG_STATE(tp, TCPS_CLOSE_WAIT);
5938 			tp->t_state = TCPS_CLOSE_WAIT;
5939 			break;
5940 
5941 		/*
5942 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
5943 		 * enter the CLOSING state.
5944 		 */
5945 		case TCPS_FIN_WAIT_1:
5946 			DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
5947 			    struct tcpcb *, tp, int32_t, TCPS_CLOSING);
5948 			TCP_LOG_STATE(tp, TCPS_CLOSING);
5949 			tp->t_state = TCPS_CLOSING;
5950 			break;
5951 
5952 		/*
5953 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
5954 		 * starting the time-wait timer, turning off the other
5955 		 * standard timers.
5956 		 */
5957 		case TCPS_FIN_WAIT_2:
5958 			DTRACE_TCP4(state__change, void, NULL,
5959 			    struct inpcb *, inp,
5960 			    struct tcpcb *, tp,
5961 			    int32_t, TCPS_TIME_WAIT);
5962 			TCP_LOG_STATE(tp, TCPS_TIME_WAIT);
5963 			tp->t_state = TCPS_TIME_WAIT;
5964 			tcp_canceltimers(tp);
5965 			tp->t_flags |= TF_ACKNOW;
5966 			if (tp->t_flagsext & TF_NOTIMEWAIT) {
5967 				tp->t_flags |= TF_CLOSING;
5968 			} else {
5969 				add_to_time_wait(tp, 2 * tcp_msl);
5970 			}
5971 			soisdisconnected(so);
5972 			break;
5973 
5974 		/*
5975 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
5976 		 */
5977 		case TCPS_TIME_WAIT:
5978 			add_to_time_wait(tp, 2 * tcp_msl);
5979 			break;
5980 		}
5981 	}
5982 	if (read_wakeup) {
5983 		mptcp_handle_input(so);
5984 	}
5985 
5986 	/*
5987 	 * Return any desired output.
5988 	 */
5989 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
5990 		(void) tcp_output(tp);
5991 	}
5992 
5993 	tcp_check_timer_state(tp);
5994 
5995 	tcp_handle_wakeup(so, read_wakeup, write_wakeup);
5996 
5997 	socket_unlock(so, 1);
5998 	KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
5999 	return;
6000 
6001 dropafterack:
6002 	/*
6003 	 * Generate an ACK dropping incoming segment if it occupies
6004 	 * sequence space, where the ACK reflects our state.
6005 	 *
6006 	 * We can now skip the test for the RST flag since all
6007 	 * paths to this code happen after packets containing
6008 	 * RST have been dropped.
6009 	 *
6010 	 * In the SYN-RECEIVED state, don't send an ACK unless the
6011 	 * segment we received passes the SYN-RECEIVED ACK test.
6012 	 * If it fails send a RST.  This breaks the loop in the
6013 	 * "LAND" DoS attack, and also prevents an ACK storm
6014 	 * between two listening ports that have been sent forged
6015 	 * SYN segments, each with the source address of the other.
6016 	 */
6017 	if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
6018 	    (SEQ_GT(tp->snd_una, th->th_ack) ||
6019 	    SEQ_GT(th->th_ack, tp->snd_max))) {
6020 		IF_TCP_STATINC(ifp, dospacket);
6021 		goto dropwithreset;
6022 	}
6023 	m_freem(m);
6024 	tp->t_flags |= TF_ACKNOW;
6025 
6026 	(void) tcp_output(tp);
6027 
6028 	tcp_handle_wakeup(so, read_wakeup, write_wakeup);
6029 
6030 	/* Don't need to check timer state as we should have done it during tcp_output */
6031 	socket_unlock(so, 1);
6032 	KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
6033 	return;
6034 dropwithresetnosock:
6035 	nosock = 1;
6036 dropwithreset:
6037 	/*
6038 	 * Generate a RST, dropping incoming segment.
6039 	 * Make ACK acceptable to originator of segment.
6040 	 * Don't bother to respond if destination was broadcast/multicast.
6041 	 */
6042 	if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST)) {
6043 		goto drop;
6044 	}
6045 	if (isipv6) {
6046 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
6047 		    IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
6048 			goto drop;
6049 		}
6050 	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
6051 	    IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
6052 	    ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
6053 	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
6054 		goto drop;
6055 	}
6056 	/* IPv6 anycast check is done at tcp6_input() */
6057 
6058 	bzero(&tra, sizeof(tra));
6059 	tra.ifscope = ifscope;
6060 	tra.awdl_unrestricted = 1;
6061 	tra.intcoproc_allowed = 1;
6062 	tra.management_allowed = 1;
6063 	if (thflags & TH_ACK) {
6064 		/* mtod() below is safe as long as hdr dropping is delayed */
6065 		tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
6066 		    TH_RST, &tra);
6067 	} else {
6068 		if (thflags & TH_SYN) {
6069 			tlen++;
6070 		}
6071 		/* mtod() below is safe as long as hdr dropping is delayed */
6072 		tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
6073 		    (tcp_seq)0, TH_RST | TH_ACK, &tra);
6074 	}
6075 	/* destroy temporarily created socket */
6076 	if (dropsocket) {
6077 		(void) soabort(so);
6078 		socket_unlock(so, 1);
6079 	} else if ((inp != NULL) && (nosock == 0)) {
6080 		tcp_handle_wakeup(so, read_wakeup, write_wakeup);
6081 
6082 		socket_unlock(so, 1);
6083 	}
6084 	KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
6085 	return;
6086 dropnosock:
6087 	nosock = 1;
6088 drop:
6089 	/*
6090 	 * Drop space held by incoming segment and return.
6091 	 */
6092 	if (isipv6 == 0) {
6093 		if (ip == NULL) {
6094 			ip = mtod(m, struct ip *);
6095 		}
6096 		/* add back the header length */
6097 		ip->ip_len += (ip->ip_hl << 2);
6098 		HTONS(ip->ip_len);
6099 		HTONS(ip->ip_off);
6100 
6101 		th = (struct tcphdr *)(void *)((caddr_t)ip + off0);
6102 	} else if (ip6 == NULL) {
6103 		ip6 = mtod(m, struct ip6_hdr *);
6104 
6105 		th = (struct tcphdr *)(void *)((caddr_t)ip6 + off0);
6106 	}
6107 	if (is_th_swapped) {
6108 		HTONL(th->th_seq);
6109 		HTONL(th->th_ack);
6110 		HTONS(th->th_win);
6111 		HTONS(th->th_urp);
6112 	}
6113 	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
6114 	/* destroy temporarily created socket */
6115 	if (dropsocket) {
6116 		(void) soabort(so);
6117 		socket_unlock(so, 1);
6118 	} else if (nosock == 0) {
6119 		tcp_handle_wakeup(so, read_wakeup, write_wakeup);
6120 
6121 		socket_unlock(so, 1);
6122 	}
6123 	KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END, 0, 0, 0, 0, 0);
6124 	return;
6125 }
6126 
6127 /*
6128  * Parse TCP options and place in tcpopt.
6129  */
6130 static void
tcp_dooptions(struct tcpcb * tp,u_char * cp,int cnt,struct tcphdr * th,struct tcpopt * to)6131 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
6132     struct tcpopt *to)
6133 {
6134 	u_short mss = 0;
6135 	uint8_t opt, optlen;
6136 
6137 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
6138 		opt = cp[0];
6139 		if (opt == TCPOPT_EOL) {
6140 			break;
6141 		}
6142 		if (opt == TCPOPT_NOP) {
6143 			optlen = 1;
6144 		} else {
6145 			if (cnt < 2) {
6146 				break;
6147 			}
6148 			optlen = cp[1];
6149 			if (optlen < 2 || optlen > cnt) {
6150 				break;
6151 			}
6152 		}
6153 		switch (opt) {
6154 		default:
6155 			continue;
6156 
6157 		case TCPOPT_MAXSEG:
6158 			if (optlen != TCPOLEN_MAXSEG) {
6159 				continue;
6160 			}
6161 			if (!(th->th_flags & TH_SYN)) {
6162 				continue;
6163 			}
6164 			bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
6165 			NTOHS(mss);
6166 			to->to_mss = mss;
6167 			to->to_flags |= TOF_MSS;
6168 			break;
6169 
6170 		case TCPOPT_WINDOW:
6171 			if (optlen != TCPOLEN_WINDOW) {
6172 				continue;
6173 			}
6174 			if (!(th->th_flags & TH_SYN)) {
6175 				continue;
6176 			}
6177 			to->to_flags |= TOF_SCALE;
6178 			to->to_requested_s_scale = MIN(cp[2], TCP_MAX_WINSHIFT);
6179 			break;
6180 
6181 		case TCPOPT_TIMESTAMP:
6182 			if (optlen != TCPOLEN_TIMESTAMP) {
6183 				continue;
6184 			}
6185 			to->to_flags |= TOF_TS;
6186 			bcopy((char *)cp + 2,
6187 			    (char *)&to->to_tsval, sizeof(to->to_tsval));
6188 			NTOHL(to->to_tsval);
6189 			bcopy((char *)cp + 6,
6190 			    (char *)&to->to_tsecr, sizeof(to->to_tsecr));
6191 			NTOHL(to->to_tsecr);
6192 			to->to_tsecr -= tp->t_ts_offset;
6193 			/* Re-enable sending Timestamps if we received them */
6194 			if (!(tp->t_flags & TF_REQ_TSTMP) && tcp_do_timestamps) {
6195 				tp->t_flags |= TF_REQ_TSTMP;
6196 			}
6197 			break;
6198 		case TCPOPT_SACK_PERMITTED:
6199 			if (optlen != TCPOLEN_SACK_PERMITTED) {
6200 				continue;
6201 			}
6202 			if (th->th_flags & TH_SYN) {
6203 				to->to_flags |= TOF_SACK;
6204 			}
6205 			break;
6206 		case TCPOPT_SACK:
6207 			if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0) {
6208 				continue;
6209 			}
6210 			to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
6211 			to->to_sacks = cp + 2;
6212 			tcpstat.tcps_sack_rcv_blocks++;
6213 
6214 			break;
6215 		case TCPOPT_FASTOPEN:
6216 			if (optlen == TCPOLEN_FASTOPEN_REQ) {
6217 				if (tp->t_state != TCPS_LISTEN) {
6218 					continue;
6219 				}
6220 
6221 				to->to_flags |= TOF_TFOREQ;
6222 			} else {
6223 				if (optlen < TCPOLEN_FASTOPEN_REQ ||
6224 				    (optlen - TCPOLEN_FASTOPEN_REQ) > TFO_COOKIE_LEN_MAX ||
6225 				    (optlen - TCPOLEN_FASTOPEN_REQ) < TFO_COOKIE_LEN_MIN) {
6226 					continue;
6227 				}
6228 				if (tp->t_state != TCPS_LISTEN &&
6229 				    tp->t_state != TCPS_SYN_SENT) {
6230 					continue;
6231 				}
6232 
6233 				to->to_flags |= TOF_TFO;
6234 				to->to_tfo = cp + 1;
6235 			}
6236 
6237 			break;
6238 		case TCPOPT_ACCECN0:
6239 		case TCPOPT_ACCECN1:
6240 			if (optlen < (TCPOLEN_ACCECN_EMPTY + 1 * TCPOLEN_ACCECN_COUNTER) ||
6241 			    (optlen - 2) % TCPOLEN_ACCECN_COUNTER != 0) {
6242 				continue;
6243 			}
6244 			to->to_num_accecn = (optlen - 2) / TCPOLEN_ACCECN_COUNTER;
6245 			to->to_accecn = cp + 2;
6246 			if (opt == TCPOPT_ACCECN0) {
6247 				to->to_accecn_order = 0;
6248 			} else if (opt == TCPOPT_ACCECN1) {
6249 				to->to_accecn_order = 1;
6250 			}
6251 			break;
6252 
6253 #if MPTCP
6254 		case TCPOPT_MULTIPATH:
6255 			tcp_do_mptcp_options(tp, cp, th, to, optlen);
6256 			break;
6257 #endif /* MPTCP */
6258 		}
6259 	}
6260 }
6261 
6262 static void
tcp_finalize_options(struct tcpcb * tp,struct tcpopt * to,unsigned int ifscope)6263 tcp_finalize_options(struct tcpcb *tp, struct tcpopt *to, unsigned int ifscope)
6264 {
6265 	if (to->to_flags & TOF_TS) {
6266 		tp->t_flags |= TF_RCVD_TSTMP;
6267 		tp->ts_recent = to->to_tsval;
6268 		tp->ts_recent_age = tcp_now;
6269 	}
6270 	if (to->to_flags & TOF_MSS) {
6271 		tcp_mss(tp, to->to_mss, ifscope);
6272 	}
6273 	if (SACK_ENABLED(tp)) {
6274 		if (!(to->to_flags & TOF_SACK)) {
6275 			tp->t_flagsext &= ~(TF_SACK_ENABLE);
6276 		} else {
6277 			tp->t_flags |= TF_SACK_PERMIT;
6278 		}
6279 	}
6280 	if (to->to_flags & TOF_SCALE) {
6281 		tp->t_flags |= TF_RCVD_SCALE;
6282 		tp->requested_s_scale = to->to_requested_s_scale;
6283 
6284 		/* Re-enable window scaling, if the option is received */
6285 		if (tp->request_r_scale > 0) {
6286 			tp->t_flags |= TF_REQ_SCALE;
6287 		}
6288 	}
6289 }
6290 
6291 /*
6292  * Pull out of band byte out of a segment so
6293  * it doesn't appear in the user's data queue.
6294  * It is still reflected in the segment length for
6295  * sequencing purposes.
6296  *
6297  * @param off delayed to be droped hdrlen
6298  */
6299 static void
tcp_pulloutofband(struct socket * so,struct tcphdr * th,struct mbuf * m,int off)6300 tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
6301 {
6302 	int cnt = off + th->th_urp - 1;
6303 
6304 	while (cnt >= 0) {
6305 		if (m->m_len > cnt) {
6306 			char *cp = mtod(m, caddr_t) + cnt;
6307 			struct tcpcb *tp = sototcpcb(so);
6308 
6309 			tp->t_iobc = *cp;
6310 			tp->t_oobflags |= TCPOOB_HAVEDATA;
6311 			bcopy(cp + 1, cp, (unsigned)(m->m_len - cnt - 1));
6312 			m->m_len--;
6313 			if (m->m_flags & M_PKTHDR) {
6314 				m->m_pkthdr.len--;
6315 			}
6316 			return;
6317 		}
6318 		cnt -= m->m_len;
6319 		m = m->m_next;
6320 		if (m == 0) {
6321 			break;
6322 		}
6323 	}
6324 	panic("tcp_pulloutofband");
6325 }
6326 
6327 uint32_t
get_base_rtt(struct tcpcb * tp)6328 get_base_rtt(struct tcpcb *tp)
6329 {
6330 	struct rtentry *rt = tp->t_inpcb->inp_route.ro_rt;
6331 	return (rt == NULL) ? 0 : rt->rtt_min;
6332 }
6333 
6334 static void
update_curr_rtt(struct tcpcb * tp,uint32_t rtt)6335 update_curr_rtt(struct tcpcb * tp, uint32_t rtt)
6336 {
6337 	tp->curr_rtt_index = (tp->curr_rtt_index + 1) % NCURR_RTT_HIST;
6338 	tp->curr_rtt_hist[tp->curr_rtt_index] = rtt;
6339 
6340 	/* forget the old value and update minimum */
6341 	tp->curr_rtt_min = 0;
6342 	for (int i = 0; i < NCURR_RTT_HIST; ++i) {
6343 		if (tp->curr_rtt_hist[i] != 0 && (tp->curr_rtt_min == 0 ||
6344 		    tp->curr_rtt_hist[i] < tp->curr_rtt_min)) {
6345 			tp->curr_rtt_min = tp->curr_rtt_hist[i];
6346 		}
6347 	}
6348 }
6349 
6350 /* Each value of RTT base represents the minimum RTT seen in a minute.
6351  * We keep upto N_RTT_BASE minutes worth of history.
6352  */
6353 void
update_base_rtt(struct tcpcb * tp,uint32_t rtt)6354 update_base_rtt(struct tcpcb *tp, uint32_t rtt)
6355 {
6356 	u_int32_t base_rtt, i;
6357 	struct rtentry *rt;
6358 
6359 	if ((rt = tp->t_inpcb->inp_route.ro_rt) == NULL) {
6360 		return;
6361 	}
6362 	if (rt->rtt_expire_ts == 0) {
6363 		RT_LOCK_SPIN(rt);
6364 		if (rt->rtt_expire_ts != 0) {
6365 			RT_UNLOCK(rt);
6366 			goto update;
6367 		}
6368 		rt->rtt_expire_ts = tcp_now;
6369 		rt->rtt_index = 0;
6370 		rt->rtt_hist[0] = rtt;
6371 		rt->rtt_min = rtt;
6372 		RT_UNLOCK(rt);
6373 
6374 		tp->curr_rtt_index = 0;
6375 		tp->curr_rtt_hist[0] = rtt;
6376 		tp->curr_rtt_min = rtt;
6377 		return;
6378 	}
6379 update:
6380 #if TRAFFIC_MGT
6381 	/*
6382 	 * If the recv side is being throttled, check if the
6383 	 * current RTT is closer to the base RTT seen in
6384 	 * first (recent) two slots. If so, unthrottle the stream.
6385 	 */
6386 	if ((tp->t_flagsext & TF_RECV_THROTTLE) &&
6387 	    (int)(tcp_now - tp->t_recv_throttle_ts) >= TCP_RECV_THROTTLE_WIN) {
6388 		base_rtt = rt->rtt_min;
6389 		if (tp->t_rttcur <= (base_rtt + target_qdelay)) {
6390 			tp->t_flagsext &= ~TF_RECV_THROTTLE;
6391 			tp->t_recv_throttle_ts = 0;
6392 		}
6393 	}
6394 #endif /* TRAFFIC_MGT */
6395 
6396 	/* Update the next current RTT sample */
6397 	update_curr_rtt(tp, rtt);
6398 
6399 	if ((int)(tcp_now - rt->rtt_expire_ts) >=
6400 	    TCP_RTT_HISTORY_EXPIRE_TIME) {
6401 		RT_LOCK_SPIN(rt);
6402 		/* check the condition again to avoid race */
6403 		if ((int)(tcp_now - rt->rtt_expire_ts) >=
6404 		    TCP_RTT_HISTORY_EXPIRE_TIME) {
6405 			/* Set the base rtt to 0 for idle periods */
6406 			uint32_t times = MIN((tcp_now - rt->rtt_expire_ts) /
6407 			    TCP_RTT_HISTORY_EXPIRE_TIME, NRTT_HIST + 1);
6408 
6409 			for (i = rt->rtt_index + 1; i < rt->rtt_index + times; i++) {
6410 				rt->rtt_hist[i % NRTT_HIST] = 0;
6411 			}
6412 
6413 			rt->rtt_index = i % NRTT_HIST;
6414 			rt->rtt_hist[rt->rtt_index] = rtt;
6415 			rt->rtt_expire_ts = tcp_now;
6416 		} else {
6417 			rt->rtt_hist[rt->rtt_index] =
6418 			    min(rt->rtt_hist[rt->rtt_index], rtt);
6419 		}
6420 		/* forget the old value and update minimum */
6421 		rt->rtt_min = 0;
6422 		for (i = 0; i < NRTT_HIST; ++i) {
6423 			if (rt->rtt_hist[i] != 0 &&
6424 			    (rt->rtt_min == 0 ||
6425 			    rt->rtt_hist[i] < rt->rtt_min)) {
6426 				rt->rtt_min = rt->rtt_hist[i];
6427 			}
6428 		}
6429 		RT_UNLOCK(rt);
6430 	} else {
6431 		rt->rtt_hist[rt->rtt_index] =
6432 		    min(rt->rtt_hist[rt->rtt_index], rtt);
6433 		if (rt->rtt_min == 0) {
6434 			rt->rtt_min = rtt;
6435 		} else {
6436 			rt->rtt_min = min(rt->rtt_min, rtt);
6437 		}
6438 	}
6439 }
6440 
6441 /*
6442  * If we have a timestamp reply, update smoothed RTT. If no timestamp is
6443  * present but transmit timer is running and timed sequence number was
6444  * acked, update smoothed RTT.
6445  *
6446  * If timestamps are supported, a receiver can update RTT even if
6447  * there is no outstanding data.
6448  *
6449  * Some boxes send broken timestamp replies during the SYN+ACK phase,
6450  * ignore timestamps of 0or we could calculate a huge RTT and blow up
6451  * the retransmit timer.
6452  */
6453 static void
tcp_compute_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)6454 tcp_compute_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
6455 {
6456 	int rtt = 0;
6457 	VERIFY(to != NULL && th != NULL);
6458 	if (tp->t_rtttime != 0 && SEQ_GT(th->th_ack, tp->t_rtseq)) {
6459 		u_int32_t pipe_ack_val;
6460 		rtt = tcp_now - tp->t_rtttime;
6461 		if (rtt == 0) {
6462 			/*
6463 			 * Make adjustment for sub ms RTT when
6464 			 * timestamps are not used.
6465 			 */
6466 			rtt = 1;
6467 		}
6468 		/*
6469 		 * Compute pipe ack -- the amount of data acknowledged
6470 		 * in the last RTT -- only works for sender
6471 		 */
6472 		if (SEQ_GT(th->th_ack, tp->t_pipeack_lastuna)) {
6473 			pipe_ack_val = th->th_ack - tp->t_pipeack_lastuna;
6474 			/* Update the sample */
6475 			tp->t_pipeack_sample[tp->t_pipeack_ind++] =
6476 			    pipe_ack_val;
6477 			tp->t_pipeack_ind %= TCP_PIPEACK_SAMPLE_COUNT;
6478 
6479 			/* Compute the max of the pipeack samples */
6480 			pipe_ack_val = tcp_get_max_pipeack(tp);
6481 			tp->t_pipeack = (pipe_ack_val >
6482 			    tcp_initial_cwnd(tp)) ?
6483 			    pipe_ack_val : 0;
6484 		}
6485 		/* start another measurement */
6486 		tp->t_rtttime = 0;
6487 	}
6488 	if (((to->to_flags & TOF_TS) != 0) &&
6489 	    (to->to_tsecr != 0) &&
6490 	    TSTMP_GEQ(tcp_now, to->to_tsecr)) {
6491 		tcp_xmit_timer(tp, (tcp_now - to->to_tsecr),
6492 		    to->to_tsecr, th->th_ack);
6493 	} else if (rtt > 0) {
6494 		tcp_xmit_timer(tp, rtt, 0, th->th_ack);
6495 	}
6496 }
6497 
6498 static void
tcp_compute_rcv_rtt(struct tcpcb * tp,struct tcpopt * to,struct tcphdr * th)6499 tcp_compute_rcv_rtt(struct tcpcb *tp, struct tcpopt *to, struct tcphdr *th)
6500 {
6501 	uint32_t rtt = 0, delta = 0;
6502 	VERIFY(to != NULL && th != NULL);
6503 
6504 	/* Calculate RTT */
6505 	if (((to->to_flags & TOF_TS) != 0) && (to->to_tsecr != 0) &&
6506 	    TSTMP_GEQ(tcp_now, to->to_tsecr)) {
6507 		/* Timestamp is supported */
6508 		rtt = tcp_now - to->to_tsecr;
6509 		if (rtt == 0) {
6510 			/* Make adjustment for sub ms RTT */
6511 			rtt = 1;
6512 		}
6513 	} else if ((to->to_flags & TOF_TS) == 0) {
6514 		/*
6515 		 * Timestamp is not supported, 1RTT is roughly
6516 		 * the time to receive one full window of data
6517 		 * Currently, RTT calculated this way is only used
6518 		 * for auto-tuning.
6519 		 */
6520 		if (tp->rcv_rtt_est_ts != 0) {
6521 			if (SEQ_LT(tp->rcv_nxt, tp->rcv_rtt_est_seq)) {
6522 				/* Haven't received a full window yet */
6523 				return;
6524 			} else {
6525 				rtt = tcp_now - tp->rcv_rtt_est_ts;
6526 				if (rtt == 0) {
6527 					/* Make adjustment for sub ms RTT */
6528 					rtt = 1;
6529 				}
6530 			}
6531 		} else {
6532 			/* Use default value when no RTT measurement */
6533 			rtt = TCPTV_RCVNOTS_QUANTUM;
6534 		}
6535 		/* Restart the measurement */
6536 		tp->rcv_rtt_est_ts = tcp_now;
6537 		tp->rcv_rtt_est_seq = tp->rcv_nxt + tp->rcv_wnd;
6538 	}
6539 
6540 	/* Update receiver's SRTT */
6541 	if (tp->rcv_srtt != 0) {
6542 		/*
6543 		 * Use the smoothed rtt formula,
6544 		 * (srtt = rtt/8 + srtt*7/8) in fixed point
6545 		 */
6546 		delta = (rtt << TCP_DELTA_SHIFT)
6547 		    - (tp->rcv_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6548 
6549 		if ((tp->rcv_srtt += delta) <= 0) {
6550 			tp->rcv_srtt = 1;
6551 		}
6552 	} else {
6553 		/* No previous measurement */
6554 		tp->rcv_srtt = rtt << TCP_RTT_SHIFT;
6555 	}
6556 
6557 	/*
6558 	 * For current RTT, base RTT and current RTT over k samples,
6559 	 * we are using the same state for both sender and receiver
6560 	 * as the most recent sample is always updated before any
6561 	 * other processing, i.e. the sender will not end up with
6562 	 * a high RTT due to the receiver.
6563 	 */
6564 	tp->t_rttcur = rtt;
6565 	update_base_rtt(tp, rtt);
6566 }
6567 
6568 /*
6569  * Collect new round-trip time estimate and update averages and
6570  * current timeout.
6571  */
6572 static void
tcp_xmit_timer(struct tcpcb * tp,int rtt,u_int32_t tsecr,tcp_seq th_ack)6573 tcp_xmit_timer(struct tcpcb *tp, int rtt,
6574     u_int32_t tsecr, tcp_seq th_ack)
6575 {
6576 	VERIFY(rtt >= 0);
6577 	int delta;
6578 	int old_srtt = tp->t_srtt;
6579 	int old_rttvar = tp->t_rttvar;
6580 	bool log_rtt = false;
6581 
6582 	if (rtt == 0) {
6583 		/*
6584 		 * As rtt has millisecond precision,
6585 		 * make adjustment for sub ms RTT
6586 		 */
6587 		rtt = 1;
6588 	}
6589 
6590 	if (rtt > 4 * TCPTV_MSL) {
6591 		TCP_LOG(tp, "%s: rtt is %d - maxing it at 4 x MSL\n", __func__, rtt);
6592 		/*
6593 		 * We compute RTT either based on the time-to-ACK a packet,
6594 		 * if TSval is disabled or based on the TSecr value.
6595 		 * If there is a middlebox messing up the TSecr value, we can
6596 		 * end up having HUGE rtt values, causing all kinds of problems.
6597 		 * Let's protect against this by capping RTT to 4*MSL
6598 		 * (60seconds).
6599 		 */
6600 		rtt = 4 * TCPTV_MSL;
6601 	}
6602 
6603 	/*
6604 	 * On AWDL interface, the initial RTT measurement on SYN
6605 	 * can be wrong due to peer caching. Avoid the first RTT
6606 	 * measurement as it might skew up the RTO.
6607 	 * <rdar://problem/28739046>
6608 	 */
6609 	if (tp->t_inpcb->inp_last_outifp != NULL &&
6610 	    (tp->t_inpcb->inp_last_outifp->if_eflags & IFEF_AWDL) &&
6611 	    th_ack == tp->iss + 1) {
6612 		return;
6613 	}
6614 
6615 	if (tp->t_flagsext & TF_RECOMPUTE_RTT) {
6616 		if (SEQ_GT(th_ack, tp->snd_una) &&
6617 		    SEQ_LEQ(th_ack, tp->snd_max) &&
6618 		    (tsecr == 0 ||
6619 		    TSTMP_GEQ(tsecr, tp->t_badrexmt_time))) {
6620 			/*
6621 			 * We received a new ACK after a
6622 			 * spurious timeout. Adapt retransmission
6623 			 * timer as described in rfc 4015.
6624 			 */
6625 			tp->t_flagsext &= ~(TF_RECOMPUTE_RTT);
6626 			tp->t_badrexmt_time = 0;
6627 			tp->t_srtt = max(tp->t_srtt_prev, rtt);
6628 			tp->t_srtt = tp->t_srtt << TCP_RTT_SHIFT;
6629 			tp->t_rttvar = max(tp->t_rttvar_prev, (rtt >> 1));
6630 			tp->t_rttvar = tp->t_rttvar << TCP_RTTVAR_SHIFT;
6631 
6632 			if (tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
6633 				tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6634 			}
6635 
6636 			goto compute_rto;
6637 		} else {
6638 			return;
6639 		}
6640 	}
6641 
6642 	tcpstat.tcps_rttupdated++;
6643 	tp->t_rttupdated++;
6644 
6645 	tp->t_rttcur = rtt;
6646 	update_base_rtt(tp, rtt);
6647 
6648 	if (tp->t_srtt != 0) {
6649 		/*
6650 		 * srtt is stored as fixed point with 5 bits after the
6651 		 * binary point (i.e., scaled by 32).  The following magic
6652 		 * is equivalent to the smoothing algorithm in rfc793 with
6653 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
6654 		 * point).
6655 		 *
6656 		 * Freebsd adjusts rtt to origin 0 by subtracting 1
6657 		 * from the provided rtt value. This was required because
6658 		 * of the way t_rtttime was initiailised to 1 before.
6659 		 * Since we changed t_rtttime to be based on
6660 		 * tcp_now, this extra adjustment is not needed.
6661 		 */
6662 		delta = (rtt << TCP_DELTA_SHIFT)
6663 		    - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
6664 
6665 		if ((tp->t_srtt += delta) <= 0) {
6666 			tp->t_srtt = 1;
6667 		}
6668 
6669 		/*
6670 		 * We accumulate a smoothed rtt variance (actually, a
6671 		 * smoothed mean difference), then set the retransmit
6672 		 * timer to smoothed rtt + 4 times the smoothed variance.
6673 		 * rttvar is stored as fixed point with 4 bits after the
6674 		 * binary point (scaled by 16).  The following is
6675 		 * equivalent to rfc793 smoothing with an alpha of .75
6676 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
6677 		 * rfc793's wired-in beta.
6678 		 */
6679 		if (delta < 0) {
6680 			delta = -delta;
6681 		}
6682 		delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
6683 		if ((tp->t_rttvar += delta) <= 0) {
6684 			tp->t_rttvar = 1;
6685 		}
6686 		if (tp->t_rttbest == 0 ||
6687 		    tp->t_rttbest > (tp->t_srtt + tp->t_rttvar)) {
6688 			tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6689 		}
6690 	} else {
6691 		/*
6692 		 * No rtt measurement yet - use the unsmoothed rtt.
6693 		 * Set the variance to half the rtt (so our first
6694 		 * retransmit happens at 3*rtt).
6695 		 */
6696 		tp->t_srtt = rtt << TCP_RTT_SHIFT;
6697 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
6698 		tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
6699 
6700 		/* Initialize the receive SRTT */
6701 		if (tp->rcv_srtt == 0) {
6702 			tp->rcv_srtt = tp->t_srtt;
6703 		}
6704 	}
6705 
6706 compute_rto:
6707 	nstat_route_rtt(tp->t_inpcb->inp_route.ro_rt, tp->t_srtt,
6708 	    tp->t_rttvar);
6709 
6710 	/*
6711 	 * the retransmit should happen at rtt + 4 * rttvar.
6712 	 * Because of the way we do the smoothing, srtt and rttvar
6713 	 * will each average +1/2 tick of bias.  When we compute
6714 	 * the retransmit timer, we want 1/2 tick of rounding and
6715 	 * 1 extra tick because of +-1/2 tick uncertainty in the
6716 	 * firing of the timer.  The bias will give us exactly the
6717 	 * 1.5 tick we need.  But, because the bias is
6718 	 * statistical, we have to test that we don't drop below
6719 	 * the minimum feasible timer (which is 2 ticks).
6720 	 */
6721 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
6722 	    max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX,
6723 	    TCP_ADD_REXMTSLOP(tp));
6724 
6725 	/*
6726 	 * We received an ack for a packet that wasn't retransmitted;
6727 	 * it is probably safe to discard any error indications we've
6728 	 * received recently.  This isn't quite right, but close enough
6729 	 * for now (a route might have failed after we sent a segment,
6730 	 * and the return path might not be symmetrical).
6731 	 */
6732 	tp->t_softerror = 0;
6733 
6734 	if (log_rtt) {
6735 		TCP_LOG_RTT_INFO(tp);
6736 	}
6737 
6738 	TCP_LOG_RTT_CHANGE(tp, old_srtt, old_rttvar);
6739 }
6740 
6741 static inline unsigned int
tcp_maxmtu(struct rtentry * rt)6742 tcp_maxmtu(struct rtentry *rt)
6743 {
6744 	unsigned int maxmtu;
6745 	int interface_mtu = 0;
6746 
6747 	RT_LOCK_ASSERT_HELD(rt);
6748 	interface_mtu = rt->rt_ifp->if_mtu;
6749 
6750 	if (rt_key(rt)->sa_family == AF_INET &&
6751 	    INTF_ADJUST_MTU_FOR_CLAT46(rt->rt_ifp)) {
6752 		interface_mtu = IN6_LINKMTU(rt->rt_ifp);
6753 		/* Further adjust the size for CLAT46 expansion */
6754 		interface_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
6755 	}
6756 
6757 	if (rt->rt_rmx.rmx_mtu == 0) {
6758 		maxmtu = interface_mtu;
6759 	} else {
6760 		maxmtu = MIN(rt->rt_rmx.rmx_mtu, interface_mtu);
6761 	}
6762 
6763 	return maxmtu;
6764 }
6765 
6766 static inline unsigned int
tcp_maxmtu6(struct rtentry * rt)6767 tcp_maxmtu6(struct rtentry *rt)
6768 {
6769 	unsigned int maxmtu;
6770 	struct nd_ifinfo *ndi = NULL;
6771 
6772 	RT_LOCK_ASSERT_HELD(rt);
6773 	if ((ndi = ND_IFINFO(rt->rt_ifp)) != NULL && !ndi->initialized) {
6774 		ndi = NULL;
6775 	}
6776 	if (ndi != NULL) {
6777 		lck_mtx_lock(&ndi->lock);
6778 	}
6779 	if (rt->rt_rmx.rmx_mtu == 0) {
6780 		maxmtu = IN6_LINKMTU(rt->rt_ifp);
6781 	} else {
6782 		maxmtu = MIN(rt->rt_rmx.rmx_mtu, IN6_LINKMTU(rt->rt_ifp));
6783 	}
6784 	if (ndi != NULL) {
6785 		lck_mtx_unlock(&ndi->lock);
6786 	}
6787 
6788 	return maxmtu;
6789 }
6790 
6791 unsigned int
get_maxmtu(struct rtentry * rt)6792 get_maxmtu(struct rtentry *rt)
6793 {
6794 	unsigned int maxmtu = 0;
6795 
6796 	RT_LOCK_ASSERT_NOTHELD(rt);
6797 
6798 	RT_LOCK(rt);
6799 
6800 	if (rt_key(rt)->sa_family == AF_INET6) {
6801 		maxmtu = tcp_maxmtu6(rt);
6802 	} else {
6803 		maxmtu = tcp_maxmtu(rt);
6804 	}
6805 
6806 	RT_UNLOCK(rt);
6807 
6808 	return maxmtu;
6809 }
6810 
6811 /*
6812  * Determine a reasonable value for maxseg size.
6813  * If the route is known, check route for mtu.
6814  * If none, use an mss that can be handled on the outgoing
6815  * interface without forcing IP to fragment; if bigger than
6816  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
6817  * to utilize large mbufs.  If no route is found, route has no mtu,
6818  * or the destination isn't local, use a default, hopefully conservative
6819  * size (usually 512 or the default IP max size, but no more than the mtu
6820  * of the interface), as we can't discover anything about intervening
6821  * gateways or networks.  We also initialize the congestion/slow start
6822  * window. While looking at the routing entry, we also initialize
6823  * other path-dependent parameters from pre-set or cached values
6824  * in the routing entry.
6825  *
6826  * Also take into account the space needed for options that we
6827  * send regularly.  Make maxseg shorter by that amount to assure
6828  * that we can send maxseg amount of data even when the options
6829  * are present.  Store the upper limit of the length of options plus
6830  * data in maxopd.
6831  *
6832  * NOTE that this routine is only called when we process an incoming
6833  * segment, for outgoing segments only tcp_mssopt is called.
6834  *
6835  */
6836 void
tcp_mss(struct tcpcb * tp,int offer,unsigned int input_ifscope)6837 tcp_mss(struct tcpcb *tp, int offer, unsigned int input_ifscope)
6838 {
6839 	struct rtentry *rt;
6840 	struct ifnet *ifp;
6841 	int rtt, mss;
6842 	uint32_t bufsize;
6843 	struct inpcb *inp;
6844 	struct socket *so;
6845 	int origoffer = offer;
6846 	int isipv6;
6847 	int min_protoh;
6848 
6849 	inp = tp->t_inpcb;
6850 
6851 	so = inp->inp_socket;
6852 	/*
6853 	 * Nothing left to send after the socket is defunct or TCP is in the closed state
6854 	 */
6855 	if ((so->so_state & SS_DEFUNCT) || tp->t_state == TCPS_CLOSED) {
6856 		return;
6857 	}
6858 
6859 	isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
6860 	min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
6861 	    : sizeof(struct tcpiphdr);
6862 
6863 	if (isipv6) {
6864 		rt = tcp_rtlookup6(inp, input_ifscope);
6865 	} else {
6866 		rt = tcp_rtlookup(inp, input_ifscope);
6867 	}
6868 
6869 	if (rt == NULL) {
6870 		tp->t_maxopd = tp->t_maxseg = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6871 		return;
6872 	}
6873 	ifp = rt->rt_ifp;
6874 	/*
6875 	 * Slower link window correction:
6876 	 * If a value is specificied for slowlink_wsize use it for
6877 	 * PPP links believed to be on a serial modem (speed <128Kbps).
6878 	 * Excludes 9600bps as it is the default value adversized
6879 	 * by pseudo-devices over ppp.
6880 	 */
6881 	if (ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
6882 	    ifp->if_baudrate > 9600 && ifp->if_baudrate <= 128000) {
6883 		tp->t_flags |= TF_SLOWLINK;
6884 	}
6885 
6886 	/*
6887 	 * Offer == -1 means that we didn't receive SYN yet. Use 0 then.
6888 	 */
6889 	if (offer == -1) {
6890 		offer = rt->rt_rmx.rmx_filler[0];
6891 	}
6892 	/*
6893 	 * Offer == 0 means that there was no MSS on the SYN segment,
6894 	 * in this case we use tcp_mssdflt.
6895 	 */
6896 	if (offer == 0) {
6897 		offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
6898 	} else {
6899 		/*
6900 		 * Prevent DoS attack with too small MSS. Round up
6901 		 * to at least minmss.
6902 		 */
6903 		offer = max(offer, tcp_minmss);
6904 		/*
6905 		 * Sanity check: make sure that maxopd will be large
6906 		 * enough to allow some data on segments even is the
6907 		 * all the option space is used (40bytes).  Otherwise
6908 		 * funny things may happen in tcp_output.
6909 		 */
6910 		offer = max(offer, 64);
6911 	}
6912 	rt->rt_rmx.rmx_filler[0] = offer;
6913 
6914 	/*
6915 	 * While we're here, check if there's an initial rtt
6916 	 * or rttvar.  Convert from the route-table units
6917 	 * to scaled multiples of the slow timeout timer.
6918 	 */
6919 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt) != 0) {
6920 		tcp_getrt_rtt(tp, rt);
6921 	} else {
6922 		tp->t_rttmin = TCPTV_REXMTMIN;
6923 	}
6924 
6925 	mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
6926 
6927 	mss = tcp_get_effective_mtu(rt, mss);
6928 #if NECP
6929 	// At this point, the mss is just the MTU. Adjust if necessary.
6930 	mss = necp_socket_get_effective_mtu(inp, mss);
6931 #endif /* NECP */
6932 
6933 	mss -= min_protoh;
6934 
6935 	if (rt->rt_rmx.rmx_mtu == 0) {
6936 		if (isipv6) {
6937 			mss = min(mss, tcp_v6mssdflt);
6938 		} else {
6939 			mss = min(mss, tcp_mssdflt);
6940 		}
6941 	}
6942 
6943 	mss = min(mss, offer);
6944 	/*
6945 	 * maxopd stores the maximum length of data AND options
6946 	 * in a segment; maxseg is the amount of data in a normal
6947 	 * segment.  We need to store this value (maxopd) apart
6948 	 * from maxseg, because now every segment carries options
6949 	 * and thus we normally have somewhat less data in segments.
6950 	 */
6951 	tp->t_maxopd = mss;
6952 
6953 	/*
6954 	 * origoffer==-1 indicates, that no segments were received yet.
6955 	 * In this case we just guess.
6956 	 */
6957 	if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
6958 	    (origoffer == -1 ||
6959 	    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)) {
6960 		mss -= TCPOLEN_TSTAMP_APPA;
6961 	}
6962 
6963 #if MPTCP
6964 	mss -= mptcp_adj_mss(tp, FALSE);
6965 #endif /* MPTCP */
6966 	tp->t_maxseg = mss;
6967 
6968 	/*
6969 	 * If there's a pipesize (ie loopback), change the socket
6970 	 * buffer to that size only if it's bigger than the current
6971 	 * sockbuf size.  Make the socket buffers an integral
6972 	 * number of mss units; if the mss is larger than
6973 	 * the socket buffer, decrease the mss.
6974 	 */
6975 #if RTV_SPIPE
6976 	bufsize = rt->rt_rmx.rmx_sendpipe;
6977 	if (bufsize < so->so_snd.sb_hiwat)
6978 #endif
6979 	bufsize = so->so_snd.sb_hiwat;
6980 	if (bufsize < mss) {
6981 		mss = bufsize;
6982 	} else {
6983 		bufsize = (((bufsize + mss - 1) / mss) * mss);
6984 		(void)sbreserve(&so->so_snd, bufsize);
6985 	}
6986 	tp->t_maxseg = mss;
6987 
6988 	ASSERT(tp->t_maxseg);
6989 
6990 	/*
6991 	 * Update MSS using recommendation from link status report. This is
6992 	 * temporary
6993 	 */
6994 	tcp_update_mss_locked(so, ifp);
6995 
6996 #if RTV_RPIPE
6997 	bufsize = rt->rt_rmx.rmx_recvpipe;
6998 	if (bufsize < so->so_rcv.sb_hiwat)
6999 #endif
7000 	bufsize = so->so_rcv.sb_hiwat;
7001 	if (bufsize > mss) {
7002 		bufsize = (((bufsize + mss - 1) / mss) * mss);
7003 		(void)sbreserve(&so->so_rcv, bufsize);
7004 	}
7005 
7006 	set_tcp_stream_priority(so);
7007 
7008 	if (rt->rt_rmx.rmx_ssthresh) {
7009 		/*
7010 		 * There's some sort of gateway or interface
7011 		 * buffer limit on the path.  Use this to set
7012 		 * slow-start threshold, but set the threshold to
7013 		 * no less than 2*mss.
7014 		 */
7015 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
7016 		tcpstat.tcps_usedssthresh++;
7017 	} else {
7018 		tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
7019 	}
7020 
7021 	/*
7022 	 * Set the slow-start flight size depending on whether this
7023 	 * is a local network or not.
7024 	 */
7025 	if (CC_ALGO(tp)->cwnd_init != NULL) {
7026 		CC_ALGO(tp)->cwnd_init(tp);
7027 	}
7028 
7029 	tcp_ccdbg_trace(tp, NULL, TCP_CC_CWND_INIT);
7030 
7031 	if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.rwnd_init != NULL) {
7032 		tcp_cc_rledbat.rwnd_init(tp);
7033 	}
7034 
7035 	/* Route locked during lookup above */
7036 	RT_UNLOCK(rt);
7037 }
7038 
7039 /*
7040  * Determine the MSS option to send on an outgoing SYN.
7041  */
7042 int
tcp_mssopt(struct tcpcb * tp)7043 tcp_mssopt(struct tcpcb *tp)
7044 {
7045 	struct rtentry *rt;
7046 	int mss;
7047 	int isipv6;
7048 	int min_protoh;
7049 
7050 	isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
7051 	min_protoh = isipv6 ? sizeof(struct ip6_hdr) + sizeof(struct tcphdr)
7052 	    : sizeof(struct tcpiphdr);
7053 
7054 	if (isipv6) {
7055 		rt = tcp_rtlookup6(tp->t_inpcb, IFSCOPE_NONE);
7056 	} else {
7057 		rt = tcp_rtlookup(tp->t_inpcb, IFSCOPE_NONE);
7058 	}
7059 	if (rt == NULL) {
7060 		return isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
7061 	}
7062 	/*
7063 	 * Slower link window correction:
7064 	 * If a value is specificied for slowlink_wsize use it for PPP links
7065 	 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
7066 	 * it is the default value adversized by pseudo-devices over ppp.
7067 	 */
7068 	if (rt->rt_ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
7069 	    rt->rt_ifp->if_baudrate > 9600 && rt->rt_ifp->if_baudrate <= 128000) {
7070 		tp->t_flags |= TF_SLOWLINK;
7071 	}
7072 
7073 	mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
7074 
7075 	mss = tcp_get_effective_mtu(rt, mss);
7076 
7077 	/* Route locked during lookup above */
7078 	RT_UNLOCK(rt);
7079 
7080 #if NECP
7081 	// At this point, the mss is just the MTU. Adjust if necessary.
7082 	mss = necp_socket_get_effective_mtu(tp->t_inpcb, mss);
7083 #endif /* NECP */
7084 
7085 	return mss - min_protoh;
7086 }
7087 
7088 /*
7089  * On a partial ack arrives, force the retransmission of the
7090  * next unacknowledged segment.  Do not clear tp->t_dupacks.
7091  * By setting snd_nxt to th_ack, this forces retransmission timer to
7092  * be started again.
7093  */
7094 static void
tcp_newreno_partial_ack(struct tcpcb * tp,struct tcphdr * th)7095 tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
7096 {
7097 	tcp_seq onxt = tp->snd_nxt;
7098 	u_int32_t  ocwnd = tp->snd_cwnd;
7099 	tp->t_timer[TCPT_REXMT] = 0;
7100 	tp->t_timer[TCPT_PTO] = 0;
7101 	tp->t_rtttime = 0;
7102 	tp->snd_nxt = th->th_ack;
7103 	/*
7104 	 * Set snd_cwnd to one segment beyond acknowledged offset
7105 	 * (tp->snd_una has not yet been updated when this function
7106 	 *  is called)
7107 	 */
7108 	tp->snd_cwnd = tp->t_maxseg + BYTES_ACKED(th, tp);
7109 	(void) tcp_output(tp);
7110 	tp->snd_cwnd = ocwnd;
7111 	if (SEQ_GT(onxt, tp->snd_nxt)) {
7112 		tp->snd_nxt = onxt;
7113 	}
7114 	/*
7115 	 * Partial window deflation.  Relies on fact that tp->snd_una
7116 	 * not updated yet.
7117 	 */
7118 	if (tp->snd_cwnd > BYTES_ACKED(th, tp)) {
7119 		tp->snd_cwnd -= BYTES_ACKED(th, tp);
7120 	} else {
7121 		tp->snd_cwnd = 0;
7122 	}
7123 	tp->snd_cwnd += tp->t_maxseg;
7124 }
7125 
7126 /*
7127  * Drop a random TCP connection that hasn't been serviced yet and
7128  * is eligible for discard.  There is a one in qlen chance that
7129  * we will return a null, saying that there are no dropable
7130  * requests.  In this case, the protocol specific code should drop
7131  * the new request.  This insures fairness.
7132  *
7133  * The listening TCP socket "head" must be locked
7134  */
7135 static int
tcp_dropdropablreq(struct socket * head)7136 tcp_dropdropablreq(struct socket *head)
7137 {
7138 	struct socket *so, *sonext;
7139 	unsigned int j, qlen;
7140 	static uint32_t rnd = 0;
7141 	static uint64_t old_runtime;
7142 	static unsigned int cur_cnt, old_cnt;
7143 	uint64_t now_sec, i;
7144 	struct inpcb *inp = NULL;
7145 	struct tcpcb *tp;
7146 
7147 	if ((head->so_options & SO_ACCEPTCONN) == 0) {
7148 		return 0;
7149 	}
7150 
7151 	if (TAILQ_EMPTY(&head->so_incomp)) {
7152 		return 0;
7153 	}
7154 
7155 	so_acquire_accept_list(head, NULL);
7156 	socket_unlock(head, 0);
7157 
7158 	/*
7159 	 * Check if there is any socket in the incomp queue
7160 	 * that is closed because of a reset from the peer and is
7161 	 * waiting to be garbage collected. If so, pick that as
7162 	 * the victim
7163 	 */
7164 	TAILQ_FOREACH_SAFE(so, &head->so_incomp, so_list, sonext) {
7165 		inp = sotoinpcb(so);
7166 		tp = intotcpcb(inp);
7167 		if (tp != NULL && tp->t_state == TCPS_CLOSED &&
7168 		    so->so_head != NULL &&
7169 		    (so->so_state & (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) ==
7170 		    (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) {
7171 			/*
7172 			 * The listen socket is already locked but we
7173 			 * can lock this socket here without lock ordering
7174 			 * issues because it is in the incomp queue and
7175 			 * is not visible to others.
7176 			 */
7177 			if (socket_try_lock(so)) {
7178 				so->so_usecount++;
7179 				goto found_victim;
7180 			} else {
7181 				continue;
7182 			}
7183 		}
7184 	}
7185 
7186 	so = TAILQ_FIRST(&head->so_incomp);
7187 
7188 	now_sec = net_uptime();
7189 	if ((i = (now_sec - old_runtime)) != 0) {
7190 		old_runtime = now_sec;
7191 		old_cnt = cur_cnt / i;
7192 		cur_cnt = 0;
7193 	}
7194 
7195 	qlen = head->so_incqlen;
7196 	if (rnd == 0) {
7197 		rnd = RandomULong();
7198 	}
7199 
7200 	if (++cur_cnt > qlen || old_cnt > qlen) {
7201 		rnd = (314159 * rnd + 66329) & 0xffff;
7202 		j = ((qlen + 1) * rnd) >> 16;
7203 
7204 		while (j-- && so) {
7205 			so = TAILQ_NEXT(so, so_list);
7206 		}
7207 	}
7208 	/* Find a connection that is not already closing (or being served) */
7209 	while (so) {
7210 		inp = (struct inpcb *)so->so_pcb;
7211 
7212 		sonext = TAILQ_NEXT(so, so_list);
7213 
7214 		if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
7215 			/*
7216 			 * Avoid the issue of a socket being accepted
7217 			 * by one input thread and being dropped by
7218 			 * another input thread. If we can't get a hold
7219 			 * on this mutex, then grab the next socket in
7220 			 * line.
7221 			 */
7222 			if (socket_try_lock(so)) {
7223 				so->so_usecount++;
7224 				if ((so->so_usecount == 2) &&
7225 				    (so->so_state & SS_INCOMP) &&
7226 				    !(so->so_flags & SOF_INCOMP_INPROGRESS)) {
7227 					break;
7228 				} else {
7229 					/*
7230 					 * don't use if being accepted or
7231 					 * used in any other way
7232 					 */
7233 					in_pcb_checkstate(inp, WNT_RELEASE, 1);
7234 					socket_unlock(so, 1);
7235 				}
7236 			} else {
7237 				/*
7238 				 * do not try to lock the inp in
7239 				 * in_pcb_checkstate because the lock
7240 				 * is already held in some other thread.
7241 				 * Only drop the inp_wntcnt reference.
7242 				 */
7243 				in_pcb_checkstate(inp, WNT_RELEASE, 1);
7244 			}
7245 		}
7246 		so = sonext;
7247 	}
7248 	if (so == NULL) {
7249 		socket_lock(head, 0);
7250 		so_release_accept_list(head);
7251 		return 0;
7252 	}
7253 
7254 	/* Makes sure socket is still in the right state to be discarded */
7255 
7256 	if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
7257 		socket_unlock(so, 1);
7258 		socket_lock(head, 0);
7259 		so_release_accept_list(head);
7260 		return 0;
7261 	}
7262 
7263 found_victim:
7264 	if (so->so_usecount != 2 || !(so->so_state & SS_INCOMP)) {
7265 		/* do not discard: that socket is being accepted */
7266 		socket_unlock(so, 1);
7267 		socket_lock(head, 0);
7268 		so_release_accept_list(head);
7269 		return 0;
7270 	}
7271 
7272 	socket_lock(head, 0);
7273 	TAILQ_REMOVE(&head->so_incomp, so, so_list);
7274 	head->so_incqlen--;
7275 	head->so_qlen--;
7276 	so->so_state &= ~SS_INCOMP;
7277 	so->so_flags |= SOF_OVERFLOW;
7278 	so->so_head = NULL;
7279 	so_release_accept_list(head);
7280 	socket_unlock(head, 0);
7281 
7282 	socket_lock_assert_owned(so);
7283 	tp = sototcpcb(so);
7284 
7285 	tcp_close(tp);
7286 	if (inp->inp_wantcnt > 0 && inp->inp_wantcnt != WNT_STOPUSING) {
7287 		/*
7288 		 * Some one has a wantcnt on this pcb. Since WNT_ACQUIRE
7289 		 * doesn't require a lock, it could have happened while
7290 		 * we are holding the lock. This pcb will have to
7291 		 * be garbage collected later.
7292 		 * Release the reference held for so_incomp queue
7293 		 */
7294 		VERIFY(so->so_usecount > 0);
7295 		so->so_usecount--;
7296 		socket_unlock(so, 1);
7297 	} else {
7298 		/*
7299 		 * Unlock this socket and leave the reference on.
7300 		 * We need to acquire the pcbinfo lock in order to
7301 		 * fully dispose it off
7302 		 */
7303 		socket_unlock(so, 0);
7304 
7305 		lck_rw_lock_exclusive(&tcbinfo.ipi_lock);
7306 
7307 		socket_lock(so, 0);
7308 		/* Release the reference held for so_incomp queue */
7309 		VERIFY(so->so_usecount > 0);
7310 		so->so_usecount--;
7311 
7312 		if (so->so_usecount != 1 ||
7313 		    (inp->inp_wantcnt > 0 &&
7314 		    inp->inp_wantcnt != WNT_STOPUSING)) {
7315 			/*
7316 			 * There is an extra wantcount or usecount
7317 			 * that must have been added when the socket
7318 			 * was unlocked. This socket will have to be
7319 			 * garbage collected later
7320 			 */
7321 			socket_unlock(so, 1);
7322 		} else {
7323 			/* Drop the reference held for this function */
7324 			VERIFY(so->so_usecount > 0);
7325 			so->so_usecount--;
7326 
7327 			in_pcbdispose(inp);
7328 		}
7329 		lck_rw_done(&tcbinfo.ipi_lock);
7330 	}
7331 	tcpstat.tcps_drops++;
7332 
7333 	socket_lock(head, 0);
7334 	return 1;
7335 }
7336 
7337 /* Set background congestion control on a socket */
7338 void
tcp_set_background_cc(struct socket * so)7339 tcp_set_background_cc(struct socket *so)
7340 {
7341 	tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
7342 }
7343 
7344 /* Set foreground congestion control on a socket */
7345 void
tcp_set_foreground_cc(struct socket * so)7346 tcp_set_foreground_cc(struct socket *so)
7347 {
7348 	if (tcp_use_newreno) {
7349 		tcp_set_new_cc(so, TCP_CC_ALGO_NEWRENO_INDEX);
7350 #if (DEVELOPMENT || DEBUG)
7351 	} else if (tcp_use_ledbat) {
7352 		/* Only used for testing */
7353 		tcp_set_new_cc(so, TCP_CC_ALGO_BACKGROUND_INDEX);
7354 #endif
7355 	} else {
7356 		struct inpcb *inp = sotoinpcb(so);
7357 		struct tcpcb *tp = intotcpcb(inp);
7358 		if (TCP_L4S_ENABLED(tp)) {
7359 			tcp_set_new_cc(so, TCP_CC_ALGO_PRAGUE_INDEX);
7360 		} else {
7361 			tcp_set_new_cc(so, TCP_CC_ALGO_CUBIC_INDEX);
7362 		}
7363 	}
7364 }
7365 
7366 static void
tcp_set_new_cc(struct socket * so,uint8_t cc_index)7367 tcp_set_new_cc(struct socket *so, uint8_t cc_index)
7368 {
7369 	struct inpcb *inp = sotoinpcb(so);
7370 	struct tcpcb *tp = intotcpcb(inp);
7371 
7372 	if (tp->tcp_cc_index != cc_index) {
7373 		if (CC_ALGO(tp)->cleanup != NULL) {
7374 			CC_ALGO(tp)->cleanup(tp);
7375 		}
7376 		tp->tcp_cc_index = cc_index;
7377 
7378 		tcp_cc_allocate_state(tp);
7379 
7380 		if (CC_ALGO(tp)->switch_to != NULL) {
7381 			CC_ALGO(tp)->switch_to(tp);
7382 		}
7383 
7384 		tcp_ccdbg_trace(tp, NULL, TCP_CC_CHANGE_ALGO);
7385 	}
7386 }
7387 
7388 void
tcp_set_recv_bg(struct socket * so)7389 tcp_set_recv_bg(struct socket *so)
7390 {
7391 	if (!IS_TCP_RECV_BG(so)) {
7392 		so->so_flags1 |= SOF1_TRAFFIC_MGT_TCP_RECVBG;
7393 
7394 		struct inpcb *inp = sotoinpcb(so);
7395 		struct tcpcb *tp = intotcpcb(inp);
7396 
7397 		if (TCP_RLEDBAT_ENABLED(tp) && tcp_cc_rledbat.switch_to != NULL) {
7398 			tcp_cc_rledbat.switch_to(tp);
7399 		}
7400 	}
7401 }
7402 
7403 void
tcp_clear_recv_bg(struct socket * so)7404 tcp_clear_recv_bg(struct socket *so)
7405 {
7406 	if (IS_TCP_RECV_BG(so)) {
7407 		so->so_flags1 &= ~(SOF1_TRAFFIC_MGT_TCP_RECVBG);
7408 	}
7409 }
7410 
7411 void
inp_fc_throttle_tcp(struct inpcb * inp)7412 inp_fc_throttle_tcp(struct inpcb *inp)
7413 {
7414 	struct tcpcb *tp = inp->inp_ppcb;
7415 
7416 	if (!tcp_flow_control_response) {
7417 		return;
7418 	}
7419 
7420 	/*
7421 	 * Back off the slow-start threshold and enter
7422 	 * congestion avoidance phase
7423 	 */
7424 	if (CC_ALGO(tp)->pre_fr != NULL) {
7425 		CC_ALGO(tp)->pre_fr(tp);
7426 	}
7427 }
7428 
7429 void
inp_fc_unthrottle_tcp(struct inpcb * inp)7430 inp_fc_unthrottle_tcp(struct inpcb *inp)
7431 {
7432 	struct tcpcb *tp = inp->inp_ppcb;
7433 	struct ifnet *outifp = inp->inp_last_outifp;
7434 
7435 	if (tcp_flow_control_response) {
7436 		if (CC_ALGO(tp)->post_fr != NULL) {
7437 			CC_ALGO(tp)->post_fr(tp, NULL);
7438 		}
7439 
7440 		tp->t_bytes_acked = 0;
7441 
7442 		/*
7443 		 * Reset retransmit shift as we know that the reason
7444 		 * for delay in sending a packet is due to flow
7445 		 * control on the outgoing interface. There is no need
7446 		 * to backoff retransmit timer except for cellular interface
7447 		 */
7448 		if (tp->t_rxtshift != 0 && outifp != NULL &&
7449 		    IFNET_IS_CELLULAR(outifp)) {
7450 			TCP_LOG(tp, "inp_fc_unthrottle_tcp keep rxmit state t_rxtshift %d", tp->t_rxtshift);
7451 		} else {
7452 			TCP_RESET_REXMT_STATE(tp);
7453 		}
7454 
7455 		tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
7456 
7457 		/*
7458 		 * Start the output stream again. Since we are
7459 		 * not retransmitting data, do not reset the
7460 		 * retransmit timer or rtt calculation.
7461 		 */
7462 		tcp_output(tp);
7463 		return;
7464 	}
7465 
7466 	/*
7467 	 * Back off the slow-start threshold and enter
7468 	 * congestion avoidance phase
7469 	 */
7470 	if (CC_ALGO(tp)->pre_fr != NULL) {
7471 		CC_ALGO(tp)->pre_fr(tp);
7472 	}
7473 
7474 	tp->snd_cwnd = tp->snd_ssthresh;
7475 	tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
7476 	/*
7477 	 * Restart counting for ABC as we changed the
7478 	 * congestion window just now.
7479 	 */
7480 	tp->t_bytes_acked = 0;
7481 
7482 	/* Reset retransmit shift as we know that the reason
7483 	 * for delay in sending a packet is due to flow
7484 	 * control on the outgoing interface. There is no need
7485 	 * to backoff retransmit timer.
7486 	 */
7487 	if (tp->t_rxtshift != 0 && outifp != NULL &&
7488 	    IFNET_IS_CELLULAR(outifp)) {
7489 		TCP_LOG(tp, "inp_fc_unthrottle_tcp keep rxmit state t_rxtshift %d", tp->t_rxtshift);
7490 	} else {
7491 		TCP_RESET_REXMT_STATE(tp);
7492 	}
7493 
7494 	/*
7495 	 * Start the output stream again. Since we are
7496 	 * not retransmitting data, do not reset the
7497 	 * retransmit timer or rtt calculation.
7498 	 */
7499 	tcp_output(tp);
7500 }
7501 
7502 static int
7503 tcp_getstat SYSCTL_HANDLER_ARGS
7504 {
7505 #pragma unused(oidp, arg1, arg2)
7506 
7507 	int error;
7508 	struct tcpstat *stat;
7509 	stat = &tcpstat;
7510 
7511 #if XNU_TARGET_OS_OSX
7512 	struct tcpstat zero_stat;
7513 
7514 	if (tcp_disable_access_to_stats &&
7515 	    !kauth_cred_issuser(kauth_cred_get())) {
7516 		bzero(&zero_stat, sizeof(zero_stat));
7517 		stat = &zero_stat;
7518 	}
7519 
7520 #endif /* XNU_TARGET_OS_OSX */
7521 
7522 	if (req->oldptr == 0) {
7523 		req->oldlen = (size_t)sizeof(struct tcpstat);
7524 	}
7525 
7526 	error = SYSCTL_OUT(req, stat, MIN(sizeof(tcpstat), req->oldlen));
7527 
7528 	return error;
7529 }
7530 
7531 /*
7532  * Checksum extended TCP header and data.
7533  */
7534 int
tcp_input_checksum(int af,struct mbuf * m,struct tcphdr * th,int off,int tlen)7535 tcp_input_checksum(int af, struct mbuf *m, struct tcphdr *th, int off, int tlen)
7536 {
7537 	struct ifnet *ifp = m->m_pkthdr.rcvif;
7538 
7539 	switch (af) {
7540 	case AF_INET: {
7541 		struct ip *ip = mtod(m, struct ip *);
7542 		struct ipovly *ipov = (struct ipovly *)ip;
7543 
7544 		/* ip_stripoptions() must have been called before we get here */
7545 		ASSERT((ip->ip_hl << 2) == sizeof(*ip));
7546 
7547 		if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
7548 		    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
7549 		    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
7550 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7551 				th->th_sum = m->m_pkthdr.csum_rx_val;
7552 			} else {
7553 				uint32_t sum = m->m_pkthdr.csum_rx_val;
7554 				uint32_t start = m->m_pkthdr.csum_rx_start;
7555 				int32_t trailer = (m_pktlen(m) - (off + tlen));
7556 
7557 				/*
7558 				 * Perform 1's complement adjustment of octets
7559 				 * that got included/excluded in the hardware-
7560 				 * calculated checksum value.  Ignore cases
7561 				 * where the value already includes the entire
7562 				 * IP header span, as the sum for those octets
7563 				 * would already be 0 by the time we get here;
7564 				 * IP has already performed its header checksum
7565 				 * checks.  If we do need to adjust, restore
7566 				 * the original fields in the IP header when
7567 				 * computing the adjustment value.  Also take
7568 				 * care of any trailing bytes and subtract out
7569 				 * their partial sum.
7570 				 */
7571 				ASSERT(trailer >= 0);
7572 				if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
7573 				    ((start != 0 && start != off) || trailer)) {
7574 					uint32_t swbytes = (uint32_t)trailer;
7575 
7576 					if (start < off) {
7577 						ip->ip_len += sizeof(*ip);
7578 #if BYTE_ORDER != BIG_ENDIAN
7579 						HTONS(ip->ip_len);
7580 						HTONS(ip->ip_off);
7581 #endif /* BYTE_ORDER != BIG_ENDIAN */
7582 					}
7583 					/* callee folds in sum */
7584 					sum = m_adj_sum16(m, start, off,
7585 					    tlen, sum);
7586 					if (off > start) {
7587 						swbytes += (off - start);
7588 					} else {
7589 						swbytes += (start - off);
7590 					}
7591 
7592 					if (start < off) {
7593 #if BYTE_ORDER != BIG_ENDIAN
7594 						NTOHS(ip->ip_off);
7595 						NTOHS(ip->ip_len);
7596 #endif /* BYTE_ORDER != BIG_ENDIAN */
7597 						ip->ip_len -= sizeof(*ip);
7598 					}
7599 
7600 					if (swbytes != 0) {
7601 						tcp_in_cksum_stats(swbytes);
7602 					}
7603 					if (trailer != 0) {
7604 						m_adj(m, -trailer);
7605 					}
7606 				}
7607 
7608 				/* callee folds in sum */
7609 				th->th_sum = in_pseudo(ip->ip_src.s_addr,
7610 				    ip->ip_dst.s_addr,
7611 				    sum + htonl(tlen + IPPROTO_TCP));
7612 			}
7613 			th->th_sum ^= 0xffff;
7614 		} else {
7615 			uint16_t ip_sum;
7616 			int len;
7617 			char b[9];
7618 
7619 			bcopy(ipov->ih_x1, b, sizeof(ipov->ih_x1));
7620 			bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
7621 			ip_sum = ipov->ih_len;
7622 			ipov->ih_len = (u_short)tlen;
7623 #if BYTE_ORDER != BIG_ENDIAN
7624 			HTONS(ipov->ih_len);
7625 #endif
7626 			len = sizeof(struct ip) + tlen;
7627 			th->th_sum = in_cksum(m, len);
7628 			bcopy(b, ipov->ih_x1, sizeof(ipov->ih_x1));
7629 			ipov->ih_len = ip_sum;
7630 
7631 			tcp_in_cksum_stats(len);
7632 		}
7633 		break;
7634 	}
7635 	case AF_INET6: {
7636 		struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
7637 
7638 		if ((hwcksum_rx || (ifp->if_flags & IFF_LOOPBACK) ||
7639 		    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) &&
7640 		    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)) {
7641 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR) {
7642 				th->th_sum = m->m_pkthdr.csum_rx_val;
7643 			} else {
7644 				uint32_t sum = m->m_pkthdr.csum_rx_val;
7645 				uint32_t start = m->m_pkthdr.csum_rx_start;
7646 				int32_t trailer = (m_pktlen(m) - (off + tlen));
7647 
7648 				/*
7649 				 * Perform 1's complement adjustment of octets
7650 				 * that got included/excluded in the hardware-
7651 				 * calculated checksum value.  Also take care
7652 				 * of any trailing bytes and subtract out their
7653 				 * partial sum.
7654 				 */
7655 				ASSERT(trailer >= 0);
7656 				if ((m->m_pkthdr.csum_flags & CSUM_PARTIAL) &&
7657 				    (start != off || trailer != 0)) {
7658 					uint16_t s = 0, d = 0;
7659 					uint32_t swbytes = (uint32_t)trailer;
7660 
7661 					if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
7662 						s = ip6->ip6_src.s6_addr16[1];
7663 						ip6->ip6_src.s6_addr16[1] = 0;
7664 					}
7665 					if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
7666 						d = ip6->ip6_dst.s6_addr16[1];
7667 						ip6->ip6_dst.s6_addr16[1] = 0;
7668 					}
7669 
7670 					/* callee folds in sum */
7671 					sum = m_adj_sum16(m, start, off,
7672 					    tlen, sum);
7673 					if (off > start) {
7674 						swbytes += (off - start);
7675 					} else {
7676 						swbytes += (start - off);
7677 					}
7678 
7679 					if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
7680 						ip6->ip6_src.s6_addr16[1] = s;
7681 					}
7682 					if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
7683 						ip6->ip6_dst.s6_addr16[1] = d;
7684 					}
7685 
7686 					if (swbytes != 0) {
7687 						tcp_in6_cksum_stats(swbytes);
7688 					}
7689 					if (trailer != 0) {
7690 						m_adj(m, -trailer);
7691 					}
7692 				}
7693 
7694 				th->th_sum = in6_pseudo(
7695 					&ip6->ip6_src, &ip6->ip6_dst,
7696 					sum + htonl(tlen + IPPROTO_TCP));
7697 			}
7698 			th->th_sum ^= 0xffff;
7699 		} else {
7700 			tcp_in6_cksum_stats(tlen);
7701 			th->th_sum = in6_cksum(m, IPPROTO_TCP, off, tlen);
7702 		}
7703 		break;
7704 	}
7705 	default:
7706 		VERIFY(0);
7707 		/* NOTREACHED */
7708 	}
7709 
7710 	if (th->th_sum != 0) {
7711 		tcpstat.tcps_rcvbadsum++;
7712 		IF_TCP_STATINC(ifp, badformat);
7713 		return -1;
7714 	}
7715 
7716 	return 0;
7717 }
7718 
7719 #define DUMP_BUF_CHK() {        \
7720 	clen -= k;              \
7721 	if (clen < 1)           \
7722 	        goto done;      \
7723 	c += k;                 \
7724 }
7725 
7726 int
dump_tcp_reass_qlen(char * str,int str_len)7727 dump_tcp_reass_qlen(char *str, int str_len)
7728 {
7729 	char *c = str;
7730 	int k, clen = str_len;
7731 
7732 	if (tcp_reass_total_qlen != 0) {
7733 		k = scnprintf(c, clen, "\ntcp reass qlen %d\n", tcp_reass_total_qlen);
7734 		DUMP_BUF_CHK();
7735 	}
7736 
7737 done:
7738 	return str_len - clen;
7739 }
7740 
7741 uint32_t
tcp_reass_qlen_space(struct socket * so)7742 tcp_reass_qlen_space(struct socket *so)
7743 {
7744 	uint32_t space = 0;
7745 	struct inpcb *inp = sotoinpcb(so);
7746 
7747 	if (inp != NULL) {
7748 		struct tcpcb *tp = intotcpcb(inp);
7749 
7750 		if (tp != NULL) {
7751 			space = tp->t_reassq_mbcnt;
7752 		}
7753 	}
7754 	return space;
7755 }
7756 
7757 
7758 SYSCTL_PROC(_net_inet_tcp, TCPCTL_STATS, stats,
7759     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0, tcp_getstat,
7760     "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
7761 
7762 static int
7763 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
7764 {
7765 #pragma unused(arg1, arg2)
7766 
7767 	int error, val = tcprexmtthresh;
7768 
7769 	error = sysctl_handle_int(oidp, &val, 0, req);
7770 	if (error || !req->newptr) {
7771 		return error;
7772 	}
7773 
7774 	/*
7775 	 * Constrain the number of duplicate ACKs
7776 	 * to consider for TCP fast retransmit
7777 	 * to either 2 or 3
7778 	 */
7779 
7780 	if (val < 2 || val > 3) {
7781 		return EINVAL;
7782 	}
7783 
7784 	tcprexmtthresh = (uint8_t)val;
7785 
7786 	return 0;
7787 }
7788 
7789 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, rexmt_thresh, CTLTYPE_INT | CTLFLAG_RW |
7790     CTLFLAG_LOCKED, &tcprexmtthresh, 0, &sysctl_rexmtthresh, "I",
7791     "Duplicate ACK Threshold for Fast Retransmit");
7792