xref: /xnu-8792.61.2/bsd/netinet/tcp_subr.c (revision 42e220869062b56f8d7d0726fd4c88954f87902c)
1 /*
2  * Copyright (c) 2000-2022 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 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_subr.c	8.2 (Berkeley) 5/24/95
61  */
62 /*
63  * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
64  * support for mandatory and extensible security protections.  This notice
65  * is included in support of clause 2.2 (b) of the Apple Public License,
66  * Version 2.0.
67  */
68 
69 #include "tcp_includes.h"
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/kernel.h>
74 #include <sys/sysctl.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/domain.h>
78 #include <sys/proc.h>
79 #include <sys/kauth.h>
80 #include <sys/socket.h>
81 #include <sys/socketvar.h>
82 #include <sys/protosw.h>
83 #include <sys/random.h>
84 #include <sys/syslog.h>
85 #include <sys/mcache.h>
86 #include <kern/locks.h>
87 #include <kern/zalloc.h>
88 
89 #include <dev/random/randomdev.h>
90 
91 #include <net/route.h>
92 #include <net/if.h>
93 #include <net/content_filter.h>
94 #include <net/ntstat.h>
95 #include <net/multi_layer_pkt_log.h>
96 
97 #define tcp_minmssoverload fring
98 #define _IP_VHL
99 #include <netinet/in.h>
100 #include <netinet/in_systm.h>
101 #include <netinet/ip.h>
102 #include <netinet/ip_icmp.h>
103 #include <netinet/ip6.h>
104 #include <netinet/icmp6.h>
105 #include <netinet/in_pcb.h>
106 #include <netinet6/in6_pcb.h>
107 #include <netinet/in_var.h>
108 #include <netinet/ip_var.h>
109 #include <netinet/icmp_var.h>
110 #include <netinet6/ip6_var.h>
111 #include <netinet/mptcp_var.h>
112 #include <netinet/tcp.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 <netinet/tcp_cache.h>
119 #include <kern/thread_call.h>
120 
121 #include <netinet6/tcp6_var.h>
122 #include <netinet/tcpip.h>
123 #if TCPDEBUG
124 #include <netinet/tcp_debug.h>
125 #endif
126 #include <netinet/tcp_log.h>
127 
128 #include <netinet6/ip6protosw.h>
129 
130 #if IPSEC
131 #include <netinet6/ipsec.h>
132 #include <netinet6/ipsec6.h>
133 #endif /* IPSEC */
134 
135 #if NECP
136 #include <net/necp.h>
137 #endif /* NECP */
138 
139 #undef tcp_minmssoverload
140 
141 #include <corecrypto/ccaes.h>
142 #include <libkern/crypto/aes.h>
143 #include <libkern/crypto/md5.h>
144 #include <sys/kdebug.h>
145 #include <mach/sdt.h>
146 #include <atm/atm_internal.h>
147 #include <pexpert/pexpert.h>
148 
149 #define DBG_FNC_TCP_CLOSE       NETDBG_CODE(DBG_NETTCP, ((5 << 8) | 2))
150 
151 static tcp_cc tcp_ccgen;
152 
153 extern struct tcptimerlist tcp_timer_list;
154 extern struct tcptailq tcp_tw_tailq;
155 
156 SYSCTL_SKMEM_TCP_INT(TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW | CTLFLAG_LOCKED,
157     int, tcp_mssdflt, TCP_MSS, "Default TCP Maximum Segment Size");
158 
159 SYSCTL_SKMEM_TCP_INT(TCPCTL_V6MSSDFLT, v6mssdflt,
160     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_v6mssdflt, TCP6_MSS,
161     "Default TCP Maximum Segment Size for IPv6");
162 
163 int tcp_sysctl_fastopenkey(struct sysctl_oid *, void *, int,
164     struct sysctl_req *);
165 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, fastopen_key, CTLTYPE_STRING | CTLFLAG_WR,
166     0, 0, tcp_sysctl_fastopenkey, "S", "TCP Fastopen key");
167 
168 /* Current count of half-open TFO connections */
169 int     tcp_tfo_halfcnt = 0;
170 
171 /* Maximum of half-open TFO connection backlog */
172 SYSCTL_SKMEM_TCP_INT(OID_AUTO, fastopen_backlog,
173     CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_tfo_backlog, 10,
174     "Backlog queue for half-open TFO connections");
175 
176 SYSCTL_SKMEM_TCP_INT(OID_AUTO, fastopen, CTLFLAG_RW | CTLFLAG_LOCKED,
177     int, tcp_fastopen, TCP_FASTOPEN_CLIENT | TCP_FASTOPEN_SERVER,
178     "Enable TCP Fastopen (RFC 7413)");
179 
180 SYSCTL_SKMEM_TCP_INT(OID_AUTO, now_init, CTLFLAG_RD | CTLFLAG_LOCKED,
181     uint32_t, tcp_now_init, 0, "Initial tcp now value");
182 
183 SYSCTL_SKMEM_TCP_INT(OID_AUTO, microuptime_init, CTLFLAG_RD | CTLFLAG_LOCKED,
184     uint32_t, tcp_microuptime_init, 0, "Initial tcp uptime value in micro seconds");
185 
186 /*
187  * Minimum MSS we accept and use. This prevents DoS attacks where
188  * we are forced to a ridiculous low MSS like 20 and send hundreds
189  * of packets instead of one. The effect scales with the available
190  * bandwidth and quickly saturates the CPU and network interface
191  * with packet generation and sending. Set to zero to disable MINMSS
192  * checking. This setting prevents us from sending too small packets.
193  */
194 SYSCTL_SKMEM_TCP_INT(OID_AUTO, minmss, CTLFLAG_RW | CTLFLAG_LOCKED,
195     int, tcp_minmss, TCP_MINMSS, "Minmum TCP Maximum Segment Size");
196 
197 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD | CTLFLAG_LOCKED,
198     &tcbinfo.ipi_count, 0, "Number of active PCBs");
199 
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tw_pcbcount, CTLFLAG_RD | CTLFLAG_LOCKED,
201     &tcbinfo.ipi_twcount, 0, "Number of pcbs in time-wait state");
202 
203 SYSCTL_SKMEM_TCP_INT(OID_AUTO, icmp_may_rst, CTLFLAG_RW | CTLFLAG_LOCKED,
204     static int, icmp_may_rst, 1,
205     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
206 
207 static int      tcp_strict_rfc1948 = 0;
208 static int      tcp_isn_reseed_interval = 0;
209 #if (DEVELOPMENT || DEBUG)
210 SYSCTL_INT(_net_inet_tcp, OID_AUTO, strict_rfc1948, CTLFLAG_RW | CTLFLAG_LOCKED,
211     &tcp_strict_rfc1948, 0, "Determines if RFC1948 is followed exactly");
212 
213 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval,
214     CTLFLAG_RW | CTLFLAG_LOCKED,
215     &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret");
216 #endif /* (DEVELOPMENT || DEBUG) */
217 
218 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rtt_min, CTLFLAG_RW | CTLFLAG_LOCKED,
219     int, tcp_TCPTV_MIN, 100, "min rtt value allowed");
220 
221 SYSCTL_SKMEM_TCP_INT(OID_AUTO, rexmt_slop, CTLFLAG_RW,
222     int, tcp_rexmt_slop, TCPTV_REXMTSLOP, "Slop added to retransmit timeout");
223 
224 SYSCTL_SKMEM_TCP_INT(OID_AUTO, randomize_ports, CTLFLAG_RW | CTLFLAG_LOCKED,
225     __private_extern__ int, tcp_use_randomport, 0,
226     "Randomize TCP port numbers");
227 
228 SYSCTL_SKMEM_TCP_INT(OID_AUTO, win_scale_factor, CTLFLAG_RW | CTLFLAG_LOCKED,
229     __private_extern__ int, tcp_win_scale, 3, "Window scaling factor");
230 
231 #if (DEVELOPMENT || DEBUG)
232 SYSCTL_SKMEM_TCP_INT(OID_AUTO, init_rtt_from_cache,
233     CTLFLAG_RW | CTLFLAG_LOCKED, static int, tcp_init_rtt_from_cache, 1,
234     "Initalize RTT from route cache");
235 #else
236 SYSCTL_SKMEM_TCP_INT(OID_AUTO, init_rtt_from_cache,
237     CTLFLAG_RD | CTLFLAG_LOCKED, static int, tcp_init_rtt_from_cache, 1,
238     "Initalize RTT from route cache");
239 #endif /* (DEVELOPMENT || DEBUG) */
240 
241 static int tso_debug = 0;
242 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tso_debug, CTLFLAG_RW | CTLFLAG_LOCKED,
243     &tso_debug, 0, "TSO verbosity");
244 
245 static int tcp_rxt_seg_max = 1024;
246 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rxt_seg_max, CTLFLAG_RW | CTLFLAG_LOCKED,
247     &tcp_rxt_seg_max, 0, "");
248 
249 static unsigned long tcp_rxt_seg_drop = 0;
250 SYSCTL_ULONG(_net_inet_tcp, OID_AUTO, rxt_seg_drop, CTLFLAG_RD | CTLFLAG_LOCKED,
251     &tcp_rxt_seg_drop, "");
252 
253 static void     tcp_notify(struct inpcb *, int);
254 
255 struct zone     *sack_hole_zone;
256 struct zone     *tcp_reass_zone;
257 struct zone     *tcp_bwmeas_zone;
258 struct zone     *tcp_rxt_seg_zone;
259 
260 extern int slowlink_wsize;      /* window correction for slow links */
261 extern int path_mtu_discovery;
262 
263 uint32_t tcp_now_remainder_us = 0;  /* remaining micro seconds for tcp_now */
264 
265 static void tcp_sbrcv_grow_rwin(struct tcpcb *tp, struct sockbuf *sb);
266 
267 #define TCP_BWMEAS_BURST_MINSIZE 6
268 #define TCP_BWMEAS_BURST_MAXSIZE 25
269 
270 /*
271  * Target size of TCP PCB hash tables. Must be a power of two.
272  *
273  * Note that this can be overridden by the kernel environment
274  * variable net.inet.tcp.tcbhashsize
275  */
276 #ifndef TCBHASHSIZE
277 #define TCBHASHSIZE     CONFIG_TCBHASHSIZE
278 #endif
279 
280 __private_extern__ int  tcp_tcbhashsize = TCBHASHSIZE;
281 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RD | CTLFLAG_LOCKED,
282     &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
283 
284 /*
285  * This is the actual shape of what we allocate using the zone
286  * allocator.  Doing it this way allows us to protect both structures
287  * using the same generation count, and also eliminates the overhead
288  * of allocating tcpcbs separately.  By hiding the structure here,
289  * we avoid changing most of the rest of the code (although it needs
290  * to be changed, eventually, for greater efficiency).
291  */
292 #define ALIGNMENT       32
293 struct  inp_tp {
294 	struct  inpcb   inp;
295 	struct  tcpcb   tcb __attribute__((aligned(ALIGNMENT)));
296 };
297 #undef ALIGNMENT
298 
299 int  get_inpcb_str_size(void);
300 int  get_tcp_str_size(void);
301 
302 os_log_t tcp_mpkl_log_object = NULL;
303 
304 static void tcpcb_to_otcpcb(struct tcpcb *, struct otcpcb *);
305 
306 int tcp_notsent_lowat_check(struct socket *so);
307 static void tcp_flow_lim_stats(struct ifnet_stats_per_flow *ifs,
308     struct if_lim_perf_stat *stat);
309 static void tcp_flow_ecn_perf_stats(struct ifnet_stats_per_flow *ifs,
310     struct if_tcp_ecn_perf_stat *stat);
311 
312 static aes_encrypt_ctx tfo_ctx; /* Crypto-context for TFO */
313 
314 void
tcp_tfo_gen_cookie(struct inpcb * inp,u_char * out,size_t blk_size)315 tcp_tfo_gen_cookie(struct inpcb *inp, u_char *out, size_t blk_size)
316 {
317 	u_char in[CCAES_BLOCK_SIZE];
318 	int isipv6 = inp->inp_vflag & INP_IPV6;
319 
320 	VERIFY(blk_size == CCAES_BLOCK_SIZE);
321 
322 	bzero(&in[0], CCAES_BLOCK_SIZE);
323 	bzero(&out[0], CCAES_BLOCK_SIZE);
324 
325 	if (isipv6) {
326 		memcpy(in, &inp->in6p_faddr, sizeof(struct in6_addr));
327 	} else {
328 		memcpy(in, &inp->inp_faddr, sizeof(struct in_addr));
329 	}
330 
331 	aes_encrypt_cbc(in, NULL, 1, out, &tfo_ctx);
332 }
333 
334 __private_extern__ int
tcp_sysctl_fastopenkey(__unused struct sysctl_oid * oidp,__unused void * arg1,__unused int arg2,struct sysctl_req * req)335 tcp_sysctl_fastopenkey(__unused struct sysctl_oid *oidp, __unused void *arg1,
336     __unused int arg2, struct sysctl_req *req)
337 {
338 	int error = 0;
339 	/*
340 	 * TFO-key is expressed as a string in hex format
341 	 *  +1 to account for the \0 char
342 	 *  +1 because sysctl_io_string() expects a string length but the sysctl command
343 	 *     now includes the terminating \0 in newlen -- see rdar://77205344
344 	 */
345 	char keystring[TCP_FASTOPEN_KEYLEN * 2 + 2];
346 	u_int32_t key[TCP_FASTOPEN_KEYLEN / sizeof(u_int32_t)];
347 	int i;
348 
349 	/*
350 	 * sysctl_io_string copies keystring into the oldptr of the sysctl_req.
351 	 * Make sure everything is zero, to avoid putting garbage in there or
352 	 * leaking the stack.
353 	 */
354 	bzero(keystring, sizeof(keystring));
355 
356 	error = sysctl_io_string(req, keystring, sizeof(keystring), 0, NULL);
357 	if (error) {
358 		os_log(OS_LOG_DEFAULT,
359 		    "%s: sysctl_io_string() error %d, req->newlen %lu, sizeof(keystring) %lu",
360 		    __func__, error, req->newlen, sizeof(keystring));
361 		goto exit;
362 	}
363 	if (req->newptr == USER_ADDR_NULL) {
364 		goto exit;
365 	}
366 
367 	if (strlen(keystring) != TCP_FASTOPEN_KEYLEN * 2) {
368 		os_log(OS_LOG_DEFAULT,
369 		    "%s: strlen(keystring) %lu != TCP_FASTOPEN_KEYLEN * 2 %u, newlen %lu",
370 		    __func__, strlen(keystring), TCP_FASTOPEN_KEYLEN * 2, req->newlen);
371 		error = EINVAL;
372 		goto exit;
373 	}
374 
375 	for (i = 0; i < (TCP_FASTOPEN_KEYLEN / sizeof(u_int32_t)); i++) {
376 		/*
377 		 * We jump over the keystring in 8-character (4 byte in hex)
378 		 * steps
379 		 */
380 		if (sscanf(&keystring[i * 8], "%8x", &key[i]) != 1) {
381 			error = EINVAL;
382 			os_log(OS_LOG_DEFAULT,
383 			    "%s: sscanf() != 1, error EINVAL", __func__);
384 			goto exit;
385 		}
386 	}
387 
388 	aes_encrypt_key128((u_char *)key, &tfo_ctx);
389 
390 exit:
391 	return error;
392 }
393 
394 int
get_inpcb_str_size(void)395 get_inpcb_str_size(void)
396 {
397 	return sizeof(struct inpcb);
398 }
399 
400 int
get_tcp_str_size(void)401 get_tcp_str_size(void)
402 {
403 	return sizeof(struct tcpcb);
404 }
405 
406 static int scale_to_powerof2(int size);
407 
408 /*
409  * This helper routine returns one of the following scaled value of size:
410  * 1. Rounded down power of two value of size if the size value passed as
411  *    argument is not a power of two and the rounded up value overflows.
412  * OR
413  * 2. Rounded up power of two value of size if the size value passed as
414  *    argument is not a power of two and the rounded up value does not overflow
415  * OR
416  * 3. Same value as argument size if it is already a power of two.
417  */
418 static int
scale_to_powerof2(int size)419 scale_to_powerof2(int size)
420 {
421 	/* Handle special case of size = 0 */
422 	int ret = size ? size : 1;
423 
424 	if (!powerof2(ret)) {
425 		while (!powerof2(size)) {
426 			/*
427 			 * Clear out least significant
428 			 * set bit till size is left with
429 			 * its highest set bit at which point
430 			 * it is rounded down power of two.
431 			 */
432 			size = size & (size - 1);
433 		}
434 
435 		/* Check for overflow when rounding up */
436 		if (0 == (size << 1)) {
437 			ret = size;
438 		} else {
439 			ret = size << 1;
440 		}
441 	}
442 
443 	return ret;
444 }
445 
446 /*
447  * Round the floating point to the next integer
448  * Eg. 1.3 will round up to 2.
449  */
450 uint32_t
tcp_ceil(double a)451 tcp_ceil(double a)
452 {
453 	double res = (uint32_t) a;
454 	return (uint32_t)(res + (res < a));
455 }
456 
457 uint32_t
tcp_round_to(uint32_t val,uint32_t round)458 tcp_round_to(uint32_t val, uint32_t round)
459 {
460 	/*
461 	 * Round up or down based on the middle. Meaning, if we round upon a
462 	 * multiple of 10, 16 will round to 20 and 14 will round to 10.
463 	 */
464 	return ((val + (round / 2)) / round) * round;
465 }
466 
467 /*
468  * Round up to the next multiple of base.
469  * Eg. for a base of 64, 65 will become 128,
470  * 2896 will become 2944.
471  */
472 uint32_t
tcp_round_up(uint32_t val,uint32_t base)473 tcp_round_up(uint32_t val, uint32_t base)
474 {
475 	if (base == 1 || val % base == 0) {
476 		return val;
477 	}
478 
479 	return ((val + base) / base) * base;
480 }
481 
482 static void
tcp_tfo_init(void)483 tcp_tfo_init(void)
484 {
485 	u_char key[TCP_FASTOPEN_KEYLEN];
486 
487 	read_frandom(key, sizeof(key));
488 	aes_encrypt_key128(key, &tfo_ctx);
489 }
490 
491 /*
492  * Tcp initialization
493  */
494 void
tcp_init(struct protosw * pp,struct domain * dp)495 tcp_init(struct protosw *pp, struct domain *dp)
496 {
497 #pragma unused(dp)
498 	static int tcp_initialized = 0;
499 	vm_size_t str_size;
500 	struct inpcbinfo *pcbinfo;
501 	uint32_t logging_config;
502 
503 	VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
504 
505 	if (tcp_initialized) {
506 		return;
507 	}
508 	tcp_initialized = 1;
509 
510 #if DEBUG || DEVELOPMENT
511 	(void) PE_parse_boot_argn("tcp_rxt_seg_max", &tcp_rxt_seg_max,
512 	    sizeof(tcp_rxt_seg_max));
513 #endif /* DEBUG || DEVELOPMENT */
514 
515 	tcp_ccgen = 1;
516 	tcp_keepinit = TCPTV_KEEP_INIT;
517 	tcp_keepidle = TCPTV_KEEP_IDLE;
518 	tcp_keepintvl = TCPTV_KEEPINTVL;
519 	tcp_keepcnt = TCPTV_KEEPCNT;
520 	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
521 	tcp_msl = TCPTV_MSL;
522 
523 	microuptime(&tcp_uptime);
524 	read_frandom(&tcp_now, sizeof(tcp_now));
525 
526 	/* Starts tcp internal clock at a random value */
527 	tcp_now = tcp_now & 0x3fffffff;
528 
529 	/* expose initial uptime/now via systcl for utcp to keep time sync */
530 	tcp_now_init = tcp_now;
531 	tcp_microuptime_init =
532 	    (uint32_t)(tcp_uptime.tv_usec + (tcp_uptime.tv_sec * USEC_PER_SEC));
533 	SYSCTL_SKMEM_UPDATE_FIELD(tcp.microuptime_init, tcp_microuptime_init);
534 	SYSCTL_SKMEM_UPDATE_FIELD(tcp.now_init, tcp_now_init);
535 
536 	tcp_tfo_init();
537 
538 	LIST_INIT(&tcb);
539 	tcbinfo.ipi_listhead = &tcb;
540 
541 	pcbinfo = &tcbinfo;
542 
543 	/*
544 	 * allocate group, lock attributes and lock for tcp pcb mutexes
545 	 */
546 	pcbinfo->ipi_lock_grp = lck_grp_alloc_init("tcppcb",
547 	    LCK_GRP_ATTR_NULL);
548 	lck_attr_setdefault(&pcbinfo->ipi_lock_attr);
549 	lck_rw_init(&pcbinfo->ipi_lock, pcbinfo->ipi_lock_grp,
550 	    &pcbinfo->ipi_lock_attr);
551 
552 	if (tcp_tcbhashsize == 0) {
553 		/* Set to default */
554 		tcp_tcbhashsize = 512;
555 	}
556 
557 	if (!powerof2(tcp_tcbhashsize)) {
558 		int old_hash_size = tcp_tcbhashsize;
559 		tcp_tcbhashsize = scale_to_powerof2(tcp_tcbhashsize);
560 		/* Lower limit of 16  */
561 		if (tcp_tcbhashsize < 16) {
562 			tcp_tcbhashsize = 16;
563 		}
564 		printf("WARNING: TCB hash size not a power of 2, "
565 		    "scaled from %d to %d.\n",
566 		    old_hash_size,
567 		    tcp_tcbhashsize);
568 	}
569 
570 	tcbinfo.ipi_hashbase = hashinit(tcp_tcbhashsize, M_PCB,
571 	    &tcbinfo.ipi_hashmask);
572 	tcbinfo.ipi_porthashbase = hashinit(tcp_tcbhashsize, M_PCB,
573 	    &tcbinfo.ipi_porthashmask);
574 	str_size = (vm_size_t)P2ROUNDUP(sizeof(struct inp_tp), sizeof(u_int64_t));
575 	tcbinfo.ipi_zone = zone_create("tcpcb", str_size, ZC_NONE);
576 
577 	tcbinfo.ipi_gc = tcp_gc;
578 	tcbinfo.ipi_timer = tcp_itimer;
579 	in_pcbinfo_attach(&tcbinfo);
580 
581 	str_size = (vm_size_t)P2ROUNDUP(sizeof(struct sackhole), sizeof(u_int64_t));
582 	sack_hole_zone = zone_create("sack_hole zone", str_size, ZC_NONE);
583 
584 	str_size = (vm_size_t)P2ROUNDUP(sizeof(struct tseg_qent), sizeof(u_int64_t));
585 	tcp_reass_zone = zone_create("tcp_reass_zone", str_size, ZC_NONE);
586 
587 	str_size = (vm_size_t)P2ROUNDUP(sizeof(struct bwmeas), sizeof(u_int64_t));
588 	tcp_bwmeas_zone = zone_create("tcp_bwmeas_zone", str_size, ZC_ZFREE_CLEARMEM);
589 
590 	str_size = (vm_size_t)P2ROUNDUP(sizeof(struct tcp_rxt_seg), sizeof(u_int64_t));
591 	tcp_rxt_seg_zone = zone_create("tcp_rxt_seg_zone", str_size, ZC_NONE);
592 
593 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
594 	if (max_protohdr < TCP_MINPROTOHDR) {
595 		max_protohdr = (int)P2ROUNDUP(TCP_MINPROTOHDR, sizeof(uint32_t));
596 	}
597 	if (max_linkhdr + max_protohdr > MCLBYTES) {
598 		panic("tcp_init");
599 	}
600 #undef TCP_MINPROTOHDR
601 
602 	/* Initialize time wait and timer lists */
603 	TAILQ_INIT(&tcp_tw_tailq);
604 
605 	bzero(&tcp_timer_list, sizeof(tcp_timer_list));
606 	LIST_INIT(&tcp_timer_list.lhead);
607 	/*
608 	 * allocate group and attribute for the tcp timer list
609 	 */
610 	tcp_timer_list.mtx_grp = lck_grp_alloc_init("tcptimerlist",
611 	    LCK_GRP_ATTR_NULL);
612 	lck_mtx_init(&tcp_timer_list.mtx, tcp_timer_list.mtx_grp,
613 	    LCK_ATTR_NULL);
614 
615 	tcp_timer_list.call = thread_call_allocate(tcp_run_timerlist, NULL);
616 	if (tcp_timer_list.call == NULL) {
617 		panic("failed to allocate call entry 1 in tcp_init");
618 	}
619 
620 	/* Initialize TCP Cache */
621 	tcp_cache_init();
622 
623 	tcp_mpkl_log_object = MPKL_CREATE_LOGOBJECT("com.apple.xnu.tcp");
624 	if (tcp_mpkl_log_object == NULL) {
625 		panic("MPKL_CREATE_LOGOBJECT failed");
626 	}
627 
628 	logging_config = atm_get_diagnostic_config();
629 	if (logging_config & 0x80000000) {
630 		tcp_log_privacy = 1;
631 	}
632 
633 	if (PE_parse_boot_argn("tcp_log", &tcp_log_enable_flags, sizeof(tcp_log_enable_flags))) {
634 		os_log(OS_LOG_DEFAULT, "tcp_init: set tcp_log_enable_flags to 0x%x", tcp_log_enable_flags);
635 	}
636 
637 	/*
638 	 * If more than 4GB of actual memory is available, increase the
639 	 * maximum allowed receive and send socket buffer size.
640 	 */
641 	if (mem_actual >= (1ULL << (GBSHIFT + 2))) {
642 		tcp_autorcvbuf_max = 4 * 1024 * 1024;
643 		tcp_autosndbuf_max = 4 * 1024 * 1024;
644 
645 		SYSCTL_SKMEM_UPDATE_FIELD(tcp.autorcvbufmax, tcp_autorcvbuf_max);
646 		SYSCTL_SKMEM_UPDATE_FIELD(tcp.autosndbufmax, tcp_autosndbuf_max);
647 	}
648 }
649 
650 /*
651  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
652  * tcp_template used to store this data in mbufs, but we now recopy it out
653  * of the tcpcb each time to conserve mbufs.
654  */
655 void
tcp_fillheaders(struct mbuf * m,struct tcpcb * tp,void * ip_ptr,void * tcp_ptr)656 tcp_fillheaders(struct mbuf *m, struct tcpcb *tp, void *ip_ptr, void *tcp_ptr)
657 {
658 	struct inpcb *inp = tp->t_inpcb;
659 	struct tcphdr *tcp_hdr = (struct tcphdr *)tcp_ptr;
660 
661 	if ((inp->inp_vflag & INP_IPV6) != 0) {
662 		struct ip6_hdr *ip6;
663 
664 		ip6 = (struct ip6_hdr *)ip_ptr;
665 		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
666 		    (inp->inp_flow & IPV6_FLOWINFO_MASK);
667 		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
668 		    (IPV6_VERSION & IPV6_VERSION_MASK);
669 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
670 		ip6->ip6_nxt = IPPROTO_TCP;
671 		ip6->ip6_hlim = 0;
672 		ip6->ip6_src = inp->in6p_laddr;
673 		ip6->ip6_dst = inp->in6p_faddr;
674 		if (m->m_flags & M_PKTHDR) {
675 			uint32_t lifscope = inp->inp_lifscope != 0 ? inp->inp_lifscope : inp->inp_fifscope;
676 			uint32_t fifscope = inp->inp_fifscope != 0 ? inp->inp_fifscope : inp->inp_lifscope;
677 			ip6_output_setsrcifscope(m, lifscope, NULL);
678 			ip6_output_setdstifscope(m, fifscope, NULL);
679 		}
680 		tcp_hdr->th_sum = in6_pseudo(&inp->in6p_laddr, &inp->in6p_faddr,
681 		    htonl(sizeof(struct tcphdr) + IPPROTO_TCP));
682 	} else {
683 		struct ip *ip = (struct ip *) ip_ptr;
684 
685 		ip->ip_vhl = IP_VHL_BORING;
686 		ip->ip_tos = 0;
687 		ip->ip_len = 0;
688 		ip->ip_id = 0;
689 		ip->ip_off = 0;
690 		ip->ip_ttl = 0;
691 		ip->ip_sum = 0;
692 		ip->ip_p = IPPROTO_TCP;
693 		ip->ip_src = inp->inp_laddr;
694 		ip->ip_dst = inp->inp_faddr;
695 		tcp_hdr->th_sum =
696 		    in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
697 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
698 	}
699 
700 	tcp_hdr->th_sport = inp->inp_lport;
701 	tcp_hdr->th_dport = inp->inp_fport;
702 	tcp_hdr->th_seq = 0;
703 	tcp_hdr->th_ack = 0;
704 	tcp_hdr->th_x2 = 0;
705 	tcp_hdr->th_off = 5;
706 	tcp_hdr->th_flags = 0;
707 	tcp_hdr->th_win = 0;
708 	tcp_hdr->th_urp = 0;
709 }
710 
711 /*
712  * Create template to be used to send tcp packets on a connection.
713  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
714  * use for this function is in keepalives, which use tcp_respond.
715  */
716 struct tcptemp *
tcp_maketemplate(struct tcpcb * tp)717 tcp_maketemplate(struct tcpcb *tp)
718 {
719 	struct mbuf *m;
720 	struct tcptemp *n;
721 
722 	m = m_get(M_DONTWAIT, MT_HEADER);
723 	if (m == NULL) {
724 		return NULL;
725 	}
726 	m->m_len = sizeof(struct tcptemp);
727 	n = mtod(m, struct tcptemp *);
728 
729 	tcp_fillheaders(m, tp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
730 	return n;
731 }
732 
733 /*
734  * Send a single message to the TCP at address specified by
735  * the given TCP/IP header.  If m == 0, then we make a copy
736  * of the tcpiphdr at ti and send directly to the addressed host.
737  * This is used to force keep alive messages out using the TCP
738  * template for a connection.  If flags are given then we send
739  * a message back to the TCP which originated the * segment ti,
740  * and discard the mbuf containing it and any other attached mbufs.
741  *
742  * In any case the ack and sequence number of the transmitted
743  * segment are as specified by the parameters.
744  *
745  * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
746  */
747 void
tcp_respond(struct tcpcb * tp,void * ipgen,struct tcphdr * th,struct mbuf * m,tcp_seq ack,tcp_seq seq,uint8_t flags,struct tcp_respond_args * tra)748 tcp_respond(struct tcpcb *tp, void *ipgen, struct tcphdr *th, struct mbuf *m,
749     tcp_seq ack, tcp_seq seq, uint8_t flags, struct tcp_respond_args *tra)
750 {
751 	uint16_t tlen;
752 	int win = 0;
753 	struct route *ro = 0;
754 	struct route sro;
755 	struct ip *ip;
756 	struct tcphdr *nth;
757 	struct route_in6 *ro6 = 0;
758 	struct route_in6 sro6;
759 	struct ip6_hdr *ip6;
760 	int isipv6;
761 	struct ifnet *outif;
762 	int sotc = SO_TC_UNSPEC;
763 	bool check_qos_marking_again = FALSE;
764 	uint32_t sifscope = IFSCOPE_NONE, fifscope = IFSCOPE_NONE;
765 
766 	isipv6 = IP_VHL_V(((struct ip *)ipgen)->ip_vhl) == 6;
767 	ip6 = ipgen;
768 	ip = ipgen;
769 
770 	if (tp) {
771 		check_qos_marking_again = tp->t_inpcb->inp_socket->so_flags1 & SOF1_QOSMARKING_POLICY_OVERRIDE ? FALSE : TRUE;
772 		sifscope = tp->t_inpcb->inp_lifscope;
773 		fifscope = tp->t_inpcb->inp_fifscope;
774 		if (!(flags & TH_RST)) {
775 			win = tcp_sbspace(tp);
776 			if (win > (int32_t)TCP_MAXWIN << tp->rcv_scale) {
777 				win = (int32_t)TCP_MAXWIN << tp->rcv_scale;
778 			}
779 		}
780 		if (isipv6) {
781 			ro6 = &tp->t_inpcb->in6p_route;
782 		} else {
783 			ro = &tp->t_inpcb->inp_route;
784 		}
785 	} else {
786 		if (isipv6) {
787 			ro6 = &sro6;
788 			bzero(ro6, sizeof(*ro6));
789 		} else {
790 			ro = &sro;
791 			bzero(ro, sizeof(*ro));
792 		}
793 	}
794 	if (m == 0) {
795 		m = m_gethdr(M_DONTWAIT, MT_HEADER);    /* MAC-OK */
796 		if (m == NULL) {
797 			return;
798 		}
799 		tlen = 0;
800 		m->m_data += max_linkhdr;
801 		if (isipv6) {
802 			VERIFY((MHLEN - max_linkhdr) >=
803 			    (sizeof(*ip6) + sizeof(*nth)));
804 			bcopy((caddr_t)ip6, mtod(m, caddr_t),
805 			    sizeof(struct ip6_hdr));
806 			ip6 = mtod(m, struct ip6_hdr *);
807 			nth = (struct tcphdr *)(void *)(ip6 + 1);
808 		} else {
809 			VERIFY((MHLEN - max_linkhdr) >=
810 			    (sizeof(*ip) + sizeof(*nth)));
811 			bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
812 			ip = mtod(m, struct ip *);
813 			nth = (struct tcphdr *)(void *)(ip + 1);
814 		}
815 		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
816 #if MPTCP
817 		if ((tp) && (tp->t_mpflags & TMPF_RESET)) {
818 			flags = (TH_RST | TH_ACK);
819 		} else
820 #endif
821 		flags = TH_ACK;
822 	} else {
823 		m_freem(m->m_next);
824 		m->m_next = 0;
825 		m->m_data = (caddr_t)ipgen;
826 		/* m_len is set later */
827 		tlen = 0;
828 #define xchg(a, b, type) { type t; t = a; a = b; b = t; }
829 		if (isipv6) {
830 			ip6_getsrcifaddr_info(m, &sifscope, NULL);
831 			ip6_getdstifaddr_info(m, &fifscope, NULL);
832 			if (!in6_embedded_scope) {
833 				m->m_pkthdr.pkt_flags &= ~PKTF_IFAINFO;
834 			}
835 			/* Expect 32-bit aligned IP on strict-align platforms */
836 			IP6_HDR_STRICT_ALIGNMENT_CHECK(ip6);
837 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
838 			nth = (struct tcphdr *)(void *)(ip6 + 1);
839 		} else {
840 			/* Expect 32-bit aligned IP on strict-align platforms */
841 			IP_HDR_STRICT_ALIGNMENT_CHECK(ip);
842 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
843 			nth = (struct tcphdr *)(void *)(ip + 1);
844 		}
845 		if (th != nth) {
846 			/*
847 			 * this is usually a case when an extension header
848 			 * exists between the IPv6 header and the
849 			 * TCP header.
850 			 */
851 			nth->th_sport = th->th_sport;
852 			nth->th_dport = th->th_dport;
853 		}
854 		xchg(nth->th_dport, nth->th_sport, n_short);
855 #undef xchg
856 	}
857 	if (isipv6) {
858 		ip6->ip6_plen = htons((u_short)(sizeof(struct tcphdr) +
859 		    tlen));
860 		tlen += sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
861 		ip6_output_setsrcifscope(m, sifscope, NULL);
862 		ip6_output_setdstifscope(m, fifscope, NULL);
863 	} else {
864 		tlen += sizeof(struct tcpiphdr);
865 		ip->ip_len = tlen;
866 		ip->ip_ttl = (uint8_t)ip_defttl;
867 	}
868 	m->m_len = tlen;
869 	m->m_pkthdr.len = tlen;
870 	m->m_pkthdr.rcvif = 0;
871 	if (tra->keep_alive) {
872 		m->m_pkthdr.pkt_flags |= PKTF_KEEPALIVE;
873 	}
874 
875 	nth->th_seq = htonl(seq);
876 	nth->th_ack = htonl(ack);
877 	nth->th_x2 = 0;
878 	nth->th_off = sizeof(struct tcphdr) >> 2;
879 	nth->th_flags = flags;
880 	if (tp) {
881 		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
882 	} else {
883 		nth->th_win = htons((u_short)win);
884 	}
885 	nth->th_urp = 0;
886 	if (isipv6) {
887 		nth->th_sum = 0;
888 		nth->th_sum = in6_pseudo(&ip6->ip6_src, &ip6->ip6_dst,
889 		    htonl((tlen - sizeof(struct ip6_hdr)) + IPPROTO_TCP));
890 		m->m_pkthdr.csum_flags = CSUM_TCPIPV6;
891 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
892 		ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL,
893 		    ro6 && ro6->ro_rt ? ro6->ro_rt->rt_ifp : NULL);
894 	} else {
895 		nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
896 		    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
897 		m->m_pkthdr.csum_flags = CSUM_TCP;
898 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
899 	}
900 #if TCPDEBUG
901 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
902 		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
903 	}
904 #endif
905 
906 #if NECP
907 	necp_mark_packet_from_socket(m, tp ? tp->t_inpcb : NULL, 0, 0, 0, 0);
908 #endif /* NECP */
909 
910 #if IPSEC
911 	if (tp != NULL && tp->t_inpcb->inp_sp != NULL &&
912 	    ipsec_setsocket(m, tp ? tp->t_inpcb->inp_socket : NULL) != 0) {
913 		m_freem(m);
914 		return;
915 	}
916 #endif
917 
918 	if (tp != NULL) {
919 		u_int32_t svc_flags = 0;
920 		if (isipv6) {
921 			svc_flags |= PKT_SCF_IPV6;
922 		}
923 		sotc = tp->t_inpcb->inp_socket->so_traffic_class;
924 		if ((flags & TH_RST) == 0) {
925 			set_packet_service_class(m, tp->t_inpcb->inp_socket,
926 			    sotc, svc_flags);
927 		} else {
928 			m_set_service_class(m, MBUF_SC_BK_SYS);
929 		}
930 
931 		/* Embed flowhash and flow control flags */
932 		m->m_pkthdr.pkt_flowsrc = FLOWSRC_INPCB;
933 		m->m_pkthdr.pkt_flowid = tp->t_inpcb->inp_flowhash;
934 		m->m_pkthdr.pkt_flags |= (PKTF_FLOW_ID | PKTF_FLOW_LOCALSRC | PKTF_FLOW_ADV);
935 		m->m_pkthdr.pkt_proto = IPPROTO_TCP;
936 		m->m_pkthdr.tx_tcp_pid = tp->t_inpcb->inp_socket->last_pid;
937 		m->m_pkthdr.tx_tcp_e_pid = tp->t_inpcb->inp_socket->e_pid;
938 
939 		if (flags & TH_RST) {
940 			m->m_pkthdr.comp_gencnt = tp->t_comp_gencnt;
941 		}
942 	} else {
943 		if (flags & TH_RST) {
944 			m->m_pkthdr.comp_gencnt = TCP_ACK_COMPRESSION_DUMMY;
945 			m_set_service_class(m, MBUF_SC_BK_SYS);
946 		}
947 	}
948 
949 	if (isipv6) {
950 		struct ip6_out_args ip6oa;
951 		bzero(&ip6oa, sizeof(ip6oa));
952 		ip6oa.ip6oa_boundif = tra->ifscope;
953 		ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR;
954 		ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
955 		ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
956 
957 		if (tra->ifscope != IFSCOPE_NONE) {
958 			ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
959 		}
960 		if (tra->nocell) {
961 			ip6oa.ip6oa_flags |= IP6OAF_NO_CELLULAR;
962 		}
963 		if (tra->noexpensive) {
964 			ip6oa.ip6oa_flags |= IP6OAF_NO_EXPENSIVE;
965 		}
966 		if (tra->noconstrained) {
967 			ip6oa.ip6oa_flags |= IP6OAF_NO_CONSTRAINED;
968 		}
969 		if (tra->awdl_unrestricted) {
970 			ip6oa.ip6oa_flags |= IP6OAF_AWDL_UNRESTRICTED;
971 		}
972 		if (tra->intcoproc_allowed) {
973 			ip6oa.ip6oa_flags |= IP6OAF_INTCOPROC_ALLOWED;
974 		}
975 		ip6oa.ip6oa_sotc = sotc;
976 		if (tp != NULL) {
977 			if ((tp->t_inpcb->inp_socket->so_flags1 & SOF1_QOSMARKING_ALLOWED)) {
978 				ip6oa.ip6oa_flags |= IP6OAF_QOSMARKING_ALLOWED;
979 			}
980 			ip6oa.qos_marking_gencount = tp->t_inpcb->inp_policyresult.results.qos_marking_gencount;
981 			if (check_qos_marking_again) {
982 				ip6oa.ip6oa_flags |= IP6OAF_REDO_QOSMARKING_POLICY;
983 			}
984 			ip6oa.ip6oa_netsvctype = tp->t_inpcb->inp_socket->so_netsvctype;
985 		}
986 		(void) ip6_output(m, NULL, ro6, IPV6_OUTARGS, NULL,
987 		    NULL, &ip6oa);
988 
989 		if (check_qos_marking_again) {
990 			struct inpcb *inp = tp->t_inpcb;
991 			inp->inp_policyresult.results.qos_marking_gencount = ip6oa.qos_marking_gencount;
992 			if (ip6oa.ip6oa_flags & IP6OAF_QOSMARKING_ALLOWED) {
993 				inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
994 			} else {
995 				inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
996 			}
997 		}
998 
999 		if (tp != NULL && ro6 != NULL && ro6->ro_rt != NULL &&
1000 		    (outif = ro6->ro_rt->rt_ifp) !=
1001 		    tp->t_inpcb->in6p_last_outifp) {
1002 			tp->t_inpcb->in6p_last_outifp = outif;
1003 #if SKYWALK
1004 			if (NETNS_TOKEN_VALID(&tp->t_inpcb->inp_netns_token)) {
1005 				netns_set_ifnet(&tp->t_inpcb->inp_netns_token,
1006 				    tp->t_inpcb->in6p_last_outifp);
1007 			}
1008 #endif /* SKYWALK */
1009 		}
1010 
1011 		if (ro6 == &sro6) {
1012 			ROUTE_RELEASE(ro6);
1013 		}
1014 	} else {
1015 		struct ip_out_args ipoa;
1016 		bzero(&ipoa, sizeof(ipoa));
1017 		ipoa.ipoa_boundif = tra->ifscope;
1018 		ipoa.ipoa_flags = IPOAF_SELECT_SRCIF | IPOAF_BOUND_SRCADDR;
1019 		ipoa.ipoa_sotc = SO_TC_UNSPEC;
1020 		ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
1021 
1022 		if (tra->ifscope != IFSCOPE_NONE) {
1023 			ipoa.ipoa_flags |= IPOAF_BOUND_IF;
1024 		}
1025 		if (tra->nocell) {
1026 			ipoa.ipoa_flags |= IPOAF_NO_CELLULAR;
1027 		}
1028 		if (tra->noexpensive) {
1029 			ipoa.ipoa_flags |= IPOAF_NO_EXPENSIVE;
1030 		}
1031 		if (tra->noconstrained) {
1032 			ipoa.ipoa_flags |= IPOAF_NO_CONSTRAINED;
1033 		}
1034 		if (tra->awdl_unrestricted) {
1035 			ipoa.ipoa_flags |= IPOAF_AWDL_UNRESTRICTED;
1036 		}
1037 		ipoa.ipoa_sotc = sotc;
1038 		if (tp != NULL) {
1039 			if ((tp->t_inpcb->inp_socket->so_flags1 & SOF1_QOSMARKING_ALLOWED)) {
1040 				ipoa.ipoa_flags |= IPOAF_QOSMARKING_ALLOWED;
1041 			}
1042 			if (!(tp->t_inpcb->inp_socket->so_flags1 & SOF1_QOSMARKING_POLICY_OVERRIDE)) {
1043 				ipoa.ipoa_flags |= IPOAF_REDO_QOSMARKING_POLICY;
1044 			}
1045 			ipoa.qos_marking_gencount = tp->t_inpcb->inp_policyresult.results.qos_marking_gencount;
1046 			ipoa.ipoa_netsvctype = tp->t_inpcb->inp_socket->so_netsvctype;
1047 		}
1048 		if (ro != &sro) {
1049 			/* Copy the cached route and take an extra reference */
1050 			inp_route_copyout(tp->t_inpcb, &sro);
1051 		}
1052 		/*
1053 		 * For consistency, pass a local route copy.
1054 		 */
1055 		(void) ip_output(m, NULL, &sro, IP_OUTARGS, NULL, &ipoa);
1056 
1057 		if (check_qos_marking_again) {
1058 			struct inpcb *inp = tp->t_inpcb;
1059 			inp->inp_policyresult.results.qos_marking_gencount = ipoa.qos_marking_gencount;
1060 			if (ipoa.ipoa_flags & IPOAF_QOSMARKING_ALLOWED) {
1061 				inp->inp_socket->so_flags1 |= SOF1_QOSMARKING_ALLOWED;
1062 			} else {
1063 				inp->inp_socket->so_flags1 &= ~SOF1_QOSMARKING_ALLOWED;
1064 			}
1065 		}
1066 		if (tp != NULL && sro.ro_rt != NULL &&
1067 		    (outif = sro.ro_rt->rt_ifp) !=
1068 		    tp->t_inpcb->inp_last_outifp) {
1069 			tp->t_inpcb->inp_last_outifp = outif;
1070 #if SKYWALK
1071 			if (NETNS_TOKEN_VALID(&tp->t_inpcb->inp_netns_token)) {
1072 				netns_set_ifnet(&tp->t_inpcb->inp_netns_token, outif);
1073 			}
1074 #endif /* SKYWALK */
1075 		}
1076 		if (ro != &sro) {
1077 			/* Synchronize cached PCB route */
1078 			inp_route_copyin(tp->t_inpcb, &sro);
1079 		} else {
1080 			ROUTE_RELEASE(&sro);
1081 		}
1082 	}
1083 }
1084 
1085 /*
1086  * Create a new TCP control block, making an
1087  * empty reassembly queue and hooking it to the argument
1088  * protocol control block.  The `inp' parameter must have
1089  * come from the zone allocator set up in tcp_init().
1090  */
1091 struct tcpcb *
tcp_newtcpcb(struct inpcb * inp)1092 tcp_newtcpcb(struct inpcb *inp)
1093 {
1094 	struct inp_tp *it;
1095 	struct tcpcb *tp;
1096 	struct socket *so = inp->inp_socket;
1097 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
1098 	uint32_t random_32;
1099 
1100 	calculate_tcp_clock();
1101 
1102 	if ((so->so_flags1 & SOF1_CACHED_IN_SOCK_LAYER) == 0) {
1103 		it = (struct inp_tp *)(void *)inp;
1104 		tp = &it->tcb;
1105 	} else {
1106 		tp = (struct tcpcb *)(void *)inp->inp_saved_ppcb;
1107 	}
1108 
1109 	bzero((char *) tp, sizeof(struct tcpcb));
1110 	LIST_INIT(&tp->t_segq);
1111 	tp->t_maxseg = tp->t_maxopd = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
1112 
1113 	tp->t_flags = (TF_REQ_SCALE | TF_REQ_TSTMP);
1114 	tp->t_flagsext |= TF_SACK_ENABLE;
1115 
1116 	TAILQ_INIT(&tp->snd_holes);
1117 	SLIST_INIT(&tp->t_rxt_segments);
1118 	SLIST_INIT(&tp->t_notify_ack);
1119 	tp->t_inpcb = inp;
1120 	/*
1121 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
1122 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
1123 	 * reasonable initial retransmit time.
1124 	 */
1125 	tp->t_srtt = TCPTV_SRTTBASE;
1126 	tp->t_rttvar =
1127 	    ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
1128 	tp->t_rttmin = tcp_TCPTV_MIN;
1129 	tp->t_rxtcur = TCPTV_RTOBASE;
1130 
1131 	if (tcp_use_newreno) {
1132 		/* use newreno by default */
1133 		tp->tcp_cc_index = TCP_CC_ALGO_NEWRENO_INDEX;
1134 #if (DEVELOPMENT || DEBUG)
1135 	} else if (tcp_use_ledbat) {
1136 		/* use ledbat for testing */
1137 		tp->tcp_cc_index = TCP_CC_ALGO_BACKGROUND_INDEX;
1138 #endif
1139 	} else {
1140 		tp->tcp_cc_index = TCP_CC_ALGO_CUBIC_INDEX;
1141 	}
1142 
1143 	tcp_cc_allocate_state(tp);
1144 
1145 	if (CC_ALGO(tp)->init != NULL) {
1146 		CC_ALGO(tp)->init(tp);
1147 	}
1148 
1149 	/* Initialize rledbat if we are using recv_bg */
1150 	if (tcp_rledbat == 1 && TCP_RECV_BG(inp->inp_socket) &&
1151 	    tcp_cc_rledbat.init != NULL) {
1152 		tcp_cc_rledbat.init(tp);
1153 	}
1154 
1155 	tp->snd_cwnd = tcp_initial_cwnd(tp);
1156 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1157 	tp->snd_ssthresh_prev = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1158 	tp->t_rcvtime = tcp_now;
1159 	tp->tentry.timer_start = tcp_now;
1160 	tp->rcv_unackwin = tcp_now;
1161 	tp->t_persist_timeout = tcp_max_persist_timeout;
1162 	tp->t_persist_stop = 0;
1163 	tp->t_flagsext |= TF_RCVUNACK_WAITSS;
1164 	tp->t_rexmtthresh = (uint8_t)tcprexmtthresh;
1165 	tp->rfbuf_ts = tcp_now;
1166 	tp->rfbuf_space = tcp_initial_cwnd(tp);
1167 	tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
1168 
1169 	/* Enable bandwidth measurement on this connection */
1170 	tp->t_flagsext |= TF_MEASURESNDBW;
1171 	if (tp->t_bwmeas == NULL) {
1172 		tp->t_bwmeas = tcp_bwmeas_alloc(tp);
1173 		if (tp->t_bwmeas == NULL) {
1174 			tp->t_flagsext &= ~TF_MEASURESNDBW;
1175 		}
1176 	}
1177 
1178 	/* Clear time wait tailq entry */
1179 	tp->t_twentry.tqe_next = NULL;
1180 	tp->t_twentry.tqe_prev = NULL;
1181 
1182 	read_frandom(&random_32, sizeof(random_32));
1183 	tp->t_comp_gencnt = random_32;
1184 	if (tp->t_comp_gencnt <= TCP_ACK_COMPRESSION_DUMMY) {
1185 		tp->t_comp_gencnt = TCP_ACK_COMPRESSION_DUMMY + 1;
1186 	}
1187 	tp->t_comp_lastinc = tcp_now;
1188 
1189 	if (__probable(tcp_randomize_timestamps)) {
1190 		tp->t_ts_offset = random_32;
1191 	}
1192 
1193 	/*
1194 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
1195 	 * because the socket may be bound to an IPv6 wildcard address,
1196 	 * which may match an IPv4-mapped IPv6 address.
1197 	 */
1198 	inp->inp_ip_ttl = (uint8_t)ip_defttl;
1199 	inp->inp_ppcb = (caddr_t)tp;
1200 	return tp;            /* XXX */
1201 }
1202 
1203 /*
1204  * Drop a TCP connection, reporting
1205  * the specified error.  If connection is synchronized,
1206  * then send a RST to peer.
1207  */
1208 struct tcpcb *
tcp_drop(struct tcpcb * tp,int errno)1209 tcp_drop(struct tcpcb *tp, int errno)
1210 {
1211 	struct socket *so = tp->t_inpcb->inp_socket;
1212 #if CONFIG_DTRACE
1213 	struct inpcb *inp = tp->t_inpcb;
1214 #endif
1215 
1216 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
1217 		DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
1218 		    struct tcpcb *, tp, int32_t, TCPS_CLOSED);
1219 		TCP_LOG_STATE(tp, TCPS_CLOSED);
1220 		tp->t_state = TCPS_CLOSED;
1221 		(void) tcp_output(tp);
1222 		tcpstat.tcps_drops++;
1223 	} else {
1224 		tcpstat.tcps_conndrops++;
1225 	}
1226 	if (errno == ETIMEDOUT && tp->t_softerror) {
1227 		errno = tp->t_softerror;
1228 	}
1229 	so->so_error = (u_short)errno;
1230 
1231 	TCP_LOG_CONNECTION_SUMMARY(tp);
1232 
1233 	return tcp_close(tp);
1234 }
1235 
1236 void
tcp_getrt_rtt(struct tcpcb * tp,struct rtentry * rt)1237 tcp_getrt_rtt(struct tcpcb *tp, struct rtentry *rt)
1238 {
1239 	u_int32_t rtt = rt->rt_rmx.rmx_rtt;
1240 	int isnetlocal = (tp->t_flags & TF_LOCAL);
1241 
1242 	TCP_LOG_RTM_RTT(tp, rt);
1243 
1244 	if (rtt != 0 && tcp_init_rtt_from_cache != 0) {
1245 		/*
1246 		 * XXX the lock bit for RTT indicates that the value
1247 		 * is also a minimum value; this is subject to time.
1248 		 */
1249 		if (rt->rt_rmx.rmx_locks & RTV_RTT) {
1250 			tp->t_rttmin = rtt / (RTM_RTTUNIT / TCP_RETRANSHZ);
1251 		} else {
1252 			tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN :
1253 			    TCPTV_REXMTMIN;
1254 		}
1255 
1256 		tp->t_srtt =
1257 		    rtt / (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTT_SCALE));
1258 		tcpstat.tcps_usedrtt++;
1259 
1260 		if (rt->rt_rmx.rmx_rttvar) {
1261 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1262 			    (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTTVAR_SCALE));
1263 			tcpstat.tcps_usedrttvar++;
1264 		} else {
1265 			/* default variation is +- 1 rtt */
1266 			tp->t_rttvar =
1267 			    tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
1268 		}
1269 
1270 		/*
1271 		 * The RTO formula in the route metric case is based on:
1272 		 *     srtt + 4 * rttvar
1273 		 * modulo the min, max and slop
1274 		 */
1275 		TCPT_RANGESET(tp->t_rxtcur,
1276 		    TCP_REXMTVAL(tp),
1277 		    tp->t_rttmin, TCPTV_REXMTMAX,
1278 		    TCP_ADD_REXMTSLOP(tp));
1279 	}
1280 
1281 	TCP_LOG_RTT_INFO(tp);
1282 }
1283 
1284 static inline void
tcp_create_ifnet_stats_per_flow(struct tcpcb * tp,struct ifnet_stats_per_flow * ifs)1285 tcp_create_ifnet_stats_per_flow(struct tcpcb *tp,
1286     struct ifnet_stats_per_flow *ifs)
1287 {
1288 	struct inpcb *inp;
1289 	struct socket *so;
1290 	if (tp == NULL || ifs == NULL) {
1291 		return;
1292 	}
1293 
1294 	bzero(ifs, sizeof(*ifs));
1295 	inp = tp->t_inpcb;
1296 	so = inp->inp_socket;
1297 
1298 	ifs->ipv4 = (inp->inp_vflag & INP_IPV6) ? 0 : 1;
1299 	ifs->local = (tp->t_flags & TF_LOCAL) ? 1 : 0;
1300 	ifs->connreset = (so->so_error == ECONNRESET) ? 1 : 0;
1301 	ifs->conntimeout = (so->so_error == ETIMEDOUT) ? 1 : 0;
1302 	ifs->ecn_flags = tp->ecn_flags;
1303 	ifs->txretransmitbytes = tp->t_stat.txretransmitbytes;
1304 	ifs->rxoutoforderbytes = tp->t_stat.rxoutoforderbytes;
1305 	ifs->rxmitpkts = tp->t_stat.rxmitpkts;
1306 	ifs->rcvoopack = tp->t_rcvoopack;
1307 	ifs->pawsdrop = tp->t_pawsdrop;
1308 	ifs->sack_recovery_episodes = tp->t_sack_recovery_episode;
1309 	ifs->reordered_pkts = tp->t_reordered_pkts;
1310 	ifs->dsack_sent = tp->t_dsack_sent;
1311 	ifs->dsack_recvd = tp->t_dsack_recvd;
1312 	ifs->srtt = tp->t_srtt;
1313 	ifs->rttupdated = tp->t_rttupdated;
1314 	ifs->rttvar = tp->t_rttvar;
1315 	ifs->rttmin = get_base_rtt(tp);
1316 	if (tp->t_bwmeas != NULL && tp->t_bwmeas->bw_sndbw_max > 0) {
1317 		ifs->bw_sndbw_max = tp->t_bwmeas->bw_sndbw_max;
1318 	} else {
1319 		ifs->bw_sndbw_max = 0;
1320 	}
1321 	if (tp->t_bwmeas != NULL && tp->t_bwmeas->bw_rcvbw_max > 0) {
1322 		ifs->bw_rcvbw_max = tp->t_bwmeas->bw_rcvbw_max;
1323 	} else {
1324 		ifs->bw_rcvbw_max = 0;
1325 	}
1326 	ifs->bk_txpackets = so->so_tc_stats[MBUF_TC_BK].txpackets;
1327 	ifs->txpackets = inp->inp_stat->txpackets;
1328 	ifs->rxpackets = inp->inp_stat->rxpackets;
1329 }
1330 
1331 static inline void
tcp_flow_ecn_perf_stats(struct ifnet_stats_per_flow * ifs,struct if_tcp_ecn_perf_stat * stat)1332 tcp_flow_ecn_perf_stats(struct ifnet_stats_per_flow *ifs,
1333     struct if_tcp_ecn_perf_stat *stat)
1334 {
1335 	u_int64_t curval, oldval;
1336 	stat->total_txpkts += ifs->txpackets;
1337 	stat->total_rxpkts += ifs->rxpackets;
1338 	stat->total_rxmitpkts += ifs->rxmitpkts;
1339 	stat->total_oopkts += ifs->rcvoopack;
1340 	stat->total_reorderpkts += (ifs->reordered_pkts +
1341 	    ifs->pawsdrop + ifs->dsack_sent + ifs->dsack_recvd);
1342 
1343 	/* Average RTT */
1344 	curval = ifs->srtt >> TCP_RTT_SHIFT;
1345 	if (curval > 0 && ifs->rttupdated >= 16) {
1346 		if (stat->rtt_avg == 0) {
1347 			stat->rtt_avg = curval;
1348 		} else {
1349 			oldval = stat->rtt_avg;
1350 			stat->rtt_avg = ((oldval << 4) - oldval + curval) >> 4;
1351 		}
1352 	}
1353 
1354 	/* RTT variance */
1355 	curval = ifs->rttvar >> TCP_RTTVAR_SHIFT;
1356 	if (curval > 0 && ifs->rttupdated >= 16) {
1357 		if (stat->rtt_var == 0) {
1358 			stat->rtt_var = curval;
1359 		} else {
1360 			oldval = stat->rtt_var;
1361 			stat->rtt_var =
1362 			    ((oldval << 4) - oldval + curval) >> 4;
1363 		}
1364 	}
1365 
1366 	/* SACK episodes */
1367 	stat->sack_episodes += ifs->sack_recovery_episodes;
1368 	if (ifs->connreset) {
1369 		stat->rst_drop++;
1370 	}
1371 }
1372 
1373 static inline void
tcp_flow_lim_stats(struct ifnet_stats_per_flow * ifs,struct if_lim_perf_stat * stat)1374 tcp_flow_lim_stats(struct ifnet_stats_per_flow *ifs,
1375     struct if_lim_perf_stat *stat)
1376 {
1377 	u_int64_t curval, oldval;
1378 
1379 	stat->lim_total_txpkts += ifs->txpackets;
1380 	stat->lim_total_rxpkts += ifs->rxpackets;
1381 	stat->lim_total_retxpkts += ifs->rxmitpkts;
1382 	stat->lim_total_oopkts += ifs->rcvoopack;
1383 
1384 	if (ifs->bw_sndbw_max > 0) {
1385 		/* convert from bytes per ms to bits per second */
1386 		ifs->bw_sndbw_max *= 8000;
1387 		stat->lim_ul_max_bandwidth = MAX(stat->lim_ul_max_bandwidth,
1388 		    ifs->bw_sndbw_max);
1389 	}
1390 
1391 	if (ifs->bw_rcvbw_max > 0) {
1392 		/* convert from bytes per ms to bits per second */
1393 		ifs->bw_rcvbw_max *= 8000;
1394 		stat->lim_dl_max_bandwidth = MAX(stat->lim_dl_max_bandwidth,
1395 		    ifs->bw_rcvbw_max);
1396 	}
1397 
1398 	/* Average RTT */
1399 	curval = ifs->srtt >> TCP_RTT_SHIFT;
1400 	if (curval > 0 && ifs->rttupdated >= 16) {
1401 		if (stat->lim_rtt_average == 0) {
1402 			stat->lim_rtt_average = curval;
1403 		} else {
1404 			oldval = stat->lim_rtt_average;
1405 			stat->lim_rtt_average =
1406 			    ((oldval << 4) - oldval + curval) >> 4;
1407 		}
1408 	}
1409 
1410 	/* RTT variance */
1411 	curval = ifs->rttvar >> TCP_RTTVAR_SHIFT;
1412 	if (curval > 0 && ifs->rttupdated >= 16) {
1413 		if (stat->lim_rtt_variance == 0) {
1414 			stat->lim_rtt_variance = curval;
1415 		} else {
1416 			oldval = stat->lim_rtt_variance;
1417 			stat->lim_rtt_variance =
1418 			    ((oldval << 4) - oldval + curval) >> 4;
1419 		}
1420 	}
1421 
1422 	if (stat->lim_rtt_min == 0) {
1423 		stat->lim_rtt_min = ifs->rttmin;
1424 	} else {
1425 		stat->lim_rtt_min = MIN(stat->lim_rtt_min, ifs->rttmin);
1426 	}
1427 
1428 	/* connection timeouts */
1429 	stat->lim_conn_attempts++;
1430 	if (ifs->conntimeout) {
1431 		stat->lim_conn_timeouts++;
1432 	}
1433 
1434 	/* bytes sent using background delay-based algorithms */
1435 	stat->lim_bk_txpkts += ifs->bk_txpackets;
1436 }
1437 
1438 /*
1439  * Close a TCP control block:
1440  *	discard all space held by the tcp
1441  *	discard internet protocol block
1442  *	wake up any sleepers
1443  */
1444 struct tcpcb *
tcp_close(struct tcpcb * tp)1445 tcp_close(struct tcpcb *tp)
1446 {
1447 	struct inpcb *inp = tp->t_inpcb;
1448 	struct socket *so = inp->inp_socket;
1449 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
1450 	struct route *ro;
1451 	struct rtentry *rt;
1452 	int dosavessthresh;
1453 	struct ifnet_stats_per_flow ifs;
1454 
1455 	/* tcp_close was called previously, bail */
1456 	if (inp->inp_ppcb == NULL) {
1457 		return NULL;
1458 	}
1459 
1460 	tcp_del_fsw_flow(tp);
1461 
1462 	tcp_canceltimers(tp);
1463 	KERNEL_DEBUG(DBG_FNC_TCP_CLOSE | DBG_FUNC_START, tp, 0, 0, 0, 0);
1464 
1465 	/*
1466 	 * If another thread for this tcp is currently in ip (indicated by
1467 	 * the TF_SENDINPROG flag), defer the cleanup until after it returns
1468 	 * back to tcp.  This is done to serialize the close until after all
1469 	 * pending output is finished, in order to avoid having the PCB be
1470 	 * detached and the cached route cleaned, only for ip to cache the
1471 	 * route back into the PCB again.  Note that we've cleared all the
1472 	 * timers at this point.  Set TF_CLOSING to indicate to tcp_output()
1473 	 * that is should call us again once it returns from ip; at that
1474 	 * point both flags should be cleared and we can proceed further
1475 	 * with the cleanup.
1476 	 */
1477 	if ((tp->t_flags & TF_CLOSING) ||
1478 	    inp->inp_sndinprog_cnt > 0) {
1479 		tp->t_flags |= TF_CLOSING;
1480 		return NULL;
1481 	}
1482 
1483 	TCP_LOG_CONNECTION_SUMMARY(tp);
1484 
1485 	DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
1486 	    struct tcpcb *, tp, int32_t, TCPS_CLOSED);
1487 
1488 	ro = (isipv6 ? (struct route *)&inp->in6p_route : &inp->inp_route);
1489 	rt = ro->ro_rt;
1490 	if (rt != NULL) {
1491 		RT_LOCK_SPIN(rt);
1492 	}
1493 
1494 	/*
1495 	 * If we got enough samples through the srtt filter,
1496 	 * save the rtt and rttvar in the routing entry.
1497 	 * 'Enough' is arbitrarily defined as the 16 samples.
1498 	 * 16 samples is enough for the srtt filter to converge
1499 	 * to within 5% of the correct value; fewer samples and
1500 	 * we could save a very bogus rtt.
1501 	 *
1502 	 * Don't update the default route's characteristics and don't
1503 	 * update anything that the user "locked".
1504 	 */
1505 	if (tp->t_rttupdated >= 16) {
1506 		u_int32_t i = 0;
1507 		bool log_rtt = false;
1508 
1509 		if (isipv6) {
1510 			struct sockaddr_in6 *sin6;
1511 
1512 			if (rt == NULL) {
1513 				goto no_valid_rt;
1514 			}
1515 			sin6 = (struct sockaddr_in6 *)(void *)rt_key(rt);
1516 			if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
1517 				goto no_valid_rt;
1518 			}
1519 		} else if (ROUTE_UNUSABLE(ro) ||
1520 		    SIN(rt_key(rt))->sin_addr.s_addr == INADDR_ANY) {
1521 			DTRACE_TCP4(state__change, void, NULL,
1522 			    struct inpcb *, inp, struct tcpcb *, tp,
1523 			    int32_t, TCPS_CLOSED);
1524 			TCP_LOG_STATE(tp, TCPS_CLOSED);
1525 			tp->t_state = TCPS_CLOSED;
1526 			goto no_valid_rt;
1527 		}
1528 
1529 		RT_LOCK_ASSERT_HELD(rt);
1530 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
1531 			i = tp->t_srtt *
1532 			    (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTT_SCALE));
1533 			if (rt->rt_rmx.rmx_rtt && i) {
1534 				/*
1535 				 * filter this update to half the old & half
1536 				 * the new values, converting scale.
1537 				 * See route.h and tcp_var.h for a
1538 				 * description of the scaling constants.
1539 				 */
1540 				rt->rt_rmx.rmx_rtt =
1541 				    (rt->rt_rmx.rmx_rtt + i) / 2;
1542 			} else {
1543 				rt->rt_rmx.rmx_rtt = i;
1544 			}
1545 			tcpstat.tcps_cachedrtt++;
1546 			log_rtt = true;
1547 		}
1548 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
1549 			i = tp->t_rttvar *
1550 			    (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTTVAR_SCALE));
1551 			if (rt->rt_rmx.rmx_rttvar && i) {
1552 				rt->rt_rmx.rmx_rttvar =
1553 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
1554 			} else {
1555 				rt->rt_rmx.rmx_rttvar = i;
1556 			}
1557 			tcpstat.tcps_cachedrttvar++;
1558 			log_rtt = true;
1559 		}
1560 		if (log_rtt) {
1561 			TCP_LOG_RTM_RTT(tp, rt);
1562 			TCP_LOG_RTT_INFO(tp);
1563 		}
1564 		/*
1565 		 * The old comment here said:
1566 		 * update the pipelimit (ssthresh) if it has been updated
1567 		 * already or if a pipesize was specified & the threshhold
1568 		 * got below half the pipesize.  I.e., wait for bad news
1569 		 * before we start updating, then update on both good
1570 		 * and bad news.
1571 		 *
1572 		 * But we want to save the ssthresh even if no pipesize is
1573 		 * specified explicitly in the route, because such
1574 		 * connections still have an implicit pipesize specified
1575 		 * by the global tcp_sendspace.  In the absence of a reliable
1576 		 * way to calculate the pipesize, it will have to do.
1577 		 */
1578 		i = tp->snd_ssthresh;
1579 		if (rt->rt_rmx.rmx_sendpipe != 0) {
1580 			dosavessthresh = (i < rt->rt_rmx.rmx_sendpipe / 2);
1581 		} else {
1582 			dosavessthresh = (i < so->so_snd.sb_hiwat / 2);
1583 		}
1584 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
1585 		    i != 0 && rt->rt_rmx.rmx_ssthresh != 0) ||
1586 		    dosavessthresh) {
1587 			/*
1588 			 * convert the limit from user data bytes to
1589 			 * packets then to packet data bytes.
1590 			 */
1591 			i = (i + tp->t_maxseg / 2) / tp->t_maxseg;
1592 			if (i < 2) {
1593 				i = 2;
1594 			}
1595 			i *= (u_int32_t)(tp->t_maxseg +
1596 			    isipv6 ? sizeof(struct ip6_hdr) +
1597 			    sizeof(struct tcphdr) :
1598 			    sizeof(struct tcpiphdr));
1599 			if (rt->rt_rmx.rmx_ssthresh) {
1600 				rt->rt_rmx.rmx_ssthresh =
1601 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
1602 			} else {
1603 				rt->rt_rmx.rmx_ssthresh = i;
1604 			}
1605 			tcpstat.tcps_cachedssthresh++;
1606 		}
1607 	}
1608 
1609 	/*
1610 	 * Mark route for deletion if no information is cached.
1611 	 */
1612 	if (rt != NULL && (so->so_flags & SOF_OVERFLOW)) {
1613 		if (!(rt->rt_rmx.rmx_locks & RTV_RTT) &&
1614 		    rt->rt_rmx.rmx_rtt == 0) {
1615 			rt->rt_flags |= RTF_DELCLONE;
1616 		}
1617 	}
1618 
1619 no_valid_rt:
1620 	if (rt != NULL) {
1621 		RT_UNLOCK(rt);
1622 	}
1623 
1624 	/* free the reassembly queue, if any */
1625 	(void) tcp_freeq(tp);
1626 
1627 	/* performance stats per interface */
1628 	tcp_create_ifnet_stats_per_flow(tp, &ifs);
1629 	tcp_update_stats_per_flow(&ifs, inp->inp_last_outifp);
1630 
1631 	tcp_free_sackholes(tp);
1632 	tcp_notify_ack_free(tp);
1633 
1634 	inp_decr_sndbytes_allunsent(so, tp->snd_una);
1635 
1636 	if (tp->t_bwmeas != NULL) {
1637 		tcp_bwmeas_free(tp);
1638 	}
1639 	tcp_rxtseg_clean(tp);
1640 	/* Free the packet list */
1641 	if (tp->t_pktlist_head != NULL) {
1642 		m_freem_list(tp->t_pktlist_head);
1643 	}
1644 	TCP_PKTLIST_CLEAR(tp);
1645 
1646 	if (so->so_flags1 & SOF1_CACHED_IN_SOCK_LAYER) {
1647 		inp->inp_saved_ppcb = (caddr_t) tp;
1648 	}
1649 
1650 	TCP_LOG_STATE(tp, TCPS_CLOSED);
1651 	tp->t_state = TCPS_CLOSED;
1652 
1653 	/*
1654 	 * Issue a wakeup before detach so that we don't miss
1655 	 * a wakeup
1656 	 */
1657 	sodisconnectwakeup(so);
1658 
1659 	/*
1660 	 * Make sure to clear the TCP Keep Alive Offload as it is
1661 	 * ref counted on the interface
1662 	 */
1663 	tcp_clear_keep_alive_offload(so);
1664 
1665 	/*
1666 	 * If this is a socket that does not want to wakeup the device
1667 	 * for it's traffic, the application might need to know that the
1668 	 * socket is closed, send a notification.
1669 	 */
1670 	if ((so->so_options & SO_NOWAKEFROMSLEEP) &&
1671 	    inp->inp_state != INPCB_STATE_DEAD &&
1672 	    !(inp->inp_flags2 & INP2_TIMEWAIT)) {
1673 		socket_post_kev_msg_closed(so);
1674 	}
1675 
1676 	if (CC_ALGO(tp)->cleanup != NULL) {
1677 		CC_ALGO(tp)->cleanup(tp);
1678 	}
1679 
1680 	tp->tcp_cc_index = TCP_CC_ALGO_NONE;
1681 
1682 	if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.cleanup != NULL) {
1683 		tcp_cc_rledbat.cleanup(tp);
1684 	}
1685 
1686 	/* Can happen if we close the socket before receiving the third ACK */
1687 	if ((tp->t_tfo_flags & TFO_F_COOKIE_VALID)) {
1688 		OSDecrementAtomic(&tcp_tfo_halfcnt);
1689 
1690 		/* Panic if something has gone terribly wrong. */
1691 		VERIFY(tcp_tfo_halfcnt >= 0);
1692 
1693 		tp->t_tfo_flags &= ~TFO_F_COOKIE_VALID;
1694 	}
1695 
1696 	if (SOCK_CHECK_DOM(so, PF_INET6)) {
1697 		in6_pcbdetach(inp);
1698 	} else {
1699 		in_pcbdetach(inp);
1700 	}
1701 
1702 	/*
1703 	 * Call soisdisconnected after detach because it might unlock the socket
1704 	 */
1705 	soisdisconnected(so);
1706 	tcpstat.tcps_closed++;
1707 	KERNEL_DEBUG(DBG_FNC_TCP_CLOSE | DBG_FUNC_END,
1708 	    tcpstat.tcps_closed, 0, 0, 0, 0);
1709 	return NULL;
1710 }
1711 
1712 int
tcp_freeq(struct tcpcb * tp)1713 tcp_freeq(struct tcpcb *tp)
1714 {
1715 	struct tseg_qent *q;
1716 	int rv = 0;
1717 	int count = 0;
1718 
1719 	while ((q = LIST_FIRST(&tp->t_segq)) != NULL) {
1720 		LIST_REMOVE(q, tqe_q);
1721 		tp->t_reassq_mbcnt -= MSIZE + (q->tqe_m->m_flags & M_EXT) ?
1722 		    q->tqe_m->m_ext.ext_size : 0;
1723 		m_freem(q->tqe_m);
1724 		zfree(tcp_reass_zone, q);
1725 		rv = 1;
1726 		count++;
1727 	}
1728 	tp->t_reassqlen = 0;
1729 	if (count > 0) {
1730 		OSAddAtomic(-count, &tcp_reass_total_qlen);
1731 	}
1732 	return rv;
1733 }
1734 
1735 
1736 void
tcp_drain(void)1737 tcp_drain(void)
1738 {
1739 	struct inpcb *inp;
1740 	struct tcpcb *tp;
1741 
1742 	if (!lck_rw_try_lock_exclusive(&tcbinfo.ipi_lock)) {
1743 		return;
1744 	}
1745 
1746 	LIST_FOREACH(inp, tcbinfo.ipi_listhead, inp_list) {
1747 		if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) !=
1748 		    WNT_STOPUSING) {
1749 			socket_lock(inp->inp_socket, 1);
1750 			if (in_pcb_checkstate(inp, WNT_RELEASE, 1)
1751 			    == WNT_STOPUSING) {
1752 				/* lost a race, try the next one */
1753 				socket_unlock(inp->inp_socket, 1);
1754 				continue;
1755 			}
1756 			tp = intotcpcb(inp);
1757 
1758 			so_drain_extended_bk_idle(inp->inp_socket);
1759 
1760 			socket_unlock(inp->inp_socket, 1);
1761 		}
1762 	}
1763 	lck_rw_done(&tcbinfo.ipi_lock);
1764 }
1765 
1766 /*
1767  * Notify a tcp user of an asynchronous error;
1768  * store error as soft error, but wake up user
1769  * (for now, won't do anything until can select for soft error).
1770  *
1771  * Do not wake up user since there currently is no mechanism for
1772  * reporting soft errors (yet - a kqueue filter may be added).
1773  */
1774 static void
tcp_notify(struct inpcb * inp,int error)1775 tcp_notify(struct inpcb *inp, int error)
1776 {
1777 	struct tcpcb *tp;
1778 
1779 	if (inp == NULL || (inp->inp_state == INPCB_STATE_DEAD)) {
1780 		return; /* pcb is gone already */
1781 	}
1782 	tp = (struct tcpcb *)inp->inp_ppcb;
1783 
1784 	VERIFY(tp != NULL);
1785 	/*
1786 	 * Ignore some errors if we are hooked up.
1787 	 * If connection hasn't completed, has retransmitted several times,
1788 	 * and receives a second error, give up now.  This is better
1789 	 * than waiting a long time to establish a connection that
1790 	 * can never complete.
1791 	 */
1792 	if (tp->t_state == TCPS_ESTABLISHED &&
1793 	    (error == EHOSTUNREACH || error == ENETUNREACH ||
1794 	    error == EHOSTDOWN)) {
1795 		if (inp->inp_route.ro_rt) {
1796 			rtfree(inp->inp_route.ro_rt);
1797 			inp->inp_route.ro_rt = (struct rtentry *)NULL;
1798 		}
1799 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
1800 	    tp->t_softerror) {
1801 		tcp_drop(tp, error);
1802 	} else {
1803 		tp->t_softerror = error;
1804 	}
1805 }
1806 
1807 struct bwmeas *
tcp_bwmeas_alloc(struct tcpcb * tp)1808 tcp_bwmeas_alloc(struct tcpcb *tp)
1809 {
1810 	struct bwmeas *elm;
1811 	elm = zalloc_flags(tcp_bwmeas_zone, Z_ZERO | Z_WAITOK);
1812 	elm->bw_minsizepkts = TCP_BWMEAS_BURST_MINSIZE;
1813 	elm->bw_minsize = elm->bw_minsizepkts * tp->t_maxseg;
1814 	return elm;
1815 }
1816 
1817 void
tcp_bwmeas_free(struct tcpcb * tp)1818 tcp_bwmeas_free(struct tcpcb *tp)
1819 {
1820 	zfree(tcp_bwmeas_zone, tp->t_bwmeas);
1821 	tp->t_bwmeas = NULL;
1822 	tp->t_flagsext &= ~(TF_MEASURESNDBW);
1823 }
1824 
1825 int
get_tcp_inp_list(struct inpcb ** inp_list,int n,inp_gen_t gencnt)1826 get_tcp_inp_list(struct inpcb **inp_list, int n, inp_gen_t gencnt)
1827 {
1828 	struct tcpcb *tp;
1829 	struct inpcb *inp;
1830 	int i = 0;
1831 
1832 	LIST_FOREACH(inp, tcbinfo.ipi_listhead, inp_list) {
1833 		if (inp->inp_gencnt <= gencnt &&
1834 		    inp->inp_state != INPCB_STATE_DEAD) {
1835 			inp_list[i++] = inp;
1836 		}
1837 		if (i >= n) {
1838 			break;
1839 		}
1840 	}
1841 
1842 	TAILQ_FOREACH(tp, &tcp_tw_tailq, t_twentry) {
1843 		inp = tp->t_inpcb;
1844 		if (inp->inp_gencnt <= gencnt &&
1845 		    inp->inp_state != INPCB_STATE_DEAD) {
1846 			inp_list[i++] = inp;
1847 		}
1848 		if (i >= n) {
1849 			break;
1850 		}
1851 	}
1852 	return i;
1853 }
1854 
1855 /*
1856  * tcpcb_to_otcpcb copies specific bits of a tcpcb to a otcpcb format.
1857  * The otcpcb data structure is passed to user space and must not change.
1858  */
1859 static void
tcpcb_to_otcpcb(struct tcpcb * tp,struct otcpcb * otp)1860 tcpcb_to_otcpcb(struct tcpcb *tp, struct otcpcb *otp)
1861 {
1862 	otp->t_segq = (uint32_t)VM_KERNEL_ADDRPERM(tp->t_segq.lh_first);
1863 	otp->t_dupacks = tp->t_dupacks;
1864 	otp->t_timer[TCPT_REXMT_EXT] = tp->t_timer[TCPT_REXMT];
1865 	otp->t_timer[TCPT_PERSIST_EXT] = tp->t_timer[TCPT_PERSIST];
1866 	otp->t_timer[TCPT_KEEP_EXT] = tp->t_timer[TCPT_KEEP];
1867 	otp->t_timer[TCPT_2MSL_EXT] = tp->t_timer[TCPT_2MSL];
1868 	otp->t_inpcb =
1869 	    (_TCPCB_PTR(struct inpcb *))VM_KERNEL_ADDRPERM(tp->t_inpcb);
1870 	otp->t_state = tp->t_state;
1871 	otp->t_flags = tp->t_flags;
1872 	otp->t_force = (tp->t_flagsext & TF_FORCE) ? 1 : 0;
1873 	otp->snd_una = tp->snd_una;
1874 	otp->snd_max = tp->snd_max;
1875 	otp->snd_nxt = tp->snd_nxt;
1876 	otp->snd_up = tp->snd_up;
1877 	otp->snd_wl1 = tp->snd_wl1;
1878 	otp->snd_wl2 = tp->snd_wl2;
1879 	otp->iss = tp->iss;
1880 	otp->irs = tp->irs;
1881 	otp->rcv_nxt = tp->rcv_nxt;
1882 	otp->rcv_adv = tp->rcv_adv;
1883 	otp->rcv_wnd = tp->rcv_wnd;
1884 	otp->rcv_up = tp->rcv_up;
1885 	otp->snd_wnd = tp->snd_wnd;
1886 	otp->snd_cwnd = tp->snd_cwnd;
1887 	otp->snd_ssthresh = tp->snd_ssthresh;
1888 	otp->t_maxopd = tp->t_maxopd;
1889 	otp->t_rcvtime = tp->t_rcvtime;
1890 	otp->t_starttime = tp->t_starttime;
1891 	otp->t_rtttime = tp->t_rtttime;
1892 	otp->t_rtseq = tp->t_rtseq;
1893 	otp->t_rxtcur = tp->t_rxtcur;
1894 	otp->t_maxseg = tp->t_maxseg;
1895 	otp->t_srtt = tp->t_srtt;
1896 	otp->t_rttvar = tp->t_rttvar;
1897 	otp->t_rxtshift = tp->t_rxtshift;
1898 	otp->t_rttmin = tp->t_rttmin;
1899 	otp->t_rttupdated = tp->t_rttupdated;
1900 	otp->max_sndwnd = tp->max_sndwnd;
1901 	otp->t_softerror = tp->t_softerror;
1902 	otp->t_oobflags = tp->t_oobflags;
1903 	otp->t_iobc = tp->t_iobc;
1904 	otp->snd_scale = tp->snd_scale;
1905 	otp->rcv_scale = tp->rcv_scale;
1906 	otp->request_r_scale = tp->request_r_scale;
1907 	otp->requested_s_scale = tp->requested_s_scale;
1908 	otp->ts_recent = tp->ts_recent;
1909 	otp->ts_recent_age = tp->ts_recent_age;
1910 	otp->last_ack_sent = tp->last_ack_sent;
1911 	otp->cc_send = 0;
1912 	otp->cc_recv = 0;
1913 	otp->snd_recover = tp->snd_recover;
1914 	otp->snd_cwnd_prev = tp->snd_cwnd_prev;
1915 	otp->snd_ssthresh_prev = tp->snd_ssthresh_prev;
1916 	otp->t_badrxtwin = 0;
1917 }
1918 
1919 static int
1920 tcp_pcblist SYSCTL_HANDLER_ARGS
1921 {
1922 #pragma unused(oidp, arg1, arg2)
1923 	int error, i = 0, n, sz;
1924 	struct inpcb **inp_list;
1925 	inp_gen_t gencnt;
1926 	struct xinpgen xig;
1927 
1928 	/*
1929 	 * The process of preparing the TCB list is too time-consuming and
1930 	 * resource-intensive to repeat twice on every request.
1931 	 */
1932 	lck_rw_lock_shared(&tcbinfo.ipi_lock);
1933 	if (req->oldptr == USER_ADDR_NULL) {
1934 		n = tcbinfo.ipi_count;
1935 		req->oldidx = 2 * (sizeof(xig))
1936 		    + (n + n / 8) * sizeof(struct xtcpcb);
1937 		lck_rw_done(&tcbinfo.ipi_lock);
1938 		return 0;
1939 	}
1940 
1941 	if (req->newptr != USER_ADDR_NULL) {
1942 		lck_rw_done(&tcbinfo.ipi_lock);
1943 		return EPERM;
1944 	}
1945 
1946 	/*
1947 	 * OK, now we're committed to doing something.
1948 	 */
1949 	gencnt = tcbinfo.ipi_gencnt;
1950 	sz = n = tcbinfo.ipi_count;
1951 
1952 	bzero(&xig, sizeof(xig));
1953 	xig.xig_len = sizeof(xig);
1954 	xig.xig_count = n;
1955 	xig.xig_gen = gencnt;
1956 	xig.xig_sogen = so_gencnt;
1957 	error = SYSCTL_OUT(req, &xig, sizeof(xig));
1958 	if (error) {
1959 		lck_rw_done(&tcbinfo.ipi_lock);
1960 		return error;
1961 	}
1962 	/*
1963 	 * We are done if there is no pcb
1964 	 */
1965 	if (n == 0) {
1966 		lck_rw_done(&tcbinfo.ipi_lock);
1967 		return 0;
1968 	}
1969 
1970 	inp_list = kalloc_type(struct inpcb *, n, Z_WAITOK);
1971 	if (inp_list == NULL) {
1972 		lck_rw_done(&tcbinfo.ipi_lock);
1973 		return ENOMEM;
1974 	}
1975 
1976 	n = get_tcp_inp_list(inp_list, n, gencnt);
1977 
1978 	error = 0;
1979 	for (i = 0; i < n; i++) {
1980 		struct xtcpcb xt;
1981 		caddr_t inp_ppcb;
1982 		struct inpcb *inp;
1983 
1984 		inp = inp_list[i];
1985 
1986 		if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
1987 			continue;
1988 		}
1989 		socket_lock(inp->inp_socket, 1);
1990 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
1991 			socket_unlock(inp->inp_socket, 1);
1992 			continue;
1993 		}
1994 		if (inp->inp_gencnt > gencnt) {
1995 			socket_unlock(inp->inp_socket, 1);
1996 			continue;
1997 		}
1998 
1999 		bzero(&xt, sizeof(xt));
2000 		xt.xt_len = sizeof(xt);
2001 		/* XXX should avoid extra copy */
2002 		inpcb_to_compat(inp, &xt.xt_inp);
2003 		inp_ppcb = inp->inp_ppcb;
2004 		if (inp_ppcb != NULL) {
2005 			tcpcb_to_otcpcb((struct tcpcb *)(void *)inp_ppcb,
2006 			    &xt.xt_tp);
2007 		} else {
2008 			bzero((char *) &xt.xt_tp, sizeof(xt.xt_tp));
2009 		}
2010 		if (inp->inp_socket) {
2011 			sotoxsocket(inp->inp_socket, &xt.xt_socket);
2012 		}
2013 
2014 		socket_unlock(inp->inp_socket, 1);
2015 
2016 		error = SYSCTL_OUT(req, &xt, sizeof(xt));
2017 	}
2018 	if (!error) {
2019 		/*
2020 		 * Give the user an updated idea of our state.
2021 		 * If the generation differs from what we told
2022 		 * her before, she knows that something happened
2023 		 * while we were processing this request, and it
2024 		 * might be necessary to retry.
2025 		 */
2026 		bzero(&xig, sizeof(xig));
2027 		xig.xig_len = sizeof(xig);
2028 		xig.xig_gen = tcbinfo.ipi_gencnt;
2029 		xig.xig_sogen = so_gencnt;
2030 		xig.xig_count = tcbinfo.ipi_count;
2031 		error = SYSCTL_OUT(req, &xig, sizeof(xig));
2032 	}
2033 
2034 	lck_rw_done(&tcbinfo.ipi_lock);
2035 	kfree_type(struct inpcb *, sz, inp_list);
2036 	return error;
2037 }
2038 
2039 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist,
2040     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
2041     tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
2042 
2043 #if XNU_TARGET_OS_OSX
2044 
2045 static void
tcpcb_to_xtcpcb64(struct tcpcb * tp,struct xtcpcb64 * otp)2046 tcpcb_to_xtcpcb64(struct tcpcb *tp, struct xtcpcb64 *otp)
2047 {
2048 	otp->t_segq = (uint32_t)VM_KERNEL_ADDRPERM(tp->t_segq.lh_first);
2049 	otp->t_dupacks = tp->t_dupacks;
2050 	otp->t_timer[TCPT_REXMT_EXT] = tp->t_timer[TCPT_REXMT];
2051 	otp->t_timer[TCPT_PERSIST_EXT] = tp->t_timer[TCPT_PERSIST];
2052 	otp->t_timer[TCPT_KEEP_EXT] = tp->t_timer[TCPT_KEEP];
2053 	otp->t_timer[TCPT_2MSL_EXT] = tp->t_timer[TCPT_2MSL];
2054 	otp->t_state = tp->t_state;
2055 	otp->t_flags = tp->t_flags;
2056 	otp->t_force = (tp->t_flagsext & TF_FORCE) ? 1 : 0;
2057 	otp->snd_una = tp->snd_una;
2058 	otp->snd_max = tp->snd_max;
2059 	otp->snd_nxt = tp->snd_nxt;
2060 	otp->snd_up = tp->snd_up;
2061 	otp->snd_wl1 = tp->snd_wl1;
2062 	otp->snd_wl2 = tp->snd_wl2;
2063 	otp->iss = tp->iss;
2064 	otp->irs = tp->irs;
2065 	otp->rcv_nxt = tp->rcv_nxt;
2066 	otp->rcv_adv = tp->rcv_adv;
2067 	otp->rcv_wnd = tp->rcv_wnd;
2068 	otp->rcv_up = tp->rcv_up;
2069 	otp->snd_wnd = tp->snd_wnd;
2070 	otp->snd_cwnd = tp->snd_cwnd;
2071 	otp->snd_ssthresh = tp->snd_ssthresh;
2072 	otp->t_maxopd = tp->t_maxopd;
2073 	otp->t_rcvtime = tp->t_rcvtime;
2074 	otp->t_starttime = tp->t_starttime;
2075 	otp->t_rtttime = tp->t_rtttime;
2076 	otp->t_rtseq = tp->t_rtseq;
2077 	otp->t_rxtcur = tp->t_rxtcur;
2078 	otp->t_maxseg = tp->t_maxseg;
2079 	otp->t_srtt = tp->t_srtt;
2080 	otp->t_rttvar = tp->t_rttvar;
2081 	otp->t_rxtshift = tp->t_rxtshift;
2082 	otp->t_rttmin = tp->t_rttmin;
2083 	otp->t_rttupdated = tp->t_rttupdated;
2084 	otp->max_sndwnd = tp->max_sndwnd;
2085 	otp->t_softerror = tp->t_softerror;
2086 	otp->t_oobflags = tp->t_oobflags;
2087 	otp->t_iobc = tp->t_iobc;
2088 	otp->snd_scale = tp->snd_scale;
2089 	otp->rcv_scale = tp->rcv_scale;
2090 	otp->request_r_scale = tp->request_r_scale;
2091 	otp->requested_s_scale = tp->requested_s_scale;
2092 	otp->ts_recent = tp->ts_recent;
2093 	otp->ts_recent_age = tp->ts_recent_age;
2094 	otp->last_ack_sent = tp->last_ack_sent;
2095 	otp->cc_send = 0;
2096 	otp->cc_recv = 0;
2097 	otp->snd_recover = tp->snd_recover;
2098 	otp->snd_cwnd_prev = tp->snd_cwnd_prev;
2099 	otp->snd_ssthresh_prev = tp->snd_ssthresh_prev;
2100 	otp->t_badrxtwin = 0;
2101 }
2102 
2103 
2104 static int
2105 tcp_pcblist64 SYSCTL_HANDLER_ARGS
2106 {
2107 #pragma unused(oidp, arg1, arg2)
2108 	int error, i = 0, n, sz;
2109 	struct inpcb **inp_list;
2110 	inp_gen_t gencnt;
2111 	struct xinpgen xig;
2112 
2113 	/*
2114 	 * The process of preparing the TCB list is too time-consuming and
2115 	 * resource-intensive to repeat twice on every request.
2116 	 */
2117 	lck_rw_lock_shared(&tcbinfo.ipi_lock);
2118 	if (req->oldptr == USER_ADDR_NULL) {
2119 		n = tcbinfo.ipi_count;
2120 		req->oldidx = 2 * (sizeof(xig))
2121 		    + (n + n / 8) * sizeof(struct xtcpcb64);
2122 		lck_rw_done(&tcbinfo.ipi_lock);
2123 		return 0;
2124 	}
2125 
2126 	if (req->newptr != USER_ADDR_NULL) {
2127 		lck_rw_done(&tcbinfo.ipi_lock);
2128 		return EPERM;
2129 	}
2130 
2131 	/*
2132 	 * OK, now we're committed to doing something.
2133 	 */
2134 	gencnt = tcbinfo.ipi_gencnt;
2135 	sz = n = tcbinfo.ipi_count;
2136 
2137 	bzero(&xig, sizeof(xig));
2138 	xig.xig_len = sizeof(xig);
2139 	xig.xig_count = n;
2140 	xig.xig_gen = gencnt;
2141 	xig.xig_sogen = so_gencnt;
2142 	error = SYSCTL_OUT(req, &xig, sizeof(xig));
2143 	if (error) {
2144 		lck_rw_done(&tcbinfo.ipi_lock);
2145 		return error;
2146 	}
2147 	/*
2148 	 * We are done if there is no pcb
2149 	 */
2150 	if (n == 0) {
2151 		lck_rw_done(&tcbinfo.ipi_lock);
2152 		return 0;
2153 	}
2154 
2155 	inp_list = kalloc_type(struct inpcb *, n, Z_WAITOK);
2156 	if (inp_list == NULL) {
2157 		lck_rw_done(&tcbinfo.ipi_lock);
2158 		return ENOMEM;
2159 	}
2160 
2161 	n = get_tcp_inp_list(inp_list, n, gencnt);
2162 
2163 	error = 0;
2164 	for (i = 0; i < n; i++) {
2165 		struct xtcpcb64 xt;
2166 		struct inpcb *inp;
2167 
2168 		inp = inp_list[i];
2169 
2170 		if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
2171 			continue;
2172 		}
2173 		socket_lock(inp->inp_socket, 1);
2174 		if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
2175 			socket_unlock(inp->inp_socket, 1);
2176 			continue;
2177 		}
2178 		if (inp->inp_gencnt > gencnt) {
2179 			socket_unlock(inp->inp_socket, 1);
2180 			continue;
2181 		}
2182 
2183 		bzero(&xt, sizeof(xt));
2184 		xt.xt_len = sizeof(xt);
2185 		inpcb_to_xinpcb64(inp, &xt.xt_inpcb);
2186 		xt.xt_inpcb.inp_ppcb =
2187 		    (uint64_t)VM_KERNEL_ADDRPERM(inp->inp_ppcb);
2188 		if (inp->inp_ppcb != NULL) {
2189 			tcpcb_to_xtcpcb64((struct tcpcb *)inp->inp_ppcb,
2190 			    &xt);
2191 		}
2192 		if (inp->inp_socket) {
2193 			sotoxsocket64(inp->inp_socket,
2194 			    &xt.xt_inpcb.xi_socket);
2195 		}
2196 
2197 		socket_unlock(inp->inp_socket, 1);
2198 
2199 		error = SYSCTL_OUT(req, &xt, sizeof(xt));
2200 	}
2201 	if (!error) {
2202 		/*
2203 		 * Give the user an updated idea of our state.
2204 		 * If the generation differs from what we told
2205 		 * her before, she knows that something happened
2206 		 * while we were processing this request, and it
2207 		 * might be necessary to retry.
2208 		 */
2209 		bzero(&xig, sizeof(xig));
2210 		xig.xig_len = sizeof(xig);
2211 		xig.xig_gen = tcbinfo.ipi_gencnt;
2212 		xig.xig_sogen = so_gencnt;
2213 		xig.xig_count = tcbinfo.ipi_count;
2214 		error = SYSCTL_OUT(req, &xig, sizeof(xig));
2215 	}
2216 
2217 	lck_rw_done(&tcbinfo.ipi_lock);
2218 	kfree_type(struct inpcb *, sz, inp_list);
2219 	return error;
2220 }
2221 
2222 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, pcblist64,
2223     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
2224     tcp_pcblist64, "S,xtcpcb64", "List of active TCP connections");
2225 
2226 #endif /* XNU_TARGET_OS_OSX */
2227 
2228 static int
2229 tcp_pcblist_n SYSCTL_HANDLER_ARGS
2230 {
2231 #pragma unused(oidp, arg1, arg2)
2232 	int error = 0;
2233 
2234 	error = get_pcblist_n(IPPROTO_TCP, req, &tcbinfo);
2235 
2236 	return error;
2237 }
2238 
2239 
2240 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, pcblist_n,
2241     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
2242     tcp_pcblist_n, "S,xtcpcb_n", "List of active TCP connections");
2243 
2244 static int
2245 tcp_progress_indicators SYSCTL_HANDLER_ARGS
2246 {
2247 #pragma unused(oidp, arg1, arg2)
2248 
2249 	return ntstat_tcp_progress_indicators(req);
2250 }
2251 
2252 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, progress,
2253     CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_ANYBODY, 0, 0,
2254     tcp_progress_indicators, "S", "Various items that indicate the current state of progress on the link");
2255 
2256 
2257 static int
2258 tcp_progress_probe_enable SYSCTL_HANDLER_ARGS
2259 {
2260 #pragma unused(oidp, arg1, arg2)
2261 
2262 	return ntstat_tcp_progress_enable(req);
2263 }
2264 
2265 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, progress_enable,
2266     CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_LOCKED | CTLFLAG_ANYBODY, 0, 0,
2267     tcp_progress_probe_enable, "S", "Enable/disable TCP keepalive probing on the specified link(s)");
2268 
2269 
2270 __private_extern__ void
tcp_get_ports_used(ifnet_t ifp,int protocol,uint32_t flags,bitstr_t * bitfield)2271 tcp_get_ports_used(ifnet_t ifp, int protocol, uint32_t flags,
2272     bitstr_t *bitfield)
2273 {
2274 	inpcb_get_ports_used(ifp, protocol, flags, bitfield,
2275 	    &tcbinfo);
2276 }
2277 
2278 __private_extern__ uint32_t
tcp_count_opportunistic(unsigned int ifindex,u_int32_t flags)2279 tcp_count_opportunistic(unsigned int ifindex, u_int32_t flags)
2280 {
2281 	return inpcb_count_opportunistic(ifindex, &tcbinfo, flags);
2282 }
2283 
2284 __private_extern__ uint32_t
tcp_find_anypcb_byaddr(struct ifaddr * ifa)2285 tcp_find_anypcb_byaddr(struct ifaddr *ifa)
2286 {
2287 #if SKYWALK
2288 	if (netns_is_enabled()) {
2289 		return netns_find_anyres_byaddr(ifa, IPPROTO_TCP);
2290 	} else
2291 #endif /* SKYWALK */
2292 	return inpcb_find_anypcb_byaddr(ifa, &tcbinfo);
2293 }
2294 
2295 static void
tcp_handle_msgsize(struct ip * ip,struct inpcb * inp)2296 tcp_handle_msgsize(struct ip *ip, struct inpcb *inp)
2297 {
2298 	struct rtentry *rt = NULL;
2299 	u_short ifscope = IFSCOPE_NONE;
2300 	int mtu;
2301 	struct sockaddr_in icmpsrc = {
2302 		.sin_len = sizeof(struct sockaddr_in),
2303 		.sin_family = AF_INET, .sin_port = 0, .sin_addr = { .s_addr = 0 },
2304 		.sin_zero = { 0, 0, 0, 0, 0, 0, 0, 0 }
2305 	};
2306 	struct icmp *icp = NULL;
2307 
2308 	icp = (struct icmp *)(void *)
2309 	    ((caddr_t)ip - offsetof(struct icmp, icmp_ip));
2310 
2311 	icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
2312 
2313 	/*
2314 	 * MTU discovery:
2315 	 * If we got a needfrag and there is a host route to the
2316 	 * original destination, and the MTU is not locked, then
2317 	 * set the MTU in the route to the suggested new value
2318 	 * (if given) and then notify as usual.  The ULPs will
2319 	 * notice that the MTU has changed and adapt accordingly.
2320 	 * If no new MTU was suggested, then we guess a new one
2321 	 * less than the current value.  If the new MTU is
2322 	 * unreasonably small (defined by sysctl tcp_minmss), then
2323 	 * we reset the MTU to the interface value and enable the
2324 	 * lock bit, indicating that we are no longer doing MTU
2325 	 * discovery.
2326 	 */
2327 	if (ROUTE_UNUSABLE(&(inp->inp_route)) == false) {
2328 		rt = inp->inp_route.ro_rt;
2329 	}
2330 
2331 	/*
2332 	 * icmp6_mtudisc_update scopes the routing lookup
2333 	 * to the incoming interface (delivered from mbuf
2334 	 * packet header.
2335 	 * That is mostly ok but for asymmetric networks
2336 	 * that may be an issue.
2337 	 * Frag needed OR Packet too big really communicates
2338 	 * MTU for the out data path.
2339 	 * Take the interface scope from cached route or
2340 	 * the last outgoing interface from inp
2341 	 */
2342 	if (rt != NULL) {
2343 		ifscope = (rt->rt_ifp != NULL) ?
2344 		    rt->rt_ifp->if_index : IFSCOPE_NONE;
2345 	} else {
2346 		ifscope = (inp->inp_last_outifp != NULL) ?
2347 		    inp->inp_last_outifp->if_index : IFSCOPE_NONE;
2348 	}
2349 
2350 	if ((rt == NULL) ||
2351 	    !(rt->rt_flags & RTF_HOST) ||
2352 	    (rt->rt_flags & (RTF_CLONING | RTF_PRCLONING))) {
2353 		rt = rtalloc1_scoped((struct sockaddr *)&icmpsrc, 0,
2354 		    RTF_CLONING | RTF_PRCLONING, ifscope);
2355 	} else if (rt) {
2356 		RT_LOCK(rt);
2357 		rtref(rt);
2358 		RT_UNLOCK(rt);
2359 	}
2360 
2361 	if (rt != NULL) {
2362 		RT_LOCK(rt);
2363 		if ((rt->rt_flags & RTF_HOST) &&
2364 		    !(rt->rt_rmx.rmx_locks & RTV_MTU)) {
2365 			mtu = ntohs(icp->icmp_nextmtu);
2366 			/*
2367 			 * XXX Stock BSD has changed the following
2368 			 * to compare with icp->icmp_ip.ip_len
2369 			 * to converge faster when sent packet
2370 			 * < route's MTU. We may want to adopt
2371 			 * that change.
2372 			 */
2373 			if (mtu == 0) {
2374 				mtu = ip_next_mtu(rt->rt_rmx.
2375 				    rmx_mtu, 1);
2376 			}
2377 #if DEBUG_MTUDISC
2378 			printf("MTU for %s reduced to %d\n",
2379 			    inet_ntop(AF_INET,
2380 			    &icmpsrc.sin_addr, ipv4str,
2381 			    sizeof(ipv4str)), mtu);
2382 #endif
2383 			if (mtu < max(296, (tcp_minmss +
2384 			    sizeof(struct tcpiphdr)))) {
2385 				rt->rt_rmx.rmx_locks |= RTV_MTU;
2386 			} else if (rt->rt_rmx.rmx_mtu > mtu) {
2387 				rt->rt_rmx.rmx_mtu = mtu;
2388 			}
2389 		}
2390 		RT_UNLOCK(rt);
2391 		rtfree(rt);
2392 	}
2393 }
2394 
2395 void
tcp_ctlinput(int cmd,struct sockaddr * sa,void * vip,__unused struct ifnet * ifp)2396 tcp_ctlinput(int cmd, struct sockaddr *sa, void *vip, __unused struct ifnet *ifp)
2397 {
2398 	tcp_seq icmp_tcp_seq;
2399 	struct ipctlparam *ctl_param = vip;
2400 	struct ip *ip = NULL;
2401 	struct mbuf *m = NULL;
2402 	struct in_addr faddr;
2403 	struct inpcb *inp;
2404 	struct tcpcb *tp;
2405 	struct tcphdr *th;
2406 	struct icmp *icp;
2407 	size_t off;
2408 #if SKYWALK
2409 	union sockaddr_in_4_6 sock_laddr;
2410 	struct protoctl_ev_val prctl_ev_val;
2411 #endif /* SKYWALK */
2412 	void (*notify)(struct inpcb *, int) = tcp_notify;
2413 
2414 	if (ctl_param != NULL) {
2415 		ip = ctl_param->ipc_icmp_ip;
2416 		icp = ctl_param->ipc_icmp;
2417 		m = ctl_param->ipc_m;
2418 		off = ctl_param->ipc_off;
2419 	} else {
2420 		ip = NULL;
2421 		icp = NULL;
2422 		m = NULL;
2423 		off = 0;
2424 	}
2425 
2426 	faddr = ((struct sockaddr_in *)(void *)sa)->sin_addr;
2427 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY) {
2428 		return;
2429 	}
2430 
2431 	if ((unsigned)cmd >= PRC_NCMDS) {
2432 		return;
2433 	}
2434 
2435 	/* Source quench is deprecated */
2436 	if (cmd == PRC_QUENCH) {
2437 		return;
2438 	}
2439 
2440 	if (cmd == PRC_MSGSIZE) {
2441 		notify = tcp_mtudisc;
2442 	} else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
2443 	    cmd == PRC_UNREACH_PORT || cmd == PRC_UNREACH_PROTOCOL ||
2444 	    cmd == PRC_TIMXCEED_INTRANS) && ip) {
2445 		notify = tcp_drop_syn_sent;
2446 	}
2447 	/*
2448 	 * Hostdead is ugly because it goes linearly through all PCBs.
2449 	 * XXX: We never get this from ICMP, otherwise it makes an
2450 	 * excellent DoS attack on machines with many connections.
2451 	 */
2452 	else if (cmd == PRC_HOSTDEAD) {
2453 		ip = NULL;
2454 	} else if (inetctlerrmap[cmd] == 0 && !PRC_IS_REDIRECT(cmd)) {
2455 		return;
2456 	}
2457 
2458 #if SKYWALK
2459 	bzero(&prctl_ev_val, sizeof(prctl_ev_val));
2460 	bzero(&sock_laddr, sizeof(sock_laddr));
2461 #endif /* SKYWALK */
2462 
2463 	if (ip == NULL) {
2464 		in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify);
2465 #if SKYWALK
2466 		protoctl_event_enqueue_nwk_wq_entry(ifp, NULL,
2467 		    sa, 0, 0, IPPROTO_TCP, cmd, NULL);
2468 #endif /* SKYWALK */
2469 		return;
2470 	}
2471 
2472 	/* Check if we can safely get the sport, dport and the sequence number from the tcp header. */
2473 	if (m == NULL ||
2474 	    (m->m_len < off + (sizeof(unsigned short) + sizeof(unsigned short) + sizeof(tcp_seq)))) {
2475 		/* Insufficient length */
2476 		return;
2477 	}
2478 
2479 	th = (struct tcphdr*)(void*)(mtod(m, uint8_t*) + off);
2480 	icmp_tcp_seq = ntohl(th->th_seq);
2481 
2482 	inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
2483 	    ip->ip_src, th->th_sport, 0, NULL);
2484 
2485 	if (inp == NULL ||
2486 	    inp->inp_socket == NULL) {
2487 #if SKYWALK
2488 		if (cmd == PRC_MSGSIZE) {
2489 			prctl_ev_val.val = ntohs(icp->icmp_nextmtu);
2490 		}
2491 		prctl_ev_val.tcp_seq_number = icmp_tcp_seq;
2492 
2493 		sock_laddr.sin.sin_family = AF_INET;
2494 		sock_laddr.sin.sin_len = sizeof(sock_laddr.sin);
2495 		sock_laddr.sin.sin_addr = ip->ip_src;
2496 
2497 		protoctl_event_enqueue_nwk_wq_entry(ifp,
2498 		    (struct sockaddr *)&sock_laddr, sa,
2499 		    th->th_sport, th->th_dport, IPPROTO_TCP,
2500 		    cmd, &prctl_ev_val);
2501 #endif /* SKYWALK */
2502 		return;
2503 	}
2504 
2505 	socket_lock(inp->inp_socket, 1);
2506 	if (in_pcb_checkstate(inp, WNT_RELEASE, 1) ==
2507 	    WNT_STOPUSING) {
2508 		socket_unlock(inp->inp_socket, 1);
2509 		return;
2510 	}
2511 
2512 	if (PRC_IS_REDIRECT(cmd)) {
2513 		/* signal EHOSTDOWN, as it flushes the cached route */
2514 		(*notify)(inp, EHOSTDOWN);
2515 	} else {
2516 		tp = intotcpcb(inp);
2517 		if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) &&
2518 		    SEQ_LT(icmp_tcp_seq, tp->snd_max)) {
2519 			if (cmd == PRC_MSGSIZE) {
2520 				tcp_handle_msgsize(ip, inp);
2521 			}
2522 
2523 			(*notify)(inp, inetctlerrmap[cmd]);
2524 		}
2525 	}
2526 	socket_unlock(inp->inp_socket, 1);
2527 }
2528 
2529 void
tcp6_ctlinput(int cmd,struct sockaddr * sa,void * d,__unused struct ifnet * ifp)2530 tcp6_ctlinput(int cmd, struct sockaddr *sa, void *d, __unused struct ifnet *ifp)
2531 {
2532 	tcp_seq icmp_tcp_seq;
2533 	struct in6_addr *dst;
2534 	void (*notify)(struct inpcb *, int) = tcp_notify;
2535 	struct ip6_hdr *ip6;
2536 	struct mbuf *m;
2537 	struct inpcb *inp;
2538 	struct tcpcb *tp;
2539 	struct icmp6_hdr *icmp6;
2540 	struct ip6ctlparam *ip6cp = NULL;
2541 	const struct sockaddr_in6 *sa6_src = NULL;
2542 	unsigned int mtu;
2543 	unsigned int off;
2544 
2545 	struct tcp_ports {
2546 		uint16_t th_sport;
2547 		uint16_t th_dport;
2548 	} t_ports;
2549 #if SKYWALK
2550 	union sockaddr_in_4_6 sock_laddr;
2551 	struct protoctl_ev_val prctl_ev_val;
2552 #endif /* SKYWALK */
2553 
2554 	if (sa->sa_family != AF_INET6 ||
2555 	    sa->sa_len != sizeof(struct sockaddr_in6)) {
2556 		return;
2557 	}
2558 
2559 	/* Source quench is deprecated */
2560 	if (cmd == PRC_QUENCH) {
2561 		return;
2562 	}
2563 
2564 	if ((unsigned)cmd >= PRC_NCMDS) {
2565 		return;
2566 	}
2567 
2568 	/* if the parameter is from icmp6, decode it. */
2569 	if (d != NULL) {
2570 		ip6cp = (struct ip6ctlparam *)d;
2571 		icmp6 = ip6cp->ip6c_icmp6;
2572 		m = ip6cp->ip6c_m;
2573 		ip6 = ip6cp->ip6c_ip6;
2574 		off = ip6cp->ip6c_off;
2575 		sa6_src = ip6cp->ip6c_src;
2576 		dst = ip6cp->ip6c_finaldst;
2577 	} else {
2578 		m = NULL;
2579 		ip6 = NULL;
2580 		off = 0;        /* fool gcc */
2581 		sa6_src = &sa6_any;
2582 		dst = NULL;
2583 	}
2584 
2585 	if (cmd == PRC_MSGSIZE) {
2586 		notify = tcp_mtudisc;
2587 	} else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
2588 	    cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) &&
2589 	    ip6 != NULL) {
2590 		notify = tcp_drop_syn_sent;
2591 	}
2592 	/*
2593 	 * Hostdead is ugly because it goes linearly through all PCBs.
2594 	 * XXX: We never get this from ICMP, otherwise it makes an
2595 	 * excellent DoS attack on machines with many connections.
2596 	 */
2597 	else if (cmd == PRC_HOSTDEAD) {
2598 		ip6 = NULL;
2599 	} else if (inet6ctlerrmap[cmd] == 0 && !PRC_IS_REDIRECT(cmd)) {
2600 		return;
2601 	}
2602 
2603 #if SKYWALK
2604 	bzero(&prctl_ev_val, sizeof(prctl_ev_val));
2605 	bzero(&sock_laddr, sizeof(sock_laddr));
2606 #endif /* SKYWALK */
2607 
2608 	if (ip6 == NULL) {
2609 		in6_pcbnotify(&tcbinfo, sa, 0, (struct sockaddr *)(size_t)sa6_src,
2610 		    0, cmd, NULL, notify);
2611 #if SKYWALK
2612 		protoctl_event_enqueue_nwk_wq_entry(ifp, NULL, sa,
2613 		    0, 0, IPPROTO_TCP, cmd, NULL);
2614 #endif /* SKYWALK */
2615 		return;
2616 	}
2617 
2618 	/* Check if we can safely get the ports from the tcp hdr */
2619 	if (m == NULL ||
2620 	    (m->m_pkthdr.len <
2621 	    (int32_t) (off + sizeof(struct tcp_ports)))) {
2622 		return;
2623 	}
2624 	bzero(&t_ports, sizeof(struct tcp_ports));
2625 	m_copydata(m, off, sizeof(struct tcp_ports), (caddr_t)&t_ports);
2626 
2627 	off += sizeof(struct tcp_ports);
2628 	if (m->m_pkthdr.len < (int32_t) (off + sizeof(tcp_seq))) {
2629 		return;
2630 	}
2631 	m_copydata(m, off, sizeof(tcp_seq), (caddr_t)&icmp_tcp_seq);
2632 	icmp_tcp_seq = ntohl(icmp_tcp_seq);
2633 
2634 	if (cmd == PRC_MSGSIZE) {
2635 		mtu = ntohl(icmp6->icmp6_mtu);
2636 		/*
2637 		 * If no alternative MTU was proposed, or the proposed
2638 		 * MTU was too small, set to the min.
2639 		 */
2640 		if (mtu < IPV6_MMTU) {
2641 			mtu = IPV6_MMTU - 8;
2642 		}
2643 	}
2644 
2645 	inp = in6_pcblookup_hash(&tcbinfo, &ip6->ip6_dst, t_ports.th_dport, ip6_input_getdstifscope(m),
2646 	    &ip6->ip6_src, t_ports.th_sport, ip6_input_getsrcifscope(m), 0, NULL);
2647 
2648 	if (inp == NULL ||
2649 	    inp->inp_socket == NULL) {
2650 #if SKYWALK
2651 		if (cmd == PRC_MSGSIZE) {
2652 			prctl_ev_val.val = mtu;
2653 		}
2654 		prctl_ev_val.tcp_seq_number = icmp_tcp_seq;
2655 
2656 		sock_laddr.sin6.sin6_family = AF_INET6;
2657 		sock_laddr.sin6.sin6_len = sizeof(sock_laddr.sin6);
2658 		sock_laddr.sin6.sin6_addr = ip6->ip6_src;
2659 
2660 		protoctl_event_enqueue_nwk_wq_entry(ifp,
2661 		    (struct sockaddr *)&sock_laddr, sa,
2662 		    t_ports.th_sport, t_ports.th_dport, IPPROTO_TCP,
2663 		    cmd, &prctl_ev_val);
2664 #endif /* SKYWALK */
2665 		return;
2666 	}
2667 
2668 	socket_lock(inp->inp_socket, 1);
2669 	if (in_pcb_checkstate(inp, WNT_RELEASE, 1) ==
2670 	    WNT_STOPUSING) {
2671 		socket_unlock(inp->inp_socket, 1);
2672 		return;
2673 	}
2674 
2675 	if (PRC_IS_REDIRECT(cmd)) {
2676 		/* signal EHOSTDOWN, as it flushes the cached route */
2677 		(*notify)(inp, EHOSTDOWN);
2678 	} else {
2679 		tp = intotcpcb(inp);
2680 		if (SEQ_GEQ(icmp_tcp_seq, tp->snd_una) &&
2681 		    SEQ_LT(icmp_tcp_seq, tp->snd_max)) {
2682 			if (cmd == PRC_MSGSIZE) {
2683 				/*
2684 				 * Only process the offered MTU if it
2685 				 * is smaller than the current one.
2686 				 */
2687 				if (mtu < tp->t_maxseg +
2688 				    (sizeof(struct tcphdr) + sizeof(struct ip6_hdr))) {
2689 					(*notify)(inp, inetctlerrmap[cmd]);
2690 				}
2691 			} else {
2692 				(*notify)(inp, inetctlerrmap[cmd]);
2693 			}
2694 		}
2695 	}
2696 	socket_unlock(inp->inp_socket, 1);
2697 }
2698 
2699 
2700 /*
2701  * Following is where TCP initial sequence number generation occurs.
2702  *
2703  * There are two places where we must use initial sequence numbers:
2704  * 1.  In SYN-ACK packets.
2705  * 2.  In SYN packets.
2706  *
2707  * The ISNs in SYN-ACK packets have no monotonicity requirement,
2708  * and should be as unpredictable as possible to avoid the possibility
2709  * of spoofing and/or connection hijacking.  To satisfy this
2710  * requirement, SYN-ACK ISNs are generated via the arc4random()
2711  * function.  If exact RFC 1948 compliance is requested via sysctl,
2712  * these ISNs will be generated just like those in SYN packets.
2713  *
2714  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
2715  * depends on this property.  In addition, these ISNs should be
2716  * unguessable so as to prevent connection hijacking.  To satisfy
2717  * the requirements of this situation, the algorithm outlined in
2718  * RFC 1948 is used to generate sequence numbers.
2719  *
2720  * For more information on the theory of operation, please see
2721  * RFC 1948.
2722  *
2723  * Implementation details:
2724  *
2725  * Time is based off the system timer, and is corrected so that it
2726  * increases by one megabyte per second.  This allows for proper
2727  * recycling on high speed LANs while still leaving over an hour
2728  * before rollover.
2729  *
2730  * Two sysctls control the generation of ISNs:
2731  *
2732  * net.inet.tcp.isn_reseed_interval controls the number of seconds
2733  * between seeding of isn_secret.  This is normally set to zero,
2734  * as reseeding should not be necessary.
2735  *
2736  * net.inet.tcp.strict_rfc1948 controls whether RFC 1948 is followed
2737  * strictly.  When strict compliance is requested, reseeding is
2738  * disabled and SYN-ACKs will be generated in the same manner as
2739  * SYNs.  Strict mode is disabled by default.
2740  *
2741  */
2742 
2743 #define ISN_BYTES_PER_SECOND 1048576
2744 
2745 tcp_seq
tcp_new_isn(struct tcpcb * tp)2746 tcp_new_isn(struct tcpcb *tp)
2747 {
2748 	u_int32_t md5_buffer[4];
2749 	tcp_seq new_isn;
2750 	struct timeval timenow;
2751 	u_char isn_secret[32];
2752 	long isn_last_reseed = 0;
2753 	MD5_CTX isn_ctx;
2754 
2755 	/* Use arc4random for SYN-ACKs when not in exact RFC1948 mode. */
2756 	if (((tp->t_state == TCPS_LISTEN) || (tp->t_state == TCPS_TIME_WAIT)) &&
2757 	    tcp_strict_rfc1948 == 0)
2758 #ifdef __APPLE__
2759 	{ return RandomULong(); }
2760 #else
2761 	{ return arc4random(); }
2762 #endif
2763 	getmicrotime(&timenow);
2764 
2765 	/* Seed if this is the first use, reseed if requested. */
2766 	if ((isn_last_reseed == 0) ||
2767 	    ((tcp_strict_rfc1948 == 0) && (tcp_isn_reseed_interval > 0) &&
2768 	    (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval * hz)
2769 	    < (u_int)timenow.tv_sec))) {
2770 #ifdef __APPLE__
2771 		read_frandom(&isn_secret, sizeof(isn_secret));
2772 #else
2773 		read_random_unlimited(&isn_secret, sizeof(isn_secret));
2774 #endif
2775 		isn_last_reseed = timenow.tv_sec;
2776 	}
2777 
2778 	/* Compute the md5 hash and return the ISN. */
2779 	MD5Init(&isn_ctx);
2780 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport,
2781 	    sizeof(u_short));
2782 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport,
2783 	    sizeof(u_short));
2784 	if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
2785 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
2786 		    sizeof(struct in6_addr));
2787 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
2788 		    sizeof(struct in6_addr));
2789 	} else {
2790 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
2791 		    sizeof(struct in_addr));
2792 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
2793 		    sizeof(struct in_addr));
2794 	}
2795 	MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
2796 	MD5Final((u_char *) &md5_buffer, &isn_ctx);
2797 	new_isn = (tcp_seq) md5_buffer[0];
2798 	new_isn += timenow.tv_sec * (ISN_BYTES_PER_SECOND / hz);
2799 	return new_isn;
2800 }
2801 
2802 
2803 /*
2804  * When a specific ICMP unreachable message is received and the
2805  * connection state is SYN-SENT, drop the connection.  This behavior
2806  * is controlled by the icmp_may_rst sysctl.
2807  */
2808 void
tcp_drop_syn_sent(struct inpcb * inp,int errno)2809 tcp_drop_syn_sent(struct inpcb *inp, int errno)
2810 {
2811 	struct tcpcb *tp = intotcpcb(inp);
2812 
2813 	if (tp && tp->t_state == TCPS_SYN_SENT) {
2814 		tcp_drop(tp, errno);
2815 	}
2816 }
2817 
2818 /*
2819  * When `need fragmentation' ICMP is received, update our idea of the MSS
2820  * based on the new value in the route.  Also nudge TCP to send something,
2821  * since we know the packet we just sent was dropped.
2822  * This duplicates some code in the tcp_mss() function in tcp_input.c.
2823  */
2824 void
tcp_mtudisc(struct inpcb * inp,__unused int errno)2825 tcp_mtudisc(struct inpcb *inp, __unused int errno)
2826 {
2827 	struct tcpcb *tp = intotcpcb(inp);
2828 	struct rtentry *rt;
2829 	struct socket *so = inp->inp_socket;
2830 	int mss;
2831 	u_int32_t mtu;
2832 	u_int32_t protoHdrOverhead = sizeof(struct tcpiphdr);
2833 	int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
2834 
2835 	/*
2836 	 * Nothing left to send after the socket is defunct or TCP is in the closed state
2837 	 */
2838 	if ((so->so_state & SS_DEFUNCT) || (tp != NULL && tp->t_state == TCPS_CLOSED)) {
2839 		return;
2840 	}
2841 
2842 	if (isipv6) {
2843 		protoHdrOverhead = sizeof(struct ip6_hdr) +
2844 		    sizeof(struct tcphdr);
2845 	}
2846 
2847 	if (tp != NULL) {
2848 		if (isipv6) {
2849 			rt = tcp_rtlookup6(inp, IFSCOPE_NONE);
2850 		} else {
2851 			rt = tcp_rtlookup(inp, IFSCOPE_NONE);
2852 		}
2853 		if (!rt || !rt->rt_rmx.rmx_mtu) {
2854 			tp->t_maxopd = tp->t_maxseg =
2855 			    isipv6 ? tcp_v6mssdflt :
2856 			    tcp_mssdflt;
2857 
2858 			/* Route locked during lookup above */
2859 			if (rt != NULL) {
2860 				RT_UNLOCK(rt);
2861 			}
2862 			return;
2863 		}
2864 		mtu = rt->rt_rmx.rmx_mtu;
2865 
2866 		/* Route locked during lookup above */
2867 		RT_UNLOCK(rt);
2868 
2869 #if NECP
2870 		// Adjust MTU if necessary.
2871 		mtu = necp_socket_get_effective_mtu(inp, mtu);
2872 #endif /* NECP */
2873 		mss = mtu - protoHdrOverhead;
2874 
2875 		if (tp->t_maxopd) {
2876 			mss = min(mss, tp->t_maxopd);
2877 		}
2878 		/*
2879 		 * XXX - The above conditional probably violates the TCP
2880 		 * spec.  The problem is that, since we don't know the
2881 		 * other end's MSS, we are supposed to use a conservative
2882 		 * default.  But, if we do that, then MTU discovery will
2883 		 * never actually take place, because the conservative
2884 		 * default is much less than the MTUs typically seen
2885 		 * on the Internet today.  For the moment, we'll sweep
2886 		 * this under the carpet.
2887 		 *
2888 		 * The conservative default might not actually be a problem
2889 		 * if the only case this occurs is when sending an initial
2890 		 * SYN with options and data to a host we've never talked
2891 		 * to before.  Then, they will reply with an MSS value which
2892 		 * will get recorded and the new parameters should get
2893 		 * recomputed.  For Further Study.
2894 		 */
2895 		if (tp->t_maxopd <= mss) {
2896 			return;
2897 		}
2898 		tp->t_maxopd = mss;
2899 
2900 		if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
2901 		    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP) {
2902 			mss -= TCPOLEN_TSTAMP_APPA;
2903 		}
2904 
2905 #if MPTCP
2906 		mss -= mptcp_adj_mss(tp, TRUE);
2907 #endif
2908 		if (so->so_snd.sb_hiwat < mss) {
2909 			mss = so->so_snd.sb_hiwat;
2910 		}
2911 
2912 		tp->t_maxseg = mss;
2913 
2914 		ASSERT(tp->t_maxseg);
2915 
2916 		/*
2917 		 * Reset the slow-start flight size as it may depends on the
2918 		 * new MSS
2919 		 */
2920 		if (CC_ALGO(tp)->cwnd_init != NULL) {
2921 			CC_ALGO(tp)->cwnd_init(tp);
2922 		}
2923 
2924 		if (TCP_USE_RLEDBAT(tp, so) && tcp_cc_rledbat.rwnd_init != NULL) {
2925 			tcp_cc_rledbat.rwnd_init(tp);
2926 		}
2927 
2928 		tcpstat.tcps_mturesent++;
2929 		tp->t_rtttime = 0;
2930 		tp->snd_nxt = tp->snd_una;
2931 		tcp_output(tp);
2932 	}
2933 }
2934 
2935 /*
2936  * Look-up the routing entry to the peer of this inpcb.  If no route
2937  * is found and it cannot be allocated the return NULL.  This routine
2938  * is called by TCP routines that access the rmx structure and by tcp_mss
2939  * to get the interface MTU.  If a route is found, this routine will
2940  * hold the rtentry lock; the caller is responsible for unlocking.
2941  */
2942 struct rtentry *
tcp_rtlookup(struct inpcb * inp,unsigned int input_ifscope)2943 tcp_rtlookup(struct inpcb *inp, unsigned int input_ifscope)
2944 {
2945 	struct route *ro;
2946 	struct rtentry *rt;
2947 	struct tcpcb *tp;
2948 
2949 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2950 
2951 	ro = &inp->inp_route;
2952 	if ((rt = ro->ro_rt) != NULL) {
2953 		RT_LOCK(rt);
2954 	}
2955 
2956 	if (ROUTE_UNUSABLE(ro)) {
2957 		if (rt != NULL) {
2958 			RT_UNLOCK(rt);
2959 			rt = NULL;
2960 		}
2961 		ROUTE_RELEASE(ro);
2962 		/* No route yet, so try to acquire one */
2963 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
2964 			unsigned int ifscope;
2965 
2966 			ro->ro_dst.sa_family = AF_INET;
2967 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
2968 			((struct sockaddr_in *)(void *)&ro->ro_dst)->sin_addr =
2969 			    inp->inp_faddr;
2970 
2971 			/*
2972 			 * If the socket was bound to an interface, then
2973 			 * the bound-to-interface takes precedence over
2974 			 * the inbound interface passed in by the caller
2975 			 * (if we get here as part of the output path then
2976 			 * input_ifscope is IFSCOPE_NONE).
2977 			 */
2978 			ifscope = (inp->inp_flags & INP_BOUND_IF) ?
2979 			    inp->inp_boundifp->if_index : input_ifscope;
2980 
2981 			rtalloc_scoped(ro, ifscope);
2982 			if ((rt = ro->ro_rt) != NULL) {
2983 				RT_LOCK(rt);
2984 			}
2985 		}
2986 	}
2987 	if (rt != NULL) {
2988 		RT_LOCK_ASSERT_HELD(rt);
2989 	}
2990 
2991 	/*
2992 	 * Update MTU discovery determination. Don't do it if:
2993 	 *	1) it is disabled via the sysctl
2994 	 *	2) the route isn't up
2995 	 *	3) the MTU is locked (if it is, then discovery has been
2996 	 *	   disabled)
2997 	 */
2998 
2999 	tp = intotcpcb(inp);
3000 
3001 	if (!path_mtu_discovery || ((rt != NULL) &&
3002 	    (!(rt->rt_flags & RTF_UP) || (rt->rt_rmx.rmx_locks & RTV_MTU)))) {
3003 		tp->t_flags &= ~TF_PMTUD;
3004 	} else {
3005 		tp->t_flags |= TF_PMTUD;
3006 	}
3007 
3008 	if (rt != NULL && rt->rt_ifp != NULL) {
3009 		somultipages(inp->inp_socket,
3010 		    (rt->rt_ifp->if_hwassist & IFNET_MULTIPAGES));
3011 		tcp_set_tso(tp, rt->rt_ifp);
3012 		soif2kcl(inp->inp_socket,
3013 		    (rt->rt_ifp->if_eflags & IFEF_2KCL));
3014 		tcp_set_ecn(tp, rt->rt_ifp);
3015 		if (inp->inp_last_outifp == NULL) {
3016 			inp->inp_last_outifp = rt->rt_ifp;
3017 #if SKYWALK
3018 			if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
3019 				netns_set_ifnet(&inp->inp_netns_token,
3020 				    inp->inp_last_outifp);
3021 			}
3022 #endif /* SKYWALK */
3023 		}
3024 	}
3025 
3026 	/* Note if the peer is local */
3027 	if (rt != NULL && !(rt->rt_ifp->if_flags & IFF_POINTOPOINT) &&
3028 	    (rt->rt_gateway->sa_family == AF_LINK ||
3029 	    rt->rt_ifp->if_flags & IFF_LOOPBACK ||
3030 	    in_localaddr(inp->inp_faddr))) {
3031 		tp->t_flags |= TF_LOCAL;
3032 	}
3033 
3034 	/*
3035 	 * Caller needs to call RT_UNLOCK(rt).
3036 	 */
3037 	return rt;
3038 }
3039 
3040 struct rtentry *
tcp_rtlookup6(struct inpcb * inp,unsigned int input_ifscope)3041 tcp_rtlookup6(struct inpcb *inp, unsigned int input_ifscope)
3042 {
3043 	struct route_in6 *ro6;
3044 	struct rtentry *rt;
3045 	struct tcpcb *tp;
3046 
3047 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
3048 
3049 	ro6 = &inp->in6p_route;
3050 	if ((rt = ro6->ro_rt) != NULL) {
3051 		RT_LOCK(rt);
3052 	}
3053 
3054 	if (ROUTE_UNUSABLE(ro6)) {
3055 		if (rt != NULL) {
3056 			RT_UNLOCK(rt);
3057 			rt = NULL;
3058 		}
3059 		ROUTE_RELEASE(ro6);
3060 		/* No route yet, so try to acquire one */
3061 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
3062 			struct sockaddr_in6 *dst6;
3063 			unsigned int ifscope;
3064 
3065 			dst6 = (struct sockaddr_in6 *)&ro6->ro_dst;
3066 			dst6->sin6_family = AF_INET6;
3067 			dst6->sin6_len = sizeof(*dst6);
3068 			dst6->sin6_addr = inp->in6p_faddr;
3069 
3070 			/*
3071 			 * If the socket was bound to an interface, then
3072 			 * the bound-to-interface takes precedence over
3073 			 * the inbound interface passed in by the caller
3074 			 * (if we get here as part of the output path then
3075 			 * input_ifscope is IFSCOPE_NONE).
3076 			 */
3077 			ifscope = (inp->inp_flags & INP_BOUND_IF) ?
3078 			    inp->inp_boundifp->if_index : input_ifscope;
3079 
3080 			rtalloc_scoped((struct route *)ro6, ifscope);
3081 			if ((rt = ro6->ro_rt) != NULL) {
3082 				RT_LOCK(rt);
3083 			}
3084 		}
3085 	}
3086 	if (rt != NULL) {
3087 		RT_LOCK_ASSERT_HELD(rt);
3088 	}
3089 
3090 	/*
3091 	 * Update path MTU Discovery determination
3092 	 * while looking up the route:
3093 	 *  1) we have a valid route to the destination
3094 	 *  2) the MTU is not locked (if it is, then discovery has been
3095 	 *    disabled)
3096 	 */
3097 
3098 
3099 	tp = intotcpcb(inp);
3100 
3101 	/*
3102 	 * Update MTU discovery determination. Don't do it if:
3103 	 *	1) it is disabled via the sysctl
3104 	 *	2) the route isn't up
3105 	 *	3) the MTU is locked (if it is, then discovery has been
3106 	 *	   disabled)
3107 	 */
3108 
3109 	if (!path_mtu_discovery || ((rt != NULL) &&
3110 	    (!(rt->rt_flags & RTF_UP) || (rt->rt_rmx.rmx_locks & RTV_MTU)))) {
3111 		tp->t_flags &= ~TF_PMTUD;
3112 	} else {
3113 		tp->t_flags |= TF_PMTUD;
3114 	}
3115 
3116 	if (rt != NULL && rt->rt_ifp != NULL) {
3117 		somultipages(inp->inp_socket,
3118 		    (rt->rt_ifp->if_hwassist & IFNET_MULTIPAGES));
3119 		tcp_set_tso(tp, rt->rt_ifp);
3120 		soif2kcl(inp->inp_socket,
3121 		    (rt->rt_ifp->if_eflags & IFEF_2KCL));
3122 		tcp_set_ecn(tp, rt->rt_ifp);
3123 		if (inp->inp_last_outifp == NULL) {
3124 			inp->inp_last_outifp = rt->rt_ifp;
3125 #if SKYWALK
3126 			if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
3127 				netns_set_ifnet(&inp->inp_netns_token,
3128 				    inp->inp_last_outifp);
3129 			}
3130 #endif /* SKYWALK */
3131 		}
3132 
3133 		/* Note if the peer is local */
3134 		if (!(rt->rt_ifp->if_flags & IFF_POINTOPOINT) &&
3135 		    (IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr) ||
3136 		    IN6_IS_ADDR_LINKLOCAL(&inp->in6p_faddr) ||
3137 		    rt->rt_gateway->sa_family == AF_LINK ||
3138 		    in6_localaddr(&inp->in6p_faddr))) {
3139 			tp->t_flags |= TF_LOCAL;
3140 		}
3141 	}
3142 
3143 	/*
3144 	 * Caller needs to call RT_UNLOCK(rt).
3145 	 */
3146 	return rt;
3147 }
3148 
3149 #if IPSEC
3150 /* compute ESP/AH header size for TCP, including outer IP header. */
3151 size_t
ipsec_hdrsiz_tcp(struct tcpcb * tp)3152 ipsec_hdrsiz_tcp(struct tcpcb *tp)
3153 {
3154 	struct inpcb *inp;
3155 	struct mbuf *m;
3156 	size_t hdrsiz;
3157 	struct ip *ip;
3158 	struct ip6_hdr *ip6 = NULL;
3159 	struct tcphdr *th;
3160 
3161 	if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL)) {
3162 		return 0;
3163 	}
3164 	MGETHDR(m, M_DONTWAIT, MT_DATA);        /* MAC-OK */
3165 	if (!m) {
3166 		return 0;
3167 	}
3168 
3169 	if ((inp->inp_vflag & INP_IPV6) != 0) {
3170 		ip6 = mtod(m, struct ip6_hdr *);
3171 		th = (struct tcphdr *)(void *)(ip6 + 1);
3172 		m->m_pkthdr.len = m->m_len =
3173 		    sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3174 		tcp_fillheaders(m, tp, ip6, th);
3175 		hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
3176 	} else {
3177 		ip = mtod(m, struct ip *);
3178 		th = (struct tcphdr *)(ip + 1);
3179 		m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
3180 		tcp_fillheaders(m, tp, ip, th);
3181 		hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
3182 	}
3183 	m_free(m);
3184 	return hdrsiz;
3185 }
3186 #endif /* IPSEC */
3187 
3188 int
tcp_lock(struct socket * so,int refcount,void * lr)3189 tcp_lock(struct socket *so, int refcount, void *lr)
3190 {
3191 	void *lr_saved;
3192 
3193 	if (lr == NULL) {
3194 		lr_saved = __builtin_return_address(0);
3195 	} else {
3196 		lr_saved = lr;
3197 	}
3198 
3199 retry:
3200 	if (so->so_pcb != NULL) {
3201 		if (so->so_flags & SOF_MP_SUBFLOW) {
3202 			struct mptcb *mp_tp = tptomptp(sototcpcb(so));
3203 			struct socket *mp_so = mptetoso(mp_tp->mpt_mpte);
3204 
3205 			socket_lock(mp_so, refcount);
3206 
3207 			/*
3208 			 * Check if we became non-MPTCP while waiting for the lock.
3209 			 * If yes, we have to retry to grab the right lock.
3210 			 */
3211 			if (!(so->so_flags & SOF_MP_SUBFLOW)) {
3212 				socket_unlock(mp_so, refcount);
3213 				goto retry;
3214 			}
3215 		} else {
3216 			lck_mtx_lock(&((struct inpcb *)so->so_pcb)->inpcb_mtx);
3217 
3218 			if (so->so_flags & SOF_MP_SUBFLOW) {
3219 				/*
3220 				 * While waiting for the lock, we might have
3221 				 * become MPTCP-enabled (see mptcp_subflow_socreate).
3222 				 */
3223 				lck_mtx_unlock(&((struct inpcb *)so->so_pcb)->inpcb_mtx);
3224 				goto retry;
3225 			}
3226 		}
3227 	} else {
3228 		panic("tcp_lock: so=%p NO PCB! lr=%p lrh= %s",
3229 		    so, lr_saved, solockhistory_nr(so));
3230 		/* NOTREACHED */
3231 	}
3232 
3233 	if (so->so_usecount < 0) {
3234 		panic("tcp_lock: so=%p so_pcb=%p lr=%p ref=%x lrh= %s",
3235 		    so, so->so_pcb, lr_saved, so->so_usecount,
3236 		    solockhistory_nr(so));
3237 		/* NOTREACHED */
3238 	}
3239 	if (refcount) {
3240 		so->so_usecount++;
3241 	}
3242 	so->lock_lr[so->next_lock_lr] = lr_saved;
3243 	so->next_lock_lr = (so->next_lock_lr + 1) % SO_LCKDBG_MAX;
3244 	return 0;
3245 }
3246 
3247 int
tcp_unlock(struct socket * so,int refcount,void * lr)3248 tcp_unlock(struct socket *so, int refcount, void *lr)
3249 {
3250 	void *lr_saved;
3251 
3252 	if (lr == NULL) {
3253 		lr_saved = __builtin_return_address(0);
3254 	} else {
3255 		lr_saved = lr;
3256 	}
3257 
3258 #ifdef MORE_TCPLOCK_DEBUG
3259 	printf("tcp_unlock: so=0x%llx sopcb=0x%llx lock=0x%llx ref=%x "
3260 	    "lr=0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(so),
3261 	    (uint64_t)VM_KERNEL_ADDRPERM(so->so_pcb),
3262 	    (uint64_t)VM_KERNEL_ADDRPERM(&(sotoinpcb(so)->inpcb_mtx)),
3263 	    so->so_usecount, (uint64_t)VM_KERNEL_ADDRPERM(lr_saved));
3264 #endif
3265 	if (refcount) {
3266 		so->so_usecount--;
3267 	}
3268 
3269 	if (so->so_usecount < 0) {
3270 		panic("tcp_unlock: so=%p usecount=%x lrh= %s",
3271 		    so, so->so_usecount, solockhistory_nr(so));
3272 		/* NOTREACHED */
3273 	}
3274 	if (so->so_pcb == NULL) {
3275 		panic("tcp_unlock: so=%p NO PCB usecount=%x lr=%p lrh= %s",
3276 		    so, so->so_usecount, lr_saved, solockhistory_nr(so));
3277 		/* NOTREACHED */
3278 	} else {
3279 		so->unlock_lr[so->next_unlock_lr] = lr_saved;
3280 		so->next_unlock_lr = (so->next_unlock_lr + 1) % SO_LCKDBG_MAX;
3281 
3282 		if (so->so_flags & SOF_MP_SUBFLOW) {
3283 			struct mptcb *mp_tp = tptomptp(sototcpcb(so));
3284 			struct socket *mp_so = mptetoso(mp_tp->mpt_mpte);
3285 
3286 			socket_lock_assert_owned(mp_so);
3287 
3288 			socket_unlock(mp_so, refcount);
3289 		} else {
3290 			LCK_MTX_ASSERT(&((struct inpcb *)so->so_pcb)->inpcb_mtx,
3291 			    LCK_MTX_ASSERT_OWNED);
3292 			lck_mtx_unlock(&((struct inpcb *)so->so_pcb)->inpcb_mtx);
3293 		}
3294 	}
3295 	return 0;
3296 }
3297 
3298 lck_mtx_t *
tcp_getlock(struct socket * so,int flags)3299 tcp_getlock(struct socket *so, int flags)
3300 {
3301 	struct inpcb *inp = sotoinpcb(so);
3302 
3303 	if (so->so_pcb) {
3304 		if (so->so_usecount < 0) {
3305 			panic("tcp_getlock: so=%p usecount=%x lrh= %s",
3306 			    so, so->so_usecount, solockhistory_nr(so));
3307 		}
3308 
3309 		if (so->so_flags & SOF_MP_SUBFLOW) {
3310 			struct mptcb *mp_tp = tptomptp(sototcpcb(so));
3311 			struct socket *mp_so = mptetoso(mp_tp->mpt_mpte);
3312 
3313 			return mp_so->so_proto->pr_getlock(mp_so, flags);
3314 		} else {
3315 			return &inp->inpcb_mtx;
3316 		}
3317 	} else {
3318 		panic("tcp_getlock: so=%p NULL so_pcb %s",
3319 		    so, solockhistory_nr(so));
3320 		return so->so_proto->pr_domain->dom_mtx;
3321 	}
3322 }
3323 
3324 /*
3325  * Determine if we can grow the recieve socket buffer to avoid sending
3326  * a zero window update to the peer. We allow even socket buffers that
3327  * have fixed size (set by the application) to grow if the resource
3328  * constraints are met. They will also be trimmed after the application
3329  * reads data.
3330  */
3331 static void
tcp_sbrcv_grow_rwin(struct tcpcb * tp,struct sockbuf * sb)3332 tcp_sbrcv_grow_rwin(struct tcpcb *tp, struct sockbuf *sb)
3333 {
3334 	u_int32_t rcvbufinc = tp->t_maxseg << 4;
3335 	u_int32_t rcvbuf = sb->sb_hiwat;
3336 	struct socket *so = tp->t_inpcb->inp_socket;
3337 
3338 	if (tcp_recv_bg == 1 || IS_TCP_RECV_BG(so)) {
3339 		return;
3340 	}
3341 
3342 	if (tcp_do_autorcvbuf == 1 &&
3343 	    tcp_cansbgrow(sb) &&
3344 	    (tp->t_flags & TF_SLOWLINK) == 0 &&
3345 	    (so->so_flags1 & SOF1_EXTEND_BK_IDLE_WANTED) == 0 &&
3346 	    (rcvbuf - sb->sb_cc) < rcvbufinc &&
3347 	    rcvbuf < tcp_autorcvbuf_max &&
3348 	    (sb->sb_idealsize > 0 &&
3349 	    sb->sb_hiwat <= (sb->sb_idealsize + rcvbufinc))) {
3350 		sbreserve(sb,
3351 		    min((sb->sb_hiwat + rcvbufinc), tcp_autorcvbuf_max));
3352 	}
3353 }
3354 
3355 int32_t
tcp_sbspace(struct tcpcb * tp)3356 tcp_sbspace(struct tcpcb *tp)
3357 {
3358 	struct socket *so = tp->t_inpcb->inp_socket;
3359 	struct sockbuf *sb = &so->so_rcv;
3360 	u_int32_t rcvbuf;
3361 	int32_t space;
3362 	int32_t pending = 0;
3363 
3364 	if (so->so_flags & SOF_MP_SUBFLOW) {
3365 		/* We still need to grow TCP's buffer to have a BDP-estimate */
3366 		tcp_sbrcv_grow_rwin(tp, sb);
3367 
3368 		return mptcp_sbspace(tptomptp(tp));
3369 	}
3370 
3371 	tcp_sbrcv_grow_rwin(tp, sb);
3372 
3373 	/* hiwat might have changed */
3374 	rcvbuf = sb->sb_hiwat;
3375 
3376 	space =  ((int32_t) imin((rcvbuf - sb->sb_cc),
3377 	    (sb->sb_mbmax - sb->sb_mbcnt)));
3378 	if (space < 0) {
3379 		space = 0;
3380 	}
3381 
3382 #if CONTENT_FILTER
3383 	/* Compensate for data being processed by content filters */
3384 	pending = cfil_sock_data_space(sb);
3385 #endif /* CONTENT_FILTER */
3386 	if (pending > space) {
3387 		space = 0;
3388 	} else {
3389 		space -= pending;
3390 	}
3391 
3392 	/*
3393 	 * Avoid increasing window size if the current window
3394 	 * is already very low, we could be in "persist" mode and
3395 	 * we could break some apps (see rdar://5409343)
3396 	 */
3397 
3398 	if (space < tp->t_maxseg) {
3399 		return space;
3400 	}
3401 
3402 	/* Clip window size for slower link */
3403 
3404 	if (((tp->t_flags & TF_SLOWLINK) != 0) && slowlink_wsize > 0) {
3405 		return imin(space, slowlink_wsize);
3406 	}
3407 
3408 	return space;
3409 }
3410 /*
3411  * Checks TCP Segment Offloading capability for a given connection
3412  * and interface pair.
3413  */
3414 void
tcp_set_tso(struct tcpcb * tp,struct ifnet * ifp)3415 tcp_set_tso(struct tcpcb *tp, struct ifnet *ifp)
3416 {
3417 	struct inpcb *inp;
3418 	int isipv6;
3419 	struct ifnet *tunnel_ifp = NULL;
3420 #define IFNET_TSO_MASK (IFNET_TSO_IPV6 | IFNET_TSO_IPV4)
3421 
3422 	tp->t_flags &= ~TF_TSO;
3423 
3424 	/*
3425 	 * Bail if there's a non-TSO-capable filter on the interface.
3426 	 */
3427 	if (ifp == NULL || ifp->if_flt_no_tso_count > 0) {
3428 		return;
3429 	}
3430 
3431 	inp = tp->t_inpcb;
3432 	isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
3433 
3434 #if MPTCP
3435 	/*
3436 	 * We can't use TSO if this tcpcb belongs to an MPTCP session.
3437 	 */
3438 	if (inp->inp_socket->so_flags & SOF_MP_SUBFLOW) {
3439 		return;
3440 	}
3441 #endif
3442 	/*
3443 	 * We can't use TSO if the TSO capability of the tunnel interface does
3444 	 * not match the capability of another interface known by TCP
3445 	 */
3446 	if (inp->inp_policyresult.results.result == NECP_KERNEL_POLICY_RESULT_IP_TUNNEL) {
3447 		u_int tunnel_if_index = inp->inp_policyresult.results.result_parameter.tunnel_interface_index;
3448 
3449 		if (tunnel_if_index != 0) {
3450 			ifnet_head_lock_shared();
3451 			tunnel_ifp = ifindex2ifnet[tunnel_if_index];
3452 			ifnet_head_done();
3453 		}
3454 
3455 		if (tunnel_ifp == NULL) {
3456 			return;
3457 		}
3458 
3459 		if ((ifp->if_hwassist & IFNET_TSO_MASK) != (tunnel_ifp->if_hwassist & IFNET_TSO_MASK)) {
3460 			if (tso_debug > 0) {
3461 				os_log(OS_LOG_DEFAULT,
3462 				    "%s: %u > %u TSO 0 tunnel_ifp %s hwassist mismatch with ifp %s",
3463 				    __func__,
3464 				    ntohs(tp->t_inpcb->inp_lport), ntohs(tp->t_inpcb->inp_fport),
3465 				    tunnel_ifp->if_xname, ifp->if_xname);
3466 			}
3467 			return;
3468 		}
3469 		if (inp->inp_last_outifp != NULL &&
3470 		    (inp->inp_last_outifp->if_hwassist & IFNET_TSO_MASK) != (tunnel_ifp->if_hwassist & IFNET_TSO_MASK)) {
3471 			if (tso_debug > 0) {
3472 				os_log(OS_LOG_DEFAULT,
3473 				    "%s: %u > %u TSO 0 tunnel_ifp %s hwassist mismatch with inp_last_outifp %s",
3474 				    __func__,
3475 				    ntohs(tp->t_inpcb->inp_lport), ntohs(tp->t_inpcb->inp_fport),
3476 				    tunnel_ifp->if_xname, inp->inp_last_outifp->if_xname);
3477 			}
3478 			return;
3479 		}
3480 		if ((inp->inp_flags & INP_BOUND_IF) && inp->inp_boundifp != NULL &&
3481 		    (inp->inp_boundifp->if_hwassist & IFNET_TSO_MASK) != (tunnel_ifp->if_hwassist & IFNET_TSO_MASK)) {
3482 			if (tso_debug > 0) {
3483 				os_log(OS_LOG_DEFAULT,
3484 				    "%s: %u > %u TSO 0 tunnel_ifp %s hwassist mismatch with inp_boundifp %s",
3485 				    __func__,
3486 				    ntohs(tp->t_inpcb->inp_lport), ntohs(tp->t_inpcb->inp_fport),
3487 				    tunnel_ifp->if_xname, inp->inp_boundifp->if_xname);
3488 			}
3489 			return;
3490 		}
3491 	}
3492 
3493 	if (isipv6) {
3494 		if (ifp->if_hwassist & IFNET_TSO_IPV6) {
3495 			tp->t_flags |= TF_TSO;
3496 			if (ifp->if_tso_v6_mtu != 0) {
3497 				tp->tso_max_segment_size = ifp->if_tso_v6_mtu;
3498 			} else {
3499 				tp->tso_max_segment_size = TCP_MAXWIN;
3500 			}
3501 		}
3502 	} else {
3503 		if (ifp->if_hwassist & IFNET_TSO_IPV4) {
3504 			tp->t_flags |= TF_TSO;
3505 			if (ifp->if_tso_v4_mtu != 0) {
3506 				tp->tso_max_segment_size = ifp->if_tso_v4_mtu;
3507 			} else {
3508 				tp->tso_max_segment_size = TCP_MAXWIN;
3509 			}
3510 			if (INTF_ADJUST_MTU_FOR_CLAT46(ifp)) {
3511 				tp->tso_max_segment_size -=
3512 				    CLAT46_HDR_EXPANSION_OVERHD;
3513 			}
3514 		}
3515 	}
3516 
3517 	if (tso_debug > 1) {
3518 		os_log(OS_LOG_DEFAULT, "%s: %u > %u TSO %d ifp %s",
3519 		    __func__,
3520 		    ntohs(tp->t_inpcb->inp_lport),
3521 		    ntohs(tp->t_inpcb->inp_fport),
3522 		    (tp->t_flags & TF_TSO) != 0,
3523 		    ifp != NULL ? ifp->if_xname : "<NULL>");
3524 	}
3525 }
3526 
3527 #define TIMEVAL_TO_TCPHZ(_tv_) ((uint32_t)((_tv_).tv_sec * TCP_RETRANSHZ + \
3528 	(_tv_).tv_usec / TCP_RETRANSHZ_TO_USEC))
3529 
3530 /*
3531  * Function to calculate the tcp clock. The tcp clock will get updated
3532  * at the boundaries of the tcp layer. This is done at 3 places:
3533  * 1. Right before processing an input tcp packet
3534  * 2. Whenever a connection wants to access the network using tcp_usrreqs
3535  * 3. When a tcp timer fires or before tcp slow timeout
3536  *
3537  */
3538 
3539 void
calculate_tcp_clock(void)3540 calculate_tcp_clock(void)
3541 {
3542 	struct timeval tv = tcp_uptime;
3543 	struct timeval interval = {.tv_sec = 0, .tv_usec = TCP_RETRANSHZ_TO_USEC};
3544 	struct timeval now, hold_now;
3545 	uint32_t incr = 0;
3546 
3547 	microuptime(&now);
3548 
3549 	/*
3550 	 * Update coarse-grained networking timestamp (in sec.); the idea
3551 	 * is to update the counter returnable via net_uptime() when
3552 	 * we read time.
3553 	 */
3554 	net_update_uptime_with_time(&now);
3555 
3556 	timevaladd(&tv, &interval);
3557 	if (timevalcmp(&now, &tv, >)) {
3558 		/* time to update the clock */
3559 		lck_spin_lock(&tcp_uptime_lock);
3560 		if (timevalcmp(&tcp_uptime, &now, >=)) {
3561 			/* clock got updated while waiting for the lock */
3562 			lck_spin_unlock(&tcp_uptime_lock);
3563 			return;
3564 		}
3565 
3566 		microuptime(&now);
3567 		hold_now = now;
3568 		tv = tcp_uptime;
3569 		timevalsub(&now, &tv);
3570 
3571 		incr = TIMEVAL_TO_TCPHZ(now);
3572 
3573 		/* Account for the previous remainder */
3574 		uint32_t remaining_us = (now.tv_usec % TCP_RETRANSHZ_TO_USEC) +
3575 		    tcp_now_remainder_us;
3576 		if (remaining_us >= TCP_RETRANSHZ_TO_USEC) {
3577 			incr += (remaining_us / TCP_RETRANSHZ_TO_USEC);
3578 		}
3579 
3580 		if (incr > 0) {
3581 			tcp_uptime = hold_now;
3582 			tcp_now_remainder_us = remaining_us % TCP_RETRANSHZ_TO_USEC;
3583 			tcp_now += incr;
3584 		}
3585 
3586 		lck_spin_unlock(&tcp_uptime_lock);
3587 	}
3588 }
3589 
3590 /*
3591  * Compute receive window scaling that we are going to request
3592  * for this connection based on  sb_hiwat. Try to leave some
3593  * room to potentially increase the window size upto a maximum
3594  * defined by the constant tcp_autorcvbuf_max.
3595  */
3596 void
tcp_set_max_rwinscale(struct tcpcb * tp,struct socket * so)3597 tcp_set_max_rwinscale(struct tcpcb *tp, struct socket *so)
3598 {
3599 	uint32_t maxsockbufsize;
3600 
3601 	tp->request_r_scale = MAX((uint8_t)tcp_win_scale, tp->request_r_scale);
3602 	maxsockbufsize = ((so->so_rcv.sb_flags & SB_USRSIZE) != 0) ?
3603 	    so->so_rcv.sb_hiwat : tcp_autorcvbuf_max;
3604 
3605 	/*
3606 	 * Window scale should not exceed what is needed
3607 	 * to send the max receive window size; adding 1 to TCP_MAXWIN
3608 	 * ensures that.
3609 	 */
3610 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
3611 	    ((TCP_MAXWIN + 1) << tp->request_r_scale) < maxsockbufsize) {
3612 		tp->request_r_scale++;
3613 	}
3614 	tp->request_r_scale = MIN(tp->request_r_scale, TCP_MAX_WINSHIFT);
3615 }
3616 
3617 int
tcp_notsent_lowat_check(struct socket * so)3618 tcp_notsent_lowat_check(struct socket *so)
3619 {
3620 	struct inpcb *inp = sotoinpcb(so);
3621 	struct tcpcb *tp = NULL;
3622 	int notsent = 0;
3623 
3624 	if (inp != NULL) {
3625 		tp = intotcpcb(inp);
3626 	}
3627 
3628 	if (tp == NULL) {
3629 		return 0;
3630 	}
3631 
3632 	notsent = so->so_snd.sb_cc -
3633 	    (tp->snd_nxt - tp->snd_una);
3634 
3635 	/*
3636 	 * When we send a FIN or SYN, not_sent can be negative.
3637 	 * In that case also we need to send a write event to the
3638 	 * process if it is waiting. In the FIN case, it will
3639 	 * get an error from send because cantsendmore will be set.
3640 	 */
3641 	if (notsent <= tp->t_notsent_lowat) {
3642 		return 1;
3643 	}
3644 
3645 	/*
3646 	 * When Nagle's algorithm is not disabled, it is better
3647 	 * to wakeup the client until there is atleast one
3648 	 * maxseg of data to write.
3649 	 */
3650 	if ((tp->t_flags & TF_NODELAY) == 0 &&
3651 	    notsent > 0 && notsent < tp->t_maxseg) {
3652 		return 1;
3653 	}
3654 	return 0;
3655 }
3656 
3657 void
tcp_rxtseg_insert(struct tcpcb * tp,tcp_seq start,tcp_seq end)3658 tcp_rxtseg_insert(struct tcpcb *tp, tcp_seq start, tcp_seq end)
3659 {
3660 	struct tcp_rxt_seg *rxseg = NULL, *prev = NULL, *next = NULL;
3661 	uint16_t rxcount = 0;
3662 
3663 	if (SLIST_EMPTY(&tp->t_rxt_segments)) {
3664 		tp->t_dsack_lastuna = tp->snd_una;
3665 	}
3666 	/*
3667 	 * First check if there is a segment already existing for this
3668 	 * sequence space.
3669 	 */
3670 
3671 	SLIST_FOREACH(rxseg, &tp->t_rxt_segments, rx_link) {
3672 		if (SEQ_GT(rxseg->rx_start, start)) {
3673 			break;
3674 		}
3675 		prev = rxseg;
3676 	}
3677 	next = rxseg;
3678 
3679 	/* check if prev seg is for this sequence */
3680 	if (prev != NULL && SEQ_LEQ(prev->rx_start, start) &&
3681 	    SEQ_GEQ(prev->rx_end, end)) {
3682 		prev->rx_count++;
3683 		return;
3684 	}
3685 
3686 	/*
3687 	 * There are a couple of possibilities at this point.
3688 	 * 1. prev overlaps with the beginning of this sequence
3689 	 * 2. next overlaps with the end of this sequence
3690 	 * 3. there is no overlap.
3691 	 */
3692 
3693 	if (prev != NULL && SEQ_GT(prev->rx_end, start)) {
3694 		if (prev->rx_start == start && SEQ_GT(end, prev->rx_end)) {
3695 			start = prev->rx_end + 1;
3696 			prev->rx_count++;
3697 		} else {
3698 			prev->rx_end = (start - 1);
3699 			rxcount = prev->rx_count;
3700 		}
3701 	}
3702 
3703 	if (next != NULL && SEQ_LT(next->rx_start, end)) {
3704 		if (SEQ_LEQ(next->rx_end, end)) {
3705 			end = next->rx_start - 1;
3706 			next->rx_count++;
3707 		} else {
3708 			next->rx_start = end + 1;
3709 			rxcount = next->rx_count;
3710 		}
3711 	}
3712 	if (!SEQ_LT(start, end)) {
3713 		return;
3714 	}
3715 
3716 	if (tcp_rxt_seg_max > 0 && tp->t_rxt_seg_count >= tcp_rxt_seg_max) {
3717 		rxseg = SLIST_FIRST(&tp->t_rxt_segments);
3718 		if (prev == rxseg) {
3719 			prev = NULL;
3720 		}
3721 		SLIST_REMOVE(&tp->t_rxt_segments, rxseg,
3722 		    tcp_rxt_seg, rx_link);
3723 
3724 		tcp_rxt_seg_drop++;
3725 		tp->t_rxt_seg_drop++;
3726 		TCP_LOG(tp, "removed rxseg list overflow %u:%u ",
3727 		    rxseg->rx_start, rxseg->rx_end);
3728 		zfree(tcp_rxt_seg_zone, rxseg);
3729 
3730 		tp->t_rxt_seg_count -= 1;
3731 	}
3732 
3733 	rxseg = zalloc_flags(tcp_rxt_seg_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3734 	rxseg->rx_start = start;
3735 	rxseg->rx_end = end;
3736 	rxseg->rx_count = rxcount + 1;
3737 
3738 	if (prev != NULL) {
3739 		SLIST_INSERT_AFTER(prev, rxseg, rx_link);
3740 	} else {
3741 		SLIST_INSERT_HEAD(&tp->t_rxt_segments, rxseg, rx_link);
3742 	}
3743 	tp->t_rxt_seg_count += 1;
3744 }
3745 
3746 struct tcp_rxt_seg *
tcp_rxtseg_find(struct tcpcb * tp,tcp_seq start,tcp_seq end)3747 tcp_rxtseg_find(struct tcpcb *tp, tcp_seq start, tcp_seq end)
3748 {
3749 	struct tcp_rxt_seg *rxseg;
3750 
3751 	if (SLIST_EMPTY(&tp->t_rxt_segments)) {
3752 		return NULL;
3753 	}
3754 
3755 	SLIST_FOREACH(rxseg, &tp->t_rxt_segments, rx_link) {
3756 		if (SEQ_LEQ(rxseg->rx_start, start) &&
3757 		    SEQ_GEQ(rxseg->rx_end, end)) {
3758 			return rxseg;
3759 		}
3760 		if (SEQ_GT(rxseg->rx_start, start)) {
3761 			break;
3762 		}
3763 	}
3764 	return NULL;
3765 }
3766 
3767 void
tcp_rxtseg_set_spurious(struct tcpcb * tp,tcp_seq start,tcp_seq end)3768 tcp_rxtseg_set_spurious(struct tcpcb *tp, tcp_seq start, tcp_seq end)
3769 {
3770 	struct tcp_rxt_seg *rxseg;
3771 
3772 	if (SLIST_EMPTY(&tp->t_rxt_segments)) {
3773 		return;
3774 	}
3775 
3776 	SLIST_FOREACH(rxseg, &tp->t_rxt_segments, rx_link) {
3777 		if (SEQ_GEQ(rxseg->rx_start, start) &&
3778 		    SEQ_LEQ(rxseg->rx_end, end)) {
3779 			/*
3780 			 * If the segment was retransmitted only once, mark it as
3781 			 * spurious.
3782 			 */
3783 			if (rxseg->rx_count == 1) {
3784 				rxseg->rx_flags |= TCP_RXT_SPURIOUS;
3785 			}
3786 		}
3787 
3788 		if (SEQ_GEQ(rxseg->rx_start, end)) {
3789 			break;
3790 		}
3791 	}
3792 	return;
3793 }
3794 
3795 void
tcp_rxtseg_clean(struct tcpcb * tp)3796 tcp_rxtseg_clean(struct tcpcb *tp)
3797 {
3798 	struct tcp_rxt_seg *rxseg, *next;
3799 
3800 	SLIST_FOREACH_SAFE(rxseg, &tp->t_rxt_segments, rx_link, next) {
3801 		SLIST_REMOVE(&tp->t_rxt_segments, rxseg,
3802 		    tcp_rxt_seg, rx_link);
3803 		zfree(tcp_rxt_seg_zone, rxseg);
3804 	}
3805 	tp->t_rxt_seg_count = 0;
3806 	tp->t_dsack_lastuna = tp->snd_max;
3807 }
3808 
3809 boolean_t
tcp_rxtseg_detect_bad_rexmt(struct tcpcb * tp,tcp_seq th_ack)3810 tcp_rxtseg_detect_bad_rexmt(struct tcpcb *tp, tcp_seq th_ack)
3811 {
3812 	boolean_t bad_rexmt;
3813 	struct tcp_rxt_seg *rxseg;
3814 
3815 	if (SLIST_EMPTY(&tp->t_rxt_segments)) {
3816 		return FALSE;
3817 	}
3818 
3819 	/*
3820 	 * If all of the segments in this window are not cumulatively
3821 	 * acknowledged, then there can still be undetected packet loss.
3822 	 * Do not restore congestion window in that case.
3823 	 */
3824 	if (SEQ_LT(th_ack, tp->snd_recover)) {
3825 		return FALSE;
3826 	}
3827 
3828 	bad_rexmt = TRUE;
3829 	SLIST_FOREACH(rxseg, &tp->t_rxt_segments, rx_link) {
3830 		if (!(rxseg->rx_flags & TCP_RXT_SPURIOUS)) {
3831 			bad_rexmt = FALSE;
3832 			break;
3833 		}
3834 	}
3835 	return bad_rexmt;
3836 }
3837 
3838 u_int32_t
tcp_rxtseg_total_size(struct tcpcb * tp)3839 tcp_rxtseg_total_size(struct tcpcb *tp)
3840 {
3841 	struct tcp_rxt_seg *rxseg;
3842 	u_int32_t total_size = 0;
3843 
3844 	SLIST_FOREACH(rxseg, &tp->t_rxt_segments, rx_link) {
3845 		total_size += (rxseg->rx_end - rxseg->rx_start) + 1;
3846 	}
3847 	return total_size;
3848 }
3849 
3850 void
tcp_get_connectivity_status(struct tcpcb * tp,struct tcp_conn_status * connstatus)3851 tcp_get_connectivity_status(struct tcpcb *tp,
3852     struct tcp_conn_status *connstatus)
3853 {
3854 	if (tp == NULL || connstatus == NULL) {
3855 		return;
3856 	}
3857 	bzero(connstatus, sizeof(*connstatus));
3858 	if (tp->t_rxtshift >= TCP_CONNECTIVITY_PROBES_MAX) {
3859 		if (TCPS_HAVEESTABLISHED(tp->t_state)) {
3860 			connstatus->write_probe_failed = 1;
3861 		} else {
3862 			connstatus->conn_probe_failed = 1;
3863 		}
3864 	}
3865 	if (tp->t_rtimo_probes >= TCP_CONNECTIVITY_PROBES_MAX) {
3866 		connstatus->read_probe_failed = 1;
3867 	}
3868 	if (tp->t_inpcb != NULL && tp->t_inpcb->inp_last_outifp != NULL &&
3869 	    (tp->t_inpcb->inp_last_outifp->if_eflags & IFEF_PROBE_CONNECTIVITY)) {
3870 		connstatus->probe_activated = 1;
3871 	}
3872 }
3873 
3874 boolean_t
tfo_enabled(const struct tcpcb * tp)3875 tfo_enabled(const struct tcpcb *tp)
3876 {
3877 	return (tp->t_flagsext & TF_FASTOPEN)? TRUE : FALSE;
3878 }
3879 
3880 void
tcp_disable_tfo(struct tcpcb * tp)3881 tcp_disable_tfo(struct tcpcb *tp)
3882 {
3883 	tp->t_flagsext &= ~TF_FASTOPEN;
3884 }
3885 
3886 static struct mbuf *
tcp_make_keepalive_frame(struct tcpcb * tp,struct ifnet * ifp,boolean_t is_probe)3887 tcp_make_keepalive_frame(struct tcpcb *tp, struct ifnet *ifp,
3888     boolean_t is_probe)
3889 {
3890 	struct inpcb *inp = tp->t_inpcb;
3891 	struct tcphdr *th;
3892 	u_int8_t *data;
3893 	int win = 0;
3894 	struct mbuf *m;
3895 
3896 	/*
3897 	 * The code assumes the IP + TCP headers fit in an mbuf packet header
3898 	 */
3899 	_CASSERT(sizeof(struct ip) + sizeof(struct tcphdr) <= _MHLEN);
3900 	_CASSERT(sizeof(struct ip6_hdr) + sizeof(struct tcphdr) <= _MHLEN);
3901 
3902 	MGETHDR(m, M_WAIT, MT_HEADER);
3903 	if (m == NULL) {
3904 		return NULL;
3905 	}
3906 	m->m_pkthdr.pkt_proto = IPPROTO_TCP;
3907 
3908 	data = mbuf_datastart(m);
3909 
3910 	if (inp->inp_vflag & INP_IPV4) {
3911 		bzero(data, sizeof(struct ip) + sizeof(struct tcphdr));
3912 		th = (struct tcphdr *)(void *) (data + sizeof(struct ip));
3913 		m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
3914 		m->m_pkthdr.len = m->m_len;
3915 	} else {
3916 		VERIFY(inp->inp_vflag & INP_IPV6);
3917 
3918 		bzero(data, sizeof(struct ip6_hdr)
3919 		    + sizeof(struct tcphdr));
3920 		th = (struct tcphdr *)(void *)(data + sizeof(struct ip6_hdr));
3921 		m->m_len = sizeof(struct ip6_hdr) +
3922 		    sizeof(struct tcphdr);
3923 		m->m_pkthdr.len = m->m_len;
3924 	}
3925 
3926 	tcp_fillheaders(m, tp, data, th);
3927 
3928 	if (inp->inp_vflag & INP_IPV4) {
3929 		struct ip *ip;
3930 
3931 		ip = (__typeof__(ip))(void *)data;
3932 
3933 		ip->ip_id = rfc6864 ? 0 : ip_randomid((uint64_t)m);
3934 		ip->ip_off = htons(IP_DF);
3935 		ip->ip_len = htons(sizeof(struct ip) + sizeof(struct tcphdr));
3936 		ip->ip_ttl = inp->inp_ip_ttl;
3937 		ip->ip_tos |= (inp->inp_ip_tos & ~IPTOS_ECN_MASK);
3938 		ip->ip_sum = in_cksum_hdr(ip);
3939 	} else {
3940 		struct ip6_hdr *ip6;
3941 
3942 		ip6 = (__typeof__(ip6))(void *)data;
3943 
3944 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
3945 		ip6->ip6_hlim = in6_selecthlim(inp, ifp);
3946 		ip6->ip6_flow = ip6->ip6_flow & ~IPV6_FLOW_ECN_MASK;
3947 
3948 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_src)) {
3949 			ip6->ip6_src.s6_addr16[1] = 0;
3950 		}
3951 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
3952 			ip6->ip6_dst.s6_addr16[1] = 0;
3953 		}
3954 	}
3955 	th->th_flags = TH_ACK;
3956 
3957 	win = tcp_sbspace(tp);
3958 	if (win > ((int32_t)TCP_MAXWIN << tp->rcv_scale)) {
3959 		win = (int32_t)TCP_MAXWIN << tp->rcv_scale;
3960 	}
3961 	th->th_win = htons((u_short) (win >> tp->rcv_scale));
3962 
3963 	if (is_probe) {
3964 		th->th_seq = htonl(tp->snd_una - 1);
3965 	} else {
3966 		th->th_seq = htonl(tp->snd_una);
3967 	}
3968 	th->th_ack = htonl(tp->rcv_nxt);
3969 
3970 	/* Force recompute TCP checksum to be the final value */
3971 	th->th_sum = 0;
3972 	if (inp->inp_vflag & INP_IPV4) {
3973 		th->th_sum = inet_cksum(m, IPPROTO_TCP,
3974 		    sizeof(struct ip), sizeof(struct tcphdr));
3975 	} else {
3976 		th->th_sum = inet6_cksum(m, IPPROTO_TCP,
3977 		    sizeof(struct ip6_hdr), sizeof(struct tcphdr));
3978 	}
3979 
3980 	return m;
3981 }
3982 
3983 void
tcp_fill_keepalive_offload_frames(ifnet_t ifp,struct ifnet_keepalive_offload_frame * frames_array,u_int32_t frames_array_count,size_t frame_data_offset,u_int32_t * used_frames_count)3984 tcp_fill_keepalive_offload_frames(ifnet_t ifp,
3985     struct ifnet_keepalive_offload_frame *frames_array,
3986     u_int32_t frames_array_count, size_t frame_data_offset,
3987     u_int32_t *used_frames_count)
3988 {
3989 	struct inpcb *inp;
3990 	inp_gen_t gencnt;
3991 	u_int32_t frame_index = *used_frames_count;
3992 
3993 	if (ifp == NULL || frames_array == NULL ||
3994 	    frames_array_count == 0 ||
3995 	    frame_index >= frames_array_count ||
3996 	    frame_data_offset >= IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
3997 		return;
3998 	}
3999 
4000 	/*
4001 	 * This function is called outside the regular TCP processing
4002 	 * so we need to update the TCP clock.
4003 	 */
4004 	calculate_tcp_clock();
4005 
4006 	lck_rw_lock_shared(&tcbinfo.ipi_lock);
4007 	gencnt = tcbinfo.ipi_gencnt;
4008 	LIST_FOREACH(inp, tcbinfo.ipi_listhead, inp_list) {
4009 		struct socket *so;
4010 		struct ifnet_keepalive_offload_frame *frame;
4011 		struct mbuf *m = NULL;
4012 		struct tcpcb *tp = intotcpcb(inp);
4013 
4014 		if (frame_index >= frames_array_count) {
4015 			break;
4016 		}
4017 
4018 		if (inp->inp_gencnt > gencnt ||
4019 		    inp->inp_state == INPCB_STATE_DEAD) {
4020 			continue;
4021 		}
4022 
4023 		if ((so = inp->inp_socket) == NULL ||
4024 		    (so->so_state & SS_DEFUNCT)) {
4025 			continue;
4026 		}
4027 		/*
4028 		 * check for keepalive offload flag without socket
4029 		 * lock to avoid a deadlock
4030 		 */
4031 		if (!(inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD)) {
4032 			continue;
4033 		}
4034 
4035 		if (!(inp->inp_vflag & (INP_IPV4 | INP_IPV6))) {
4036 			continue;
4037 		}
4038 		if (inp->inp_ppcb == NULL ||
4039 		    in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
4040 			continue;
4041 		}
4042 		socket_lock(so, 1);
4043 		/* Release the want count */
4044 		if (inp->inp_ppcb == NULL ||
4045 		    (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING)) {
4046 			socket_unlock(so, 1);
4047 			continue;
4048 		}
4049 		if ((inp->inp_vflag & INP_IPV4) &&
4050 		    (inp->inp_laddr.s_addr == INADDR_ANY ||
4051 		    inp->inp_faddr.s_addr == INADDR_ANY)) {
4052 			socket_unlock(so, 1);
4053 			continue;
4054 		}
4055 		if ((inp->inp_vflag & INP_IPV6) &&
4056 		    (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ||
4057 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))) {
4058 			socket_unlock(so, 1);
4059 			continue;
4060 		}
4061 		if (inp->inp_lport == 0 || inp->inp_fport == 0) {
4062 			socket_unlock(so, 1);
4063 			continue;
4064 		}
4065 		if (inp->inp_last_outifp == NULL ||
4066 		    inp->inp_last_outifp->if_index != ifp->if_index) {
4067 			socket_unlock(so, 1);
4068 			continue;
4069 		}
4070 		if ((inp->inp_vflag & INP_IPV4) && frame_data_offset +
4071 		    sizeof(struct ip) + sizeof(struct tcphdr) >
4072 		    IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
4073 			socket_unlock(so, 1);
4074 			continue;
4075 		} else if (!(inp->inp_vflag & INP_IPV4) && frame_data_offset +
4076 		    sizeof(struct ip6_hdr) + sizeof(struct tcphdr) >
4077 		    IFNET_KEEPALIVE_OFFLOAD_FRAME_DATA_SIZE) {
4078 			socket_unlock(so, 1);
4079 			continue;
4080 		}
4081 		/*
4082 		 * There is no point in waking up the device for connections
4083 		 * that are not established. Long lived connection are meant
4084 		 * for processes that will sent and receive data
4085 		 */
4086 		if (tp->t_state != TCPS_ESTABLISHED) {
4087 			socket_unlock(so, 1);
4088 			continue;
4089 		}
4090 		/*
4091 		 * This inp has all the information that is needed to
4092 		 * generate an offload frame.
4093 		 */
4094 		frame = &frames_array[frame_index];
4095 		frame->type = IFNET_KEEPALIVE_OFFLOAD_FRAME_TCP;
4096 		frame->ether_type = (inp->inp_vflag & INP_IPV4) ?
4097 		    IFNET_KEEPALIVE_OFFLOAD_FRAME_ETHERTYPE_IPV4 :
4098 		    IFNET_KEEPALIVE_OFFLOAD_FRAME_ETHERTYPE_IPV6;
4099 		frame->interval = (uint16_t)(tp->t_keepidle > 0 ? tp->t_keepidle :
4100 		    tcp_keepidle);
4101 		frame->keep_cnt = (uint8_t)TCP_CONN_KEEPCNT(tp);
4102 		frame->keep_retry = (uint16_t)TCP_CONN_KEEPINTVL(tp);
4103 		if (so->so_options & SO_NOWAKEFROMSLEEP) {
4104 			frame->flags |=
4105 			    IFNET_KEEPALIVE_OFFLOAD_FLAG_NOWAKEFROMSLEEP;
4106 		}
4107 		frame->local_port = ntohs(inp->inp_lport);
4108 		frame->remote_port = ntohs(inp->inp_fport);
4109 		frame->local_seq = tp->snd_nxt;
4110 		frame->remote_seq = tp->rcv_nxt;
4111 		if (inp->inp_vflag & INP_IPV4) {
4112 			ASSERT(frame_data_offset + sizeof(struct ip) + sizeof(struct tcphdr) <= UINT8_MAX);
4113 			frame->length = (uint8_t)(frame_data_offset +
4114 			    sizeof(struct ip) + sizeof(struct tcphdr));
4115 			frame->reply_length =  frame->length;
4116 
4117 			frame->addr_length = sizeof(struct in_addr);
4118 			bcopy(&inp->inp_laddr, frame->local_addr,
4119 			    sizeof(struct in_addr));
4120 			bcopy(&inp->inp_faddr, frame->remote_addr,
4121 			    sizeof(struct in_addr));
4122 		} else {
4123 			struct in6_addr *ip6;
4124 
4125 			ASSERT(frame_data_offset + sizeof(struct ip6_hdr) + sizeof(struct tcphdr) <= UINT8_MAX);
4126 			frame->length = (uint8_t)(frame_data_offset +
4127 			    sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
4128 			frame->reply_length =  frame->length;
4129 
4130 			frame->addr_length = sizeof(struct in6_addr);
4131 			ip6 = (struct in6_addr *)(void *)frame->local_addr;
4132 			bcopy(&inp->in6p_laddr, ip6, sizeof(struct in6_addr));
4133 			if (IN6_IS_SCOPE_EMBED(ip6)) {
4134 				ip6->s6_addr16[1] = 0;
4135 			}
4136 
4137 			ip6 = (struct in6_addr *)(void *)frame->remote_addr;
4138 			bcopy(&inp->in6p_faddr, ip6, sizeof(struct in6_addr));
4139 			if (IN6_IS_SCOPE_EMBED(ip6)) {
4140 				ip6->s6_addr16[1] = 0;
4141 			}
4142 		}
4143 
4144 		/*
4145 		 * First the probe
4146 		 */
4147 		m = tcp_make_keepalive_frame(tp, ifp, TRUE);
4148 		if (m == NULL) {
4149 			socket_unlock(so, 1);
4150 			continue;
4151 		}
4152 		bcopy(m->m_data, frame->data + frame_data_offset,
4153 		    m->m_len);
4154 		m_freem(m);
4155 
4156 		/*
4157 		 * Now the response packet to incoming probes
4158 		 */
4159 		m = tcp_make_keepalive_frame(tp, ifp, FALSE);
4160 		if (m == NULL) {
4161 			socket_unlock(so, 1);
4162 			continue;
4163 		}
4164 		bcopy(m->m_data, frame->reply_data + frame_data_offset,
4165 		    m->m_len);
4166 		m_freem(m);
4167 
4168 		frame_index++;
4169 		socket_unlock(so, 1);
4170 	}
4171 	lck_rw_done(&tcbinfo.ipi_lock);
4172 	*used_frames_count = frame_index;
4173 }
4174 
4175 static bool
inp_matches_kao_frame(ifnet_t ifp,struct ifnet_keepalive_offload_frame * frame,struct inpcb * inp)4176 inp_matches_kao_frame(ifnet_t ifp, struct ifnet_keepalive_offload_frame *frame,
4177     struct inpcb *inp)
4178 {
4179 	if (inp->inp_ppcb == NULL) {
4180 		return false;
4181 	}
4182 	/* Release the want count */
4183 	if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
4184 		return false;
4185 	}
4186 	if (inp->inp_last_outifp == NULL ||
4187 	    inp->inp_last_outifp->if_index != ifp->if_index) {
4188 		return false;
4189 	}
4190 	if (frame->local_port != ntohs(inp->inp_lport) ||
4191 	    frame->remote_port != ntohs(inp->inp_fport)) {
4192 		return false;
4193 	}
4194 	if (inp->inp_vflag & INP_IPV4) {
4195 		if (memcmp(&inp->inp_laddr, frame->local_addr,
4196 		    sizeof(struct in_addr)) != 0 ||
4197 		    memcmp(&inp->inp_faddr, frame->remote_addr,
4198 		    sizeof(struct in_addr)) != 0) {
4199 			return false;
4200 		}
4201 	} else if (inp->inp_vflag & INP_IPV6) {
4202 		if (memcmp(&inp->inp_laddr, frame->local_addr,
4203 		    sizeof(struct in6_addr)) != 0 ||
4204 		    memcmp(&inp->inp_faddr, frame->remote_addr,
4205 		    sizeof(struct in6_addr)) != 0) {
4206 			return false;
4207 		}
4208 	} else {
4209 		return false;
4210 	}
4211 	return true;
4212 }
4213 
4214 int
tcp_notify_kao_timeout(ifnet_t ifp,struct ifnet_keepalive_offload_frame * frame)4215 tcp_notify_kao_timeout(ifnet_t ifp,
4216     struct ifnet_keepalive_offload_frame *frame)
4217 {
4218 	struct inpcb *inp = NULL;
4219 	struct socket *so = NULL;
4220 	bool found = false;
4221 
4222 	/*
4223 	 *  Unlock the list before posting event on the matching socket
4224 	 */
4225 	lck_rw_lock_shared(&tcbinfo.ipi_lock);
4226 
4227 	LIST_FOREACH(inp, tcbinfo.ipi_listhead, inp_list) {
4228 		if ((so = inp->inp_socket) == NULL ||
4229 		    (so->so_state & SS_DEFUNCT)) {
4230 			continue;
4231 		}
4232 		if (!(inp->inp_flags2 & INP2_KEEPALIVE_OFFLOAD)) {
4233 			continue;
4234 		}
4235 		if (!(inp->inp_vflag & (INP_IPV4 | INP_IPV6))) {
4236 			continue;
4237 		}
4238 		if (inp->inp_ppcb == NULL ||
4239 		    in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
4240 			continue;
4241 		}
4242 		socket_lock(so, 1);
4243 		if (inp_matches_kao_frame(ifp, frame, inp)) {
4244 			/*
4245 			 * Keep the matching socket locked
4246 			 */
4247 			found = true;
4248 			break;
4249 		}
4250 		socket_unlock(so, 1);
4251 	}
4252 	lck_rw_done(&tcbinfo.ipi_lock);
4253 
4254 	if (found) {
4255 		ASSERT(inp != NULL);
4256 		ASSERT(so != NULL);
4257 		ASSERT(so == inp->inp_socket);
4258 		/*
4259 		 * Drop the TCP connection like tcptimers() does
4260 		 */
4261 		struct tcpcb *tp = inp->inp_ppcb;
4262 
4263 		tcpstat.tcps_keepdrops++;
4264 		soevent(so,
4265 		    (SO_FILT_HINT_LOCKED | SO_FILT_HINT_TIMEOUT));
4266 		tp = tcp_drop(tp, ETIMEDOUT);
4267 
4268 		tcpstat.tcps_ka_offload_drops++;
4269 		os_log_info(OS_LOG_DEFAULT, "%s: dropped lport %u fport %u\n",
4270 		    __func__, frame->local_port, frame->remote_port);
4271 
4272 		socket_unlock(so, 1);
4273 	}
4274 
4275 	return 0;
4276 }
4277 
4278 errno_t
tcp_notify_ack_id_valid(struct tcpcb * tp,struct socket * so,u_int32_t notify_id)4279 tcp_notify_ack_id_valid(struct tcpcb *tp, struct socket *so,
4280     u_int32_t notify_id)
4281 {
4282 	struct tcp_notify_ack_marker *elm;
4283 
4284 	if (so->so_snd.sb_cc == 0) {
4285 		return ENOBUFS;
4286 	}
4287 
4288 	SLIST_FOREACH(elm, &tp->t_notify_ack, notify_next) {
4289 		/* Duplicate id is not allowed */
4290 		if (elm->notify_id == notify_id) {
4291 			return EINVAL;
4292 		}
4293 		/* Duplicate position is not allowed */
4294 		if (elm->notify_snd_una == tp->snd_una + so->so_snd.sb_cc) {
4295 			return EINVAL;
4296 		}
4297 	}
4298 	return 0;
4299 }
4300 
4301 errno_t
tcp_add_notify_ack_marker(struct tcpcb * tp,u_int32_t notify_id)4302 tcp_add_notify_ack_marker(struct tcpcb *tp, u_int32_t notify_id)
4303 {
4304 	struct tcp_notify_ack_marker *nm, *elm = NULL;
4305 	struct socket *so = tp->t_inpcb->inp_socket;
4306 
4307 	nm = kalloc_type(struct tcp_notify_ack_marker, M_WAIT | Z_ZERO);
4308 	if (nm == NULL) {
4309 		return ENOMEM;
4310 	}
4311 	nm->notify_id = notify_id;
4312 	nm->notify_snd_una = tp->snd_una + so->so_snd.sb_cc;
4313 
4314 	SLIST_FOREACH(elm, &tp->t_notify_ack, notify_next) {
4315 		if (SEQ_GT(nm->notify_snd_una, elm->notify_snd_una)) {
4316 			break;
4317 		}
4318 	}
4319 
4320 	if (elm == NULL) {
4321 		VERIFY(SLIST_EMPTY(&tp->t_notify_ack));
4322 		SLIST_INSERT_HEAD(&tp->t_notify_ack, nm, notify_next);
4323 	} else {
4324 		SLIST_INSERT_AFTER(elm, nm, notify_next);
4325 	}
4326 	tp->t_notify_ack_count++;
4327 	return 0;
4328 }
4329 
4330 void
tcp_notify_ack_free(struct tcpcb * tp)4331 tcp_notify_ack_free(struct tcpcb *tp)
4332 {
4333 	struct tcp_notify_ack_marker *elm, *next;
4334 	if (SLIST_EMPTY(&tp->t_notify_ack)) {
4335 		return;
4336 	}
4337 
4338 	SLIST_FOREACH_SAFE(elm, &tp->t_notify_ack, notify_next, next) {
4339 		SLIST_REMOVE(&tp->t_notify_ack, elm, tcp_notify_ack_marker,
4340 		    notify_next);
4341 		kfree_type(struct tcp_notify_ack_marker, elm);
4342 	}
4343 	SLIST_INIT(&tp->t_notify_ack);
4344 	tp->t_notify_ack_count = 0;
4345 }
4346 
4347 inline void
tcp_notify_acknowledgement(struct tcpcb * tp,struct socket * so)4348 tcp_notify_acknowledgement(struct tcpcb *tp, struct socket *so)
4349 {
4350 	struct tcp_notify_ack_marker *elm;
4351 
4352 	elm = SLIST_FIRST(&tp->t_notify_ack);
4353 	if (SEQ_GEQ(tp->snd_una, elm->notify_snd_una)) {
4354 		soevent(so, SO_FILT_HINT_LOCKED | SO_FILT_HINT_NOTIFY_ACK);
4355 	}
4356 }
4357 
4358 void
tcp_get_notify_ack_count(struct tcpcb * tp,struct tcp_notify_ack_complete * retid)4359 tcp_get_notify_ack_count(struct tcpcb *tp,
4360     struct tcp_notify_ack_complete *retid)
4361 {
4362 	struct tcp_notify_ack_marker *elm;
4363 	uint32_t  complete = 0;
4364 
4365 	SLIST_FOREACH(elm, &tp->t_notify_ack, notify_next) {
4366 		if (SEQ_GEQ(tp->snd_una, elm->notify_snd_una)) {
4367 			ASSERT(complete < UINT32_MAX);
4368 			complete++;
4369 		} else {
4370 			break;
4371 		}
4372 	}
4373 	retid->notify_pending = tp->t_notify_ack_count - complete;
4374 	retid->notify_complete_count = min(TCP_MAX_NOTIFY_ACK, complete);
4375 }
4376 
4377 void
tcp_get_notify_ack_ids(struct tcpcb * tp,struct tcp_notify_ack_complete * retid)4378 tcp_get_notify_ack_ids(struct tcpcb *tp,
4379     struct tcp_notify_ack_complete *retid)
4380 {
4381 	size_t i = 0;
4382 	struct tcp_notify_ack_marker *elm, *next;
4383 
4384 	SLIST_FOREACH_SAFE(elm, &tp->t_notify_ack, notify_next, next) {
4385 		if (i >= retid->notify_complete_count) {
4386 			break;
4387 		}
4388 		if (SEQ_GEQ(tp->snd_una, elm->notify_snd_una)) {
4389 			retid->notify_complete_id[i++] = elm->notify_id;
4390 			SLIST_REMOVE(&tp->t_notify_ack, elm,
4391 			    tcp_notify_ack_marker, notify_next);
4392 			kfree_type(struct tcp_notify_ack_marker, elm);
4393 			tp->t_notify_ack_count--;
4394 		} else {
4395 			break;
4396 		}
4397 	}
4398 }
4399 
4400 bool
tcp_notify_ack_active(struct socket * so)4401 tcp_notify_ack_active(struct socket *so)
4402 {
4403 	if ((SOCK_DOM(so) == PF_INET || SOCK_DOM(so) == PF_INET6) &&
4404 	    SOCK_TYPE(so) == SOCK_STREAM) {
4405 		struct tcpcb *tp = intotcpcb(sotoinpcb(so));
4406 
4407 		if (!SLIST_EMPTY(&tp->t_notify_ack)) {
4408 			struct tcp_notify_ack_marker *elm;
4409 			elm = SLIST_FIRST(&tp->t_notify_ack);
4410 			if (SEQ_GEQ(tp->snd_una, elm->notify_snd_una)) {
4411 				return true;
4412 			}
4413 		}
4414 	}
4415 	return false;
4416 }
4417 
4418 inline int32_t
inp_get_sndbytes_allunsent(struct socket * so,u_int32_t th_ack)4419 inp_get_sndbytes_allunsent(struct socket *so, u_int32_t th_ack)
4420 {
4421 	struct inpcb *inp = sotoinpcb(so);
4422 	struct tcpcb *tp = intotcpcb(inp);
4423 
4424 	if ((so->so_snd.sb_flags & SB_SNDBYTE_CNT) &&
4425 	    so->so_snd.sb_cc > 0) {
4426 		int32_t unsent, sent;
4427 		sent = tp->snd_max - th_ack;
4428 		if (tp->t_flags & TF_SENTFIN) {
4429 			sent--;
4430 		}
4431 		unsent = so->so_snd.sb_cc - sent;
4432 		return unsent;
4433 	}
4434 	return 0;
4435 }
4436 
4437 uint8_t
tcp_get_ace(struct tcphdr * th)4438 tcp_get_ace(struct tcphdr *th)
4439 {
4440 	uint8_t ace = 0;
4441 	if (th->th_flags & TH_ECE) {
4442 		ace += 1;
4443 	}
4444 	if (th->th_flags & TH_CWR) {
4445 		ace += 2;
4446 	}
4447 	if (th->th_x2 & (TH_AE >> 8)) {
4448 		ace += 4;
4449 	}
4450 
4451 	return ace;
4452 }
4453 
4454 #define IFP_PER_FLOW_STAT(_ipv4_, _stat_) { \
4455 	if (_ipv4_) { \
4456 	        ifp->if_ipv4_stat->_stat_++; \
4457 	} else { \
4458 	        ifp->if_ipv6_stat->_stat_++; \
4459 	} \
4460 }
4461 
4462 #define FLOW_ECN_ENABLED(_flags_) \
4463     ((_flags_ & (TE_ECN_ON)) == (TE_ECN_ON))
4464 
4465 void
tcp_update_stats_per_flow(struct ifnet_stats_per_flow * ifs,struct ifnet * ifp)4466 tcp_update_stats_per_flow(struct ifnet_stats_per_flow *ifs,
4467     struct ifnet *ifp)
4468 {
4469 	if (ifp == NULL || !IF_FULLY_ATTACHED(ifp)) {
4470 		return;
4471 	}
4472 
4473 	ifnet_lock_shared(ifp);
4474 	if (ifs->ecn_flags & TE_SETUPSENT) {
4475 		if (ifs->ecn_flags & TE_CLIENT_SETUP) {
4476 			IFP_PER_FLOW_STAT(ifs->ipv4, ecn_client_setup);
4477 			if (FLOW_ECN_ENABLED(ifs->ecn_flags)) {
4478 				IFP_PER_FLOW_STAT(ifs->ipv4,
4479 				    ecn_client_success);
4480 			} else if (ifs->ecn_flags & TE_LOST_SYN) {
4481 				IFP_PER_FLOW_STAT(ifs->ipv4,
4482 				    ecn_syn_lost);
4483 			} else {
4484 				IFP_PER_FLOW_STAT(ifs->ipv4,
4485 				    ecn_peer_nosupport);
4486 			}
4487 		} else {
4488 			IFP_PER_FLOW_STAT(ifs->ipv4, ecn_server_setup);
4489 			if (FLOW_ECN_ENABLED(ifs->ecn_flags)) {
4490 				IFP_PER_FLOW_STAT(ifs->ipv4,
4491 				    ecn_server_success);
4492 			} else if (ifs->ecn_flags & TE_LOST_SYN) {
4493 				IFP_PER_FLOW_STAT(ifs->ipv4,
4494 				    ecn_synack_lost);
4495 			} else {
4496 				IFP_PER_FLOW_STAT(ifs->ipv4,
4497 				    ecn_peer_nosupport);
4498 			}
4499 		}
4500 	} else {
4501 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_off_conn);
4502 	}
4503 	if (FLOW_ECN_ENABLED(ifs->ecn_flags)) {
4504 		if (ifs->ecn_flags & TE_RECV_ECN_CE) {
4505 			tcpstat.tcps_ecn_conn_recv_ce++;
4506 			IFP_PER_FLOW_STAT(ifs->ipv4, ecn_conn_recv_ce);
4507 		}
4508 		if (ifs->ecn_flags & TE_RECV_ECN_ECE) {
4509 			tcpstat.tcps_ecn_conn_recv_ece++;
4510 			IFP_PER_FLOW_STAT(ifs->ipv4, ecn_conn_recv_ece);
4511 		}
4512 		if (ifs->ecn_flags & (TE_RECV_ECN_CE | TE_RECV_ECN_ECE)) {
4513 			if (ifs->txretransmitbytes > 0 ||
4514 			    ifs->rxoutoforderbytes > 0) {
4515 				tcpstat.tcps_ecn_conn_pl_ce++;
4516 				IFP_PER_FLOW_STAT(ifs->ipv4, ecn_conn_plce);
4517 			} else {
4518 				tcpstat.tcps_ecn_conn_nopl_ce++;
4519 				IFP_PER_FLOW_STAT(ifs->ipv4, ecn_conn_noplce);
4520 			}
4521 		} else {
4522 			if (ifs->txretransmitbytes > 0 ||
4523 			    ifs->rxoutoforderbytes > 0) {
4524 				tcpstat.tcps_ecn_conn_plnoce++;
4525 				IFP_PER_FLOW_STAT(ifs->ipv4, ecn_conn_plnoce);
4526 			}
4527 		}
4528 	}
4529 
4530 	/* Other stats are interesting for non-local connections only */
4531 	if (ifs->local) {
4532 		ifnet_lock_done(ifp);
4533 		return;
4534 	}
4535 
4536 	if (ifs->ipv4) {
4537 		ifp->if_ipv4_stat->timestamp = net_uptime();
4538 		if (FLOW_ECN_ENABLED(ifs->ecn_flags)) {
4539 			tcp_flow_ecn_perf_stats(ifs, &ifp->if_ipv4_stat->ecn_on);
4540 		} else {
4541 			tcp_flow_ecn_perf_stats(ifs, &ifp->if_ipv4_stat->ecn_off);
4542 		}
4543 	} else {
4544 		ifp->if_ipv6_stat->timestamp = net_uptime();
4545 		if (FLOW_ECN_ENABLED(ifs->ecn_flags)) {
4546 			tcp_flow_ecn_perf_stats(ifs, &ifp->if_ipv6_stat->ecn_on);
4547 		} else {
4548 			tcp_flow_ecn_perf_stats(ifs, &ifp->if_ipv6_stat->ecn_off);
4549 		}
4550 	}
4551 
4552 	if (ifs->rxmit_drop) {
4553 		if (FLOW_ECN_ENABLED(ifs->ecn_flags)) {
4554 			IFP_PER_FLOW_STAT(ifs->ipv4, ecn_on.rxmit_drop);
4555 		} else {
4556 			IFP_PER_FLOW_STAT(ifs->ipv4, ecn_off.rxmit_drop);
4557 		}
4558 	}
4559 	if (ifs->ecn_fallback_synloss) {
4560 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_fallback_synloss);
4561 	}
4562 	if (ifs->ecn_fallback_droprst) {
4563 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_fallback_droprst);
4564 	}
4565 	if (ifs->ecn_fallback_droprxmt) {
4566 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_fallback_droprxmt);
4567 	}
4568 	if (ifs->ecn_fallback_ce) {
4569 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_fallback_ce);
4570 	}
4571 	if (ifs->ecn_fallback_reorder) {
4572 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_fallback_reorder);
4573 	}
4574 	if (ifs->ecn_recv_ce > 0) {
4575 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_recv_ce);
4576 	}
4577 	if (ifs->ecn_recv_ece > 0) {
4578 		IFP_PER_FLOW_STAT(ifs->ipv4, ecn_recv_ece);
4579 	}
4580 
4581 	tcp_flow_lim_stats(ifs, &ifp->if_lim_stat);
4582 	ifnet_lock_done(ifp);
4583 }
4584 
4585 #if SKYWALK
4586 
4587 #include <skywalk/core/skywalk_var.h>
4588 #include <skywalk/nexus/flowswitch/nx_flowswitch.h>
4589 
4590 void
tcp_add_fsw_flow(struct tcpcb * tp,struct ifnet * ifp)4591 tcp_add_fsw_flow(struct tcpcb *tp, struct ifnet *ifp)
4592 {
4593 	struct inpcb *inp = tp->t_inpcb;
4594 	struct socket *so = inp->inp_socket;
4595 	uuid_t fsw_uuid;
4596 	struct nx_flow_req nfr;
4597 	int err;
4598 
4599 	if (!NX_FSW_TCP_RX_AGG_ENABLED()) {
4600 		return;
4601 	}
4602 
4603 	if (ifp == NULL || kern_nexus_get_flowswitch_instance(ifp, fsw_uuid)) {
4604 		TCP_LOG_FSW_FLOW(tp, "skip ifp no fsw");
4605 		return;
4606 	}
4607 
4608 	memset(&nfr, 0, sizeof(nfr));
4609 
4610 	if (inp->inp_vflag & INP_IPV4) {
4611 		ASSERT(!(inp->inp_laddr.s_addr == INADDR_ANY ||
4612 		    inp->inp_faddr.s_addr == INADDR_ANY ||
4613 		    IN_MULTICAST(ntohl(inp->inp_laddr.s_addr)) ||
4614 		    IN_MULTICAST(ntohl(inp->inp_faddr.s_addr))));
4615 		nfr.nfr_saddr.sin.sin_len = sizeof(struct sockaddr_in);
4616 		nfr.nfr_saddr.sin.sin_family = AF_INET;
4617 		nfr.nfr_saddr.sin.sin_port = inp->inp_lport;
4618 		memcpy(&nfr.nfr_saddr.sin.sin_addr, &inp->inp_laddr,
4619 		    sizeof(struct in_addr));
4620 		nfr.nfr_daddr.sin.sin_len = sizeof(struct sockaddr_in);
4621 		nfr.nfr_daddr.sin.sin_family = AF_INET;
4622 		nfr.nfr_daddr.sin.sin_port = inp->inp_fport;
4623 		memcpy(&nfr.nfr_daddr.sin.sin_addr, &inp->inp_faddr,
4624 		    sizeof(struct in_addr));
4625 	} else {
4626 		ASSERT(!(IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ||
4627 		    IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) ||
4628 		    IN6_IS_ADDR_MULTICAST(&inp->in6p_laddr) ||
4629 		    IN6_IS_ADDR_MULTICAST(&inp->in6p_faddr)));
4630 		nfr.nfr_saddr.sin6.sin6_len = sizeof(struct sockaddr_in6);
4631 		nfr.nfr_saddr.sin6.sin6_family = AF_INET6;
4632 		nfr.nfr_saddr.sin6.sin6_port = inp->inp_lport;
4633 		memcpy(&nfr.nfr_saddr.sin6.sin6_addr, &inp->in6p_laddr,
4634 		    sizeof(struct in6_addr));
4635 		nfr.nfr_daddr.sin6.sin6_len = sizeof(struct sockaddr_in6);
4636 		nfr.nfr_daddr.sin.sin_family = AF_INET6;
4637 		nfr.nfr_daddr.sin6.sin6_port = inp->inp_fport;
4638 		memcpy(&nfr.nfr_daddr.sin6.sin6_addr, &inp->in6p_faddr,
4639 		    sizeof(struct in6_addr));
4640 		/* clear embedded scope ID */
4641 		if (IN6_IS_SCOPE_EMBED(&nfr.nfr_saddr.sin6.sin6_addr)) {
4642 			nfr.nfr_saddr.sin6.sin6_addr.s6_addr16[1] = 0;
4643 		}
4644 		if (IN6_IS_SCOPE_EMBED(&nfr.nfr_daddr.sin6.sin6_addr)) {
4645 			nfr.nfr_daddr.sin6.sin6_addr.s6_addr16[1] = 0;
4646 		}
4647 	}
4648 
4649 	nfr.nfr_nx_port = 1;
4650 	nfr.nfr_ip_protocol = IPPROTO_TCP;
4651 	nfr.nfr_transport_protocol = IPPROTO_TCP;
4652 	nfr.nfr_flags = NXFLOWREQF_ASIS;
4653 	nfr.nfr_epid = (so != NULL ? so->last_pid : 0);
4654 	if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
4655 		nfr.nfr_port_reservation = inp->inp_netns_token;
4656 		nfr.nfr_flags |= NXFLOWREQF_EXT_PORT_RSV;
4657 	}
4658 	ASSERT(inp->inp_flowhash != 0);
4659 	nfr.nfr_inp_flowhash = inp->inp_flowhash;
4660 
4661 	uuid_generate_random(nfr.nfr_flow_uuid);
4662 	err = kern_nexus_flow_add(kern_nexus_shared_controller(), fsw_uuid,
4663 	    &nfr, sizeof(nfr));
4664 
4665 	if (err == 0) {
4666 		uuid_copy(tp->t_fsw_uuid, fsw_uuid);
4667 		uuid_copy(tp->t_flow_uuid, nfr.nfr_flow_uuid);
4668 	}
4669 
4670 	TCP_LOG_FSW_FLOW(tp, "add err %d\n", err);
4671 }
4672 
4673 void
tcp_del_fsw_flow(struct tcpcb * tp)4674 tcp_del_fsw_flow(struct tcpcb *tp)
4675 {
4676 	if (uuid_is_null(tp->t_fsw_uuid) || uuid_is_null(tp->t_flow_uuid)) {
4677 		return;
4678 	}
4679 
4680 	struct nx_flow_req nfr;
4681 	uuid_copy(nfr.nfr_flow_uuid, tp->t_flow_uuid);
4682 
4683 	/* It's possible for this call to fail if the nexus has detached */
4684 	int err = kern_nexus_flow_del(kern_nexus_shared_controller(),
4685 	    tp->t_fsw_uuid, &nfr, sizeof(nfr));
4686 	VERIFY(err == 0 || err == ENOENT || err == ENXIO);
4687 
4688 	uuid_clear(tp->t_fsw_uuid);
4689 	uuid_clear(tp->t_flow_uuid);
4690 
4691 	TCP_LOG_FSW_FLOW(tp, "del err %d\n", err);
4692 }
4693 
4694 #endif /* SKYWALK */
4695