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