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