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