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