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