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