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