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