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