2 * Copyright (c) 2000-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
30 * The Regents of the University of California. All rights reserved.
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
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.
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
60 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95
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,
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>
76 #include <sys/domain.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>
88 #include <dev/random/randomdev.h>
90 #include <net/route.h>
92 #include <net/content_filter.h>
94 #define tcp_minmssoverload fring
96 #include <netinet/in.h>
97 #include <netinet/in_systm.h>
98 #include <netinet/ip.h>
99 #include <netinet/ip_icmp.h>
101 #include <netinet/ip6.h>
103 #include <netinet/in_pcb.h>
105 #include <netinet6/in6_pcb.h>
107 #include <netinet/in_var.h>
108 #include <netinet/ip_var.h>
109 #include <netinet/icmp_var.h>
111 #include <netinet6/ip6_var.h>
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>
123 #include <netinet6/tcp6_var.h>
125 #include <netinet/tcpip.h>
127 #include <netinet/tcp_debug.h>
129 #include <netinet6/ip6protosw.h>
132 #include <netinet6/ipsec.h>
134 #include <netinet6/ipsec6.h>
139 #include <net/necp.h>
142 #undef tcp_minmssoverload
145 #include <security/mac_framework.h>
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>
154 #include <netinet/lro_ext.h>
156 #define DBG_FNC_TCP_CLOSE NETDBG_CODE(DBG_NETTCP, ((5 << 8) | 2))
158 extern int tcp_lq_overflow
;
160 extern struct tcptimerlist tcp_timer_list
;
161 extern struct tcptailq tcp_tw_tailq
;
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");
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");
174 extern int tcp_do_autorcvbuf
;
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");
181 /* Current count of half-open TFO connections */
182 int tcp_tfo_halfcnt
= 0;
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");
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)");
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");
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.
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) */
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");
223 static int do_tcpdrain
= 0;
224 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, do_tcpdrain
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
226 "Enable tcp_drain routine for extra help when low on mbufs");
228 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, pcbcount
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
229 &tcbinfo
.ipi_count
, 0, "Number of active PCBs");
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");
234 static int icmp_may_rst
= 1;
235 SYSCTL_INT(_net_inet_tcp
, OID_AUTO
, icmp_may_rst
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
237 "Certain ICMP unreachable messages may abort connections in SYN_SENT");
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");
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) */
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");
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");
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");
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");
268 static void tcp_cleartaocache(void);
269 static void tcp_notify(struct inpcb
*, int);
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
;
276 extern int slowlink_wsize
; /* window correction for slow links */
277 extern int path_mtu_discovery
;
279 static void tcp_sbrcv_grow_rwin(struct tcpcb
*tp
, struct sockbuf
*sb
);
281 #define TCP_BWMEAS_BURST_MINSIZE 6
282 #define TCP_BWMEAS_BURST_MAXSIZE 25
284 static uint32_t bwmeas_elm_size
;
287 * Target size of TCP PCB hash tables. Must be a power of two.
289 * Note that this can be overridden by the kernel environment
290 * variable net.inet.tcp.tcbhashsize
293 #define TCBHASHSIZE CONFIG_TCBHASHSIZE
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");
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).
311 struct tcpcb tcb
__attribute__((aligned(ALIGNMENT
)));
315 int get_inpcb_str_size(void);
316 int get_tcp_str_size(void);
318 static void tcpcb_to_otcpcb(struct tcpcb
*, struct otcpcb
*);
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
);
325 static aes_encrypt_ctx tfo_ctx
; /* Crypto-context for TFO */
328 tcp_tfo_gen_cookie(struct inpcb
*inp
, u_char
*out
, size_t blk_size
)
330 u_char in
[CCAES_BLOCK_SIZE
];
332 int isipv6
= inp
->inp_vflag
& INP_IPV6
;
335 VERIFY(blk_size
== CCAES_BLOCK_SIZE
);
337 bzero(&in
[0], CCAES_BLOCK_SIZE
);
338 bzero(&out
[0], CCAES_BLOCK_SIZE
);
342 memcpy(in
, &inp
->in6p_faddr
, sizeof(struct in6_addr
));
345 memcpy(in
, &inp
->inp_faddr
, sizeof(struct in_addr
));
347 aes_encrypt_cbc(in
, NULL
, 1, out
, &tfo_ctx
);
350 __private_extern__
int
351 tcp_sysctl_fastopenkey(__unused
struct sysctl_oid
*oidp
, __unused
void *arg1
,
352 __unused
int arg2
, struct sysctl_req
*req
)
356 * TFO-key is expressed as a string in hex format
357 * (+1 to account for \0 char)
359 char keystring
[TCP_FASTOPEN_KEYLEN
* 2 + 1];
360 u_int32_t key
[TCP_FASTOPEN_KEYLEN
/ sizeof(u_int32_t
)];
363 /* -1, because newlen is len without the terminating \0 character */
364 if (req
->newlen
!= (sizeof(keystring
) - 1)) {
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
374 bzero(keystring
, sizeof(keystring
));
376 error
= sysctl_io_string(req
, keystring
, sizeof(keystring
), 0, NULL
);
380 for (i
= 0; i
< (TCP_FASTOPEN_KEYLEN
/ sizeof(u_int32_t
)); i
++) {
382 * We jump over the keystring in 8-character (4 byte in hex)
385 if (sscanf(&keystring
[i
* 8], "%8x", &key
[i
]) != 1) {
391 aes_encrypt_key128((u_char
*)key
, &tfo_ctx
);
398 get_inpcb_str_size(void)
400 return (sizeof(struct inpcb
));
404 get_tcp_str_size(void)
406 return (sizeof(struct tcpcb
));
409 int tcp_freeq(struct tcpcb
*tp
);
411 static int scale_to_powerof2(int size
);
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.
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
421 * 3. Same value as argument size if it is already a power of two.
424 scale_to_powerof2(int size
) {
425 /* Handle special case of size = 0 */
426 int ret
= size
? size
: 1;
428 if (!powerof2(ret
)) {
429 while (!powerof2(size
)) {
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.
436 size
= size
& (size
-1);
439 /* Check for overflow when rounding up */
440 if (0 == (size
<< 1)) {
453 u_char key
[TCP_FASTOPEN_KEYLEN
];
455 read_random(key
, sizeof(key
));
456 aes_encrypt_key128(key
, &tfo_ctx
);
463 tcp_init(struct protosw
*pp
, struct domain
*dp
)
466 static int tcp_initialized
= 0;
468 struct inpcbinfo
*pcbinfo
;
470 VERIFY((pp
->pr_flags
& (PR_INITIALIZED
|PR_ATTACHED
)) == PR_ATTACHED
);
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
;
486 microuptime(&tcp_uptime
);
487 read_random(&tcp_now
, sizeof(tcp_now
));
489 /* Starts tcp internal clock at a random value */
490 tcp_now
= tcp_now
& 0x3fffffff;
495 tcbinfo
.ipi_listhead
= &tcb
;
499 * allocate lock group attribute and group for tcp pcb mutexes
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
);
506 * allocate the lock attribute for tcp pcb mutexes
508 pcbinfo
->ipi_lock_attr
= lck_attr_alloc_init();
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__
);
516 if (tcp_tcbhashsize
== 0) {
518 tcp_tcbhashsize
= 512;
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;
528 printf("WARNING: TCB hash size not a power of 2, "
529 "scaled from %d to %d.\n",
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
);
543 tcbinfo
.ipi_gc
= tcp_gc
;
544 tcbinfo
.ipi_timer
= tcp_itimer
;
545 in_pcbinfo_attach(&tcbinfo
);
547 str_size
= P2ROUNDUP(sizeof(struct sackhole
), sizeof(u_int64_t
));
548 sack_hole_zone
= zinit(str_size
, 120000*str_size
, 8192,
550 zone_change(sack_hole_zone
, Z_CALLERACCT
, FALSE
);
551 zone_change(sack_hole_zone
, Z_EXPAND
, TRUE
);
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__
);
560 zone_change(tcp_reass_zone
, Z_CALLERACCT
, FALSE
);
561 zone_change(tcp_reass_zone
, Z_EXPAND
, TRUE
);
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,
566 if (tcp_bwmeas_zone
== NULL
) {
567 panic("%s: failed allocating tcp_bwmeas_zone", __func__
);
570 zone_change(tcp_bwmeas_zone
, Z_CALLERACCT
, FALSE
);
571 zone_change(tcp_bwmeas_zone
, Z_EXPAND
, TRUE
);
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
);
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,
581 zone_change(tcp_rxt_seg_zone
, Z_CALLERACCT
, FALSE
);
582 zone_change(tcp_rxt_seg_zone
, Z_EXPAND
, TRUE
);
585 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
587 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
589 if (max_protohdr
< TCP_MINPROTOHDR
) {
590 _max_protohdr
= TCP_MINPROTOHDR
;
591 _max_protohdr
= max_protohdr
; /* round it up */
593 if (max_linkhdr
+ max_protohdr
> MCLBYTES
)
595 #undef TCP_MINPROTOHDR
597 /* Initialize time wait and timer lists */
598 TAILQ_INIT(&tcp_tw_tailq
);
600 bzero(&tcp_timer_list
, sizeof(tcp_timer_list
));
601 LIST_INIT(&tcp_timer_list
.lhead
);
603 * allocate lock group attribute, group and attribute for
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");
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");
620 * allocate lock group attribute, group and attribute for
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
);
630 /* Initialize TCP LRO data structures */
633 /* Initialize TCP Cache */
637 * If more than 60 MB of mbuf pool is available, increase the
638 * maximum allowed receive and send socket buffer size.
640 if (nmbclusters
> 30720) {
641 tcp_autorcvbuf_max
= 1024 * 1024;
642 tcp_autosndbuf_max
= 1024 * 1024;
645 * Receive buffer max for cellular interfaces supporting
646 * Carrier Aggregation is higher
648 tcp_autorcvbuf_max_ca
= 2 * 1024 * 1024;
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.
658 tcp_fillheaders(struct tcpcb
*tp
, void *ip_ptr
, void *tcp_ptr
)
660 struct inpcb
*inp
= tp
->t_inpcb
;
661 struct tcphdr
*tcp_hdr
= (struct tcphdr
*)tcp_ptr
;
664 if ((inp
->inp_vflag
& INP_IPV6
) != 0) {
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
;
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
));
682 struct ip
*ip
= (struct ip
*) ip_ptr
;
684 ip
->ip_vhl
= IP_VHL_BORING
;
691 ip
->ip_p
= IPPROTO_TCP
;
692 ip
->ip_src
= inp
->inp_laddr
;
693 ip
->ip_dst
= inp
->inp_faddr
;
695 in_pseudo(ip
->ip_src
.s_addr
, ip
->ip_dst
.s_addr
,
696 htons(sizeof(struct tcphdr
) + IPPROTO_TCP
));
699 tcp_hdr
->th_sport
= inp
->inp_lport
;
700 tcp_hdr
->th_dport
= inp
->inp_fport
;
705 tcp_hdr
->th_flags
= 0;
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.
716 tcp_maketemplate(struct tcpcb
*tp
)
721 m
= m_get(M_DONTWAIT
, MT_HEADER
);
724 m
->m_len
= sizeof(struct tcptemp
);
725 n
= mtod(m
, struct tcptemp
*);
727 tcp_fillheaders(tp
, (void *)&n
->tt_ipgen
, (void *)&n
->tt_t
);
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.
740 * In any case the ack and sequence number of the transmitted
741 * segment are as specified by the parameters.
743 * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
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
)
751 struct route
*ro
= 0;
756 struct route_in6
*ro6
= 0;
757 struct route_in6 sro6
;
762 int sotc
= SO_TC_UNSPEC
;
765 isipv6
= IP_VHL_V(((struct ip
*)ipgen
)->ip_vhl
) == 6;
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
;
778 ro6
= &tp
->t_inpcb
->in6p_route
;
781 ro
= &tp
->t_inpcb
->inp_route
;
786 bzero(ro6
, sizeof(*ro6
));
791 bzero(ro
, sizeof(*ro
));
795 m
= m_gethdr(M_DONTWAIT
, MT_HEADER
); /* MAC-OK */
799 m
->m_data
+= max_linkhdr
;
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);
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);
817 bcopy((caddr_t
)th
, (caddr_t
)nth
, sizeof(struct tcphdr
));
819 if ((tp
) && (tp
->t_mpflags
& TMPF_RESET
))
820 flags
= (TH_RST
| TH_ACK
);
827 m
->m_data
= (caddr_t
)ipgen
;
828 /* m_len is set later */
830 #define xchg(a, b, type) { type t; t = a; a = b; b = t; }
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);
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);
847 * this is usually a case when an extension header
848 * exists between the IPv6 header and the
851 nth
->th_sport
= th
->th_sport
;
852 nth
->th_dport
= th
->th_dport
;
854 xchg(nth
->th_dport
, nth
->th_sport
, n_short
);
859 ip6
->ip6_plen
= htons((u_short
)(sizeof (struct tcphdr
) +
861 tlen
+= sizeof (struct ip6_hdr
) + sizeof (struct tcphdr
);
865 tlen
+= sizeof (struct tcpiphdr
);
867 ip
->ip_ttl
= ip_defttl
;
870 m
->m_pkthdr
.len
= tlen
;
871 m
->m_pkthdr
.rcvif
= 0;
873 if (tp
!= NULL
&& tp
->t_inpcb
!= NULL
) {
875 * Packet is associated with a socket, so allow the
876 * label of the response to reflect the socket label.
878 mac_mbuf_label_associate_inpcb(tp
->t_inpcb
, m
);
881 * Packet is not associated with a socket, so possibly
882 * update the label in place.
884 mac_netinet_tcp_reply(m
);
888 nth
->th_seq
= htonl(seq
);
889 nth
->th_ack
= htonl(ack
);
891 nth
->th_off
= sizeof (struct tcphdr
) >> 2;
892 nth
->th_flags
= flags
;
894 nth
->th_win
= htons((u_short
) (win
>> tp
->rcv_scale
));
896 nth
->th_win
= htons((u_short
)win
);
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
);
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
);
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);
921 necp_mark_packet_from_socket(m
, tp
? tp
->t_inpcb
: NULL
, 0, 0);
925 if (tp
!= NULL
&& tp
->t_inpcb
->inp_sp
!= NULL
&&
926 ipsec_setsocket(m
, tp
? tp
->t_inpcb
->inp_socket
: NULL
) != 0) {
933 u_int32_t svc_flags
= 0;
935 svc_flags
|= PKT_SCF_IPV6
;
937 sotc
= tp
->t_inpcb
->inp_socket
->so_traffic_class
;
938 set_packet_service_class(m
, tp
->t_inpcb
->inp_socket
,
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
;
946 /* Disable flow advisory when using MPTCP. */
947 if (!(tp
->t_mpflags
& TMPF_MPTCP_TRUE
))
949 m
->m_pkthdr
.pkt_flags
|= PKTF_FLOW_ADV
;
950 m
->m_pkthdr
.pkt_proto
= IPPROTO_TCP
;
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
};
959 if (tra
->ifscope
!= IFSCOPE_NONE
)
960 ip6oa
.ip6oa_flags
|= IP6OAF_BOUND_IF
;
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
;
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
;
975 (void) ip6_output(m
, NULL
, ro6
, IPV6_OUTARGS
, NULL
,
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
;
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
};
992 if (tra
->ifscope
!= IFSCOPE_NONE
)
993 ipoa
.ipoa_flags
|= IPOAF_BOUND_IF
;
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
;
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
;
1007 /* Copy the cached route and take an extra reference */
1008 inp_route_copyout(tp
->t_inpcb
, &sro
);
1011 * For consistency, pass a local route copy.
1013 (void) ip_output(m
, NULL
, &sro
, IP_OUTARGS
, NULL
, &ipoa
);
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
;
1021 /* Synchronize cached PCB route */
1022 inp_route_copyin(tp
->t_inpcb
, &sro
);
1024 ROUTE_RELEASE(&sro
);
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().
1036 tcp_newtcpcb(struct inpcb
*inp
)
1040 struct socket
*so
= inp
->inp_socket
;
1042 int isipv6
= (inp
->inp_vflag
& INP_IPV6
) != 0;
1045 calculate_tcp_clock();
1047 if ((so
->so_flags1
& SOF1_CACHED_IN_SOCK_LAYER
) == 0) {
1048 it
= (struct inp_tp
*)(void *)inp
;
1051 tp
= (struct tcpcb
*)(void *)inp
->inp_saved_ppcb
;
1054 bzero((char *) tp
, sizeof(struct tcpcb
));
1055 LIST_INIT(&tp
->t_segq
);
1056 tp
->t_maxseg
= tp
->t_maxopd
=
1058 isipv6
? tcp_v6mssdflt
:
1063 tp
->t_flags
= (TF_REQ_SCALE
|TF_REQ_TSTMP
);
1065 tp
->t_flagsext
|= TF_SACK_ENABLE
;
1067 TAILQ_INIT(&tp
->snd_holes
);
1068 SLIST_INIT(&tp
->t_rxt_segments
);
1069 SLIST_INIT(&tp
->t_notify_ack
);
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.
1076 tp
->t_srtt
= TCPTV_SRTTBASE
;
1078 ((TCPTV_RTOBASE
- TCPTV_SRTTBASE
) << TCP_RTTVAR_SHIFT
) / 4;
1079 tp
->t_rttmin
= tcp_TCPTV_MIN
;
1080 tp
->t_rxtcur
= TCPTV_RTOBASE
;
1082 if (tcp_use_newreno
)
1083 /* use newreno by default */
1084 tp
->tcp_cc_index
= TCP_CC_ALGO_NEWRENO_INDEX
;
1086 tp
->tcp_cc_index
= TCP_CC_ALGO_CUBIC_INDEX
;
1088 tcp_cc_allocate_state(tp
);
1090 if (CC_ALGO(tp
)->init
!= NULL
)
1091 CC_ALGO(tp
)->init(tp
);
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
;
1103 /* Clear time wait tailq entry */
1104 tp
->t_twentry
.tqe_next
= NULL
;
1105 tp
->t_twentry
.tqe_prev
= NULL
;
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.
1112 inp
->inp_ip_ttl
= ip_defttl
;
1113 inp
->inp_ppcb
= (caddr_t
)tp
;
1114 return (tp
); /* XXX */
1118 * Drop a TCP connection, reporting
1119 * the specified error. If connection is synchronized,
1120 * then send a RST to peer.
1123 tcp_drop(struct tcpcb
*tp
, int errno
)
1125 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
1127 struct inpcb
*inp
= tp
->t_inpcb
;
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
++;
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
));
1145 tcp_getrt_rtt(struct tcpcb
*tp
, struct rtentry
*rt
)
1147 u_int32_t rtt
= rt
->rt_rmx
.rmx_rtt
;
1148 int isnetlocal
= (tp
->t_flags
& TF_LOCAL
);
1152 * XXX the lock bit for RTT indicates that the value
1153 * is also a minimum value; this is subject to time.
1155 if (rt
->rt_rmx
.rmx_locks
& RTV_RTT
)
1156 tp
->t_rttmin
= rtt
/ (RTM_RTTUNIT
/ TCP_RETRANSHZ
);
1158 tp
->t_rttmin
= isnetlocal
? tcp_TCPTV_MIN
:
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
++;
1168 /* default variation is +- 1 rtt */
1170 tp
->t_srtt
* TCP_RTTVAR_SCALE
/ TCP_RTT_SCALE
;
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
));
1180 tcp_update_ecn_perf_stats(struct tcpcb
*tp
,
1181 struct if_tcp_ecn_perf_stat
*stat
)
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
);
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
;
1198 oldval
= stat
->rtt_avg
;
1200 ((oldval
<< 4) - oldval
+ curval
) >> 4;
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
;
1210 oldval
= stat
->rtt_var
;
1212 ((oldval
<< 4) - oldval
+ curval
) >> 4;
1216 /* Total number of SACK recovery episodes */
1217 stat
->sack_episodes
+= tp
->t_sack_recovery_episode
;
1219 if (inp
->inp_socket
->so_error
== ECONNRESET
)
1224 * Close a TCP control block:
1225 * discard all space held by the tcp
1226 * discard internet protocol block
1227 * wake up any sleepers
1230 tcp_close(struct tcpcb
*tp
)
1232 struct inpcb
*inp
= tp
->t_inpcb
;
1233 struct socket
*so
= inp
->inp_socket
;
1235 int isipv6
= (inp
->inp_vflag
& INP_IPV6
) != 0;
1241 /* tcp_close was called previously, bail */
1242 if (inp
->inp_ppcb
== NULL
)
1245 tcp_canceltimers(tp
);
1246 KERNEL_DEBUG(DBG_FNC_TCP_CLOSE
| DBG_FUNC_START
, tp
, 0, 0, 0, 0);
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
1260 if ((tp
->t_flags
& TF_CLOSING
) ||
1261 inp
->inp_sndinprog_cnt
> 0) {
1262 tp
->t_flags
|= TF_CLOSING
;
1266 DTRACE_TCP4(state__change
, void, NULL
, struct inpcb
*, inp
,
1267 struct tcpcb
*, tp
, int32_t, TCPS_CLOSED
);
1270 ro
= (isipv6
? (struct route
*)&inp
->in6p_route
: &inp
->inp_route
);
1272 ro
= &inp
->inp_route
;
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.
1286 * Don't update the default route's characteristics and don't
1287 * update anything that the user "locked".
1289 if (tp
->t_rttupdated
>= 16) {
1294 struct sockaddr_in6
*sin6
;
1298 sin6
= (struct sockaddr_in6
*)(void *)rt_key(rt
);
1299 if (IN6_IS_ADDR_UNSPECIFIED(&sin6
->sin6_addr
))
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
;
1313 RT_LOCK_ASSERT_HELD(rt
);
1314 if ((rt
->rt_rmx
.rmx_locks
& RTV_RTT
) == 0) {
1316 (RTM_RTTUNIT
/ (TCP_RETRANSHZ
* TCP_RTT_SCALE
));
1317 if (rt
->rt_rmx
.rmx_rtt
&& i
)
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.
1324 rt
->rt_rmx
.rmx_rtt
=
1325 (rt
->rt_rmx
.rmx_rtt
+ i
) / 2;
1327 rt
->rt_rmx
.rmx_rtt
= i
;
1328 tcpstat
.tcps_cachedrtt
++;
1330 if ((rt
->rt_rmx
.rmx_locks
& RTV_RTTVAR
) == 0) {
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;
1337 rt
->rt_rmx
.rmx_rttvar
= i
;
1338 tcpstat
.tcps_cachedrttvar
++;
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
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.
1354 i
= tp
->snd_ssthresh
;
1355 if (rt
->rt_rmx
.rmx_sendpipe
!= 0)
1356 dosavessthresh
= (i
< rt
->rt_rmx
.rmx_sendpipe
/ 2);
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) ||
1363 * convert the limit from user data bytes to
1364 * packets then to packet data bytes.
1366 i
= (i
+ tp
->t_maxseg
/ 2) / tp
->t_maxseg
;
1369 i
*= (u_int32_t
)(tp
->t_maxseg
+
1371 isipv6
? sizeof (struct ip6_hdr
) +
1372 sizeof (struct tcphdr
) :
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;
1379 rt
->rt_rmx
.rmx_ssthresh
= i
;
1380 tcpstat
.tcps_cachedssthresh
++;
1385 * Mark route for deletion if no information is cached.
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
;
1398 /* free the reassembly queue, if any */
1399 (void) tcp_freeq(tp
);
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
);
1411 INP_INC_IFNET_STAT(inp
,
1412 ecn_peer_nosupport
);
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
,
1423 INP_INC_IFNET_STAT(inp
,
1424 ecn_peer_nosupport
);
1428 INP_INC_IFNET_STAT(inp
, ecn_off_conn
);
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
);
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
);
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
);
1445 tcpstat
.tcps_ecn_conn_nopl_ce
++;
1446 INP_INC_IFNET_STAT(inp
, ecn_conn_noplce
);
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
);
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
)) ==
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
);
1469 tcp_update_ecn_perf_stats(tp
,
1470 &ifp
->if_ipv6_stat
->ecn_off
);
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
);
1478 tcp_update_ecn_perf_stats(tp
,
1479 &ifp
->if_ipv4_stat
->ecn_off
);
1483 ifnet_lock_done(ifp
);
1486 tcp_free_sackholes(tp
);
1487 tcp_notify_ack_free(tp
);
1489 inp_decr_sndbytes_allunsent(so
, tp
->snd_una
);
1491 if (tp
->t_bwmeas
!= NULL
) {
1492 tcp_bwmeas_free(tp
);
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
);
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
));
1510 if (so
->so_flags1
& SOF1_CACHED_IN_SOCK_LAYER
)
1511 inp
->inp_saved_ppcb
= (caddr_t
) tp
;
1513 tp
->t_state
= TCPS_CLOSED
;
1516 * Issue a wakeup before detach so that we don't miss
1519 sodisconnectwakeup(so
);
1522 * Clean up any LRO state
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
;
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.
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
);
1540 if (CC_ALGO(tp
)->cleanup
!= NULL
) {
1541 CC_ALGO(tp
)->cleanup(tp
);
1544 if (tp
->t_ccstate
!= NULL
) {
1545 zfree(tcp_cc_zone
, tp
->t_ccstate
);
1546 tp
->t_ccstate
= NULL
;
1548 tp
->tcp_cc_index
= TCP_CC_ALGO_NONE
;
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
);
1554 /* Panic if something has gone terribly wrong. */
1555 VERIFY(tcp_tfo_halfcnt
>= 0);
1557 tp
->t_tfo_flags
&= ~TFO_F_COOKIE_VALID
;
1561 if (SOCK_CHECK_DOM(so
, PF_INET6
))
1568 * Call soisdisconnected after detach because it might unlock the socket
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);
1578 tcp_freeq(struct tcpcb
*tp
)
1580 struct tseg_qent
*q
;
1583 while ((q
= LIST_FIRST(&tp
->t_segq
)) != NULL
) {
1584 LIST_REMOVE(q
, tqe_q
);
1586 zfree(tcp_reass_zone
, q
);
1589 tp
->t_reassqlen
= 0;
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
1606 if (!lck_rw_try_lock_exclusive(tcbinfo
.ipi_lock
))
1609 LIST_FOREACH(inp
, tcbinfo
.ipi_listhead
, inp_list
) {
1610 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) !=
1612 tcp_lock(inp
->inp_socket
, 1, 0);
1613 if (in_pcb_checkstate(inp
, WNT_RELEASE
, 1)
1615 /* lost a race, try the next one */
1616 tcp_unlock(inp
->inp_socket
, 1, 0);
1619 tp
= intotcpcb(inp
);
1624 so_drain_extended_bk_idle(inp
->inp_socket
);
1626 tcp_unlock(inp
->inp_socket
, 1, 0);
1629 lck_rw_done(tcbinfo
.ipi_lock
);
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).
1638 * Do not wake up user since there currently is no mechanism for
1639 * reporting soft errors (yet - a kqueue filter may be added).
1642 tcp_notify(struct inpcb
*inp
, int error
)
1646 if (inp
== NULL
|| (inp
->inp_state
== INPCB_STATE_DEAD
))
1647 return; /* pcb is gone already */
1649 tp
= (struct tcpcb
*)inp
->inp_ppcb
;
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.
1658 if (tp
->t_state
== TCPS_ESTABLISHED
&&
1659 (error
== EHOSTUNREACH
|| error
== ENETUNREACH
||
1660 error
== EHOSTDOWN
)) {
1662 } else if (tp
->t_state
< TCPS_ESTABLISHED
&& tp
->t_rxtshift
> 3 &&
1664 tcp_drop(tp
, error
);
1666 tp
->t_softerror
= error
;
1668 wakeup((caddr_t
) &so
->so_timeo
);
1675 tcp_bwmeas_alloc(struct tcpcb
*tp
)
1678 elm
= zalloc(tcp_bwmeas_zone
);
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
;
1691 tcp_bwmeas_free(struct tcpcb
*tp
)
1693 zfree(tcp_bwmeas_zone
, tp
->t_bwmeas
);
1694 tp
->t_bwmeas
= NULL
;
1695 tp
->t_flagsext
&= ~(TF_MEASURESNDBW
);
1699 get_tcp_inp_list(struct inpcb
**inp_list
, int n
, inp_gen_t gencnt
)
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
;
1713 TAILQ_FOREACH(tp
, &tcp_tw_tailq
, t_twentry
) {
1715 if (inp
->inp_gencnt
<= gencnt
&&
1716 inp
->inp_state
!= INPCB_STATE_DEAD
)
1717 inp_list
[i
++] = inp
;
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.
1729 tcpcb_to_otcpcb(struct tcpcb
*tp
, struct otcpcb
*otp
)
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
];
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
;
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
;
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;
1789 tcp_pcblist SYSCTL_HANDLER_ARGS
1791 #pragma unused(oidp, arg1, arg2)
1792 int error
, i
= 0, n
;
1793 struct inpcb
**inp_list
;
1798 * The process of preparing the TCB list is too time-consuming and
1799 * resource-intensive to repeat twice on every request.
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
);
1810 if (req
->newptr
!= USER_ADDR_NULL
) {
1811 lck_rw_done(tcbinfo
.ipi_lock
);
1816 * OK, now we're committed to doing something.
1818 gencnt
= tcbinfo
.ipi_gencnt
;
1819 n
= tcbinfo
.ipi_count
;
1821 bzero(&xig
, sizeof(xig
));
1822 xig
.xig_len
= sizeof(xig
);
1824 xig
.xig_gen
= gencnt
;
1825 xig
.xig_sogen
= so_gencnt
;
1826 error
= SYSCTL_OUT(req
, &xig
, sizeof(xig
));
1828 lck_rw_done(tcbinfo
.ipi_lock
);
1832 * We are done if there is no pcb
1835 lck_rw_done(tcbinfo
.ipi_lock
);
1839 inp_list
= _MALLOC(n
* sizeof (*inp_list
), M_TEMP
, M_WAITOK
);
1840 if (inp_list
== 0) {
1841 lck_rw_done(tcbinfo
.ipi_lock
);
1845 n
= get_tcp_inp_list(inp_list
, n
, gencnt
);
1848 for (i
= 0; i
< n
; i
++) {
1855 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) == WNT_STOPUSING
)
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
);
1862 if (inp
->inp_gencnt
> gencnt
) {
1863 tcp_unlock(inp
->inp_socket
, 1, NULL
);
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
,
1876 bzero((char *) &xt
.xt_tp
, sizeof(xt
.xt_tp
));
1878 if (inp
->inp_socket
)
1879 sotoxsocket(inp
->inp_socket
, &xt
.xt_socket
);
1881 tcp_unlock(inp
->inp_socket
, 1, NULL
);
1883 error
= SYSCTL_OUT(req
, &xt
, sizeof(xt
));
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.
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
));
1900 FREE(inp_list
, M_TEMP
);
1901 lck_rw_done(tcbinfo
.ipi_lock
);
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");
1911 tcpcb_to_xtcpcb64(struct tcpcb
*tp
, struct xtcpcb64
*otp
)
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
;
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
;
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;
1970 tcp_pcblist64 SYSCTL_HANDLER_ARGS
1972 #pragma unused(oidp, arg1, arg2)
1973 int error
, i
= 0, n
;
1974 struct inpcb
**inp_list
;
1979 * The process of preparing the TCB list is too time-consuming and
1980 * resource-intensive to repeat twice on every request.
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
);
1991 if (req
->newptr
!= USER_ADDR_NULL
) {
1992 lck_rw_done(tcbinfo
.ipi_lock
);
1997 * OK, now we're committed to doing something.
1999 gencnt
= tcbinfo
.ipi_gencnt
;
2000 n
= tcbinfo
.ipi_count
;
2002 bzero(&xig
, sizeof(xig
));
2003 xig
.xig_len
= sizeof(xig
);
2005 xig
.xig_gen
= gencnt
;
2006 xig
.xig_sogen
= so_gencnt
;
2007 error
= SYSCTL_OUT(req
, &xig
, sizeof(xig
));
2009 lck_rw_done(tcbinfo
.ipi_lock
);
2013 * We are done if there is no pcb
2016 lck_rw_done(tcbinfo
.ipi_lock
);
2020 inp_list
= _MALLOC(n
* sizeof (*inp_list
), M_TEMP
, M_WAITOK
);
2021 if (inp_list
== 0) {
2022 lck_rw_done(tcbinfo
.ipi_lock
);
2026 n
= get_tcp_inp_list(inp_list
, n
, gencnt
);
2029 for (i
= 0; i
< n
; i
++) {
2035 if (in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) == WNT_STOPUSING
)
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
);
2042 if (inp
->inp_gencnt
> gencnt
) {
2043 tcp_unlock(inp
->inp_socket
, 1, NULL
);
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
,
2055 if (inp
->inp_socket
)
2056 sotoxsocket64(inp
->inp_socket
,
2057 &xt
.xt_inpcb
.xi_socket
);
2059 tcp_unlock(inp
->inp_socket
, 1, NULL
);
2061 error
= SYSCTL_OUT(req
, &xt
, sizeof(xt
));
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.
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
));
2078 FREE(inp_list
, M_TEMP
);
2079 lck_rw_done(tcbinfo
.ipi_lock
);
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");
2089 tcp_pcblist_n SYSCTL_HANDLER_ARGS
2091 #pragma unused(oidp, arg1, arg2)
2094 error
= get_pcblist_n(IPPROTO_TCP
, req
, &tcbinfo
);
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");
2105 __private_extern__
void
2106 tcp_get_ports_used(uint32_t ifindex
, int protocol
, uint32_t flags
,
2109 inpcb_get_ports_used(ifindex
, protocol
, flags
,
2110 bitfield
, &tcbinfo
);
2113 __private_extern__
uint32_t
2114 tcp_count_opportunistic(unsigned int ifindex
, u_int32_t flags
)
2116 return (inpcb_count_opportunistic(ifindex
, &tcbinfo
, flags
));
2119 __private_extern__
uint32_t
2120 tcp_find_anypcb_byaddr(struct ifaddr
*ifa
)
2122 return (inpcb_find_anypcb_byaddr(ifa
, &tcbinfo
));
2126 tcp_handle_msgsize(struct ip
*ip
, struct inpcb
*inp
)
2128 struct rtentry
*rt
= NULL
;
2129 u_short ifscope
= IFSCOPE_NONE
;
2131 struct sockaddr_in icmpsrc
= {
2132 sizeof (struct sockaddr_in
),
2134 { 0, 0, 0, 0, 0, 0, 0, 0 } };
2135 struct icmp
*icp
= NULL
;
2137 icp
= (struct icmp
*)(void *)
2138 ((caddr_t
)ip
- offsetof(struct icmp
, icmp_ip
));
2140 icmpsrc
.sin_addr
= icp
->icmp_ip
.ip_dst
;
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
2156 if (ROUTE_UNUSABLE(&(inp
->inp_route
)) == false)
2157 rt
= inp
->inp_route
.ro_rt
;
2160 * icmp6_mtudisc_update scopes the routing lookup
2161 * to the incoming interface (delivered from mbuf
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
2171 ifscope
= (rt
->rt_ifp
!= NULL
) ?
2172 rt
->rt_ifp
->if_index
: IFSCOPE_NONE
;
2174 ifscope
= (inp
->inp_last_outifp
!= NULL
) ?
2175 inp
->inp_last_outifp
->if_index
: IFSCOPE_NONE
;
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
);
2190 if ((rt
->rt_flags
& RTF_HOST
) &&
2191 !(rt
->rt_rmx
.rmx_locks
& RTV_MTU
)) {
2192 mtu
= ntohs(icp
->icmp_nextmtu
);
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
2201 mtu
= ip_next_mtu(rt
->rt_rmx
.
2204 printf("MTU for %s reduced to %d\n",
2206 &icmpsrc
.sin_addr
, ipv4str
,
2207 sizeof (ipv4str
)), mtu
);
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
;
2222 tcp_ctlinput(int cmd
, struct sockaddr
*sa
, void *vip
)
2224 tcp_seq icmp_tcp_seq
;
2225 struct ip
*ip
= vip
;
2226 struct in_addr faddr
;
2230 void (*notify
)(struct inpcb
*, int) = tcp_notify
;
2232 faddr
= ((struct sockaddr_in
*)(void *)sa
)->sin_addr
;
2233 if (sa
->sa_family
!= AF_INET
|| faddr
.s_addr
== INADDR_ANY
)
2236 if ((unsigned)cmd
>= PRC_NCMDS
)
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
)) {
2246 notify
= in_rtchange
;
2247 } else if (cmd
== PRC_HOSTDEAD
)
2249 /* Source quench is deprecated */
2250 else if (cmd
== PRC_QUENCH
)
2252 else if (inetctlerrmap
[cmd
] == 0)
2258 icp
= (struct icmp
*)(void *)
2259 ((caddr_t
)ip
- offsetof(struct icmp
, icmp_ip
));
2261 * Only the first 8 bytes of TCP header will be returned.
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) ==
2271 tcp_unlock(inp
->inp_socket
, 1, 0);
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
);
2281 (*notify
)(inp
, inetctlerrmap
[cmd
]);
2283 tcp_unlock(inp
->inp_socket
, 1, 0);
2286 in_pcbnotifyall(&tcbinfo
, faddr
, inetctlerrmap
[cmd
], notify
);
2291 tcp6_ctlinput(int cmd
, struct sockaddr
*sa
, void *d
)
2294 void (*notify
)(struct inpcb
*, int) = tcp_notify
;
2295 struct ip6_hdr
*ip6
;
2297 struct ip6ctlparam
*ip6cp
= NULL
;
2298 const struct sockaddr_in6
*sa6_src
= NULL
;
2300 struct tcp_portonly
{
2305 if (sa
->sa_family
!= AF_INET6
||
2306 sa
->sa_len
!= sizeof(struct sockaddr_in6
))
2309 if ((unsigned)cmd
>= PRC_NCMDS
)
2312 if (cmd
== PRC_MSGSIZE
)
2313 notify
= tcp_mtudisc
;
2314 else if (!PRC_IS_REDIRECT(cmd
) && (inet6ctlerrmap
[cmd
] == 0))
2316 /* Source quench is deprecated */
2317 else if (cmd
== PRC_QUENCH
)
2320 /* if the parameter is from icmp6, decode it. */
2322 ip6cp
= (struct ip6ctlparam
*)d
;
2324 ip6
= ip6cp
->ip6c_ip6
;
2325 off
= ip6cp
->ip6c_off
;
2326 sa6_src
= ip6cp
->ip6c_src
;
2330 off
= 0; /* fool gcc */
2336 * XXX: We assume that when IPV6 is non NULL,
2337 * M and OFF are valid.
2340 /* check if we can safely examine src and dst ports */
2341 if (m
->m_pkthdr
.len
< off
+ sizeof(*thp
))
2344 bzero(&th
, sizeof(th
));
2345 m_copydata(m
, off
, sizeof(*thp
), (caddr_t
)&th
);
2347 in6_pcbnotify(&tcbinfo
, sa
, th
.th_dport
,
2348 (struct sockaddr
*)ip6cp
->ip6c_src
,
2349 th
.th_sport
, cmd
, NULL
, notify
);
2351 in6_pcbnotify(&tcbinfo
, sa
, 0,
2352 (struct sockaddr
*)(size_t)sa6_src
, 0, cmd
, NULL
, notify
);
2359 * Following is where TCP initial sequence number generation occurs.
2361 * There are two places where we must use initial sequence numbers:
2362 * 1. In SYN-ACK packets.
2363 * 2. In SYN packets.
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.
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.
2378 * For more information on the theory of operation, please see
2381 * Implementation details:
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
2388 * Two sysctls control the generation of ISNs:
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.
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.
2401 #define ISN_BYTES_PER_SECOND 1048576
2404 tcp_new_isn(struct tcpcb
*tp
)
2406 u_int32_t md5_buffer
[4];
2408 struct timeval timenow
;
2409 u_char isn_secret
[32];
2410 int isn_last_reseed
= 0;
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)
2417 return (RandomULong());
2419 return (arc4random());
2421 getmicrotime(&timenow
);
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
))) {
2429 read_random(&isn_secret
, sizeof(isn_secret
));
2431 read_random_unlimited(&isn_secret
, sizeof(isn_secret
));
2433 isn_last_reseed
= timenow
.tv_sec
;
2436 /* Compute the md5 hash and return the ISN. */
2438 MD5Update(&isn_ctx
, (u_char
*) &tp
->t_inpcb
->inp_fport
,
2440 MD5Update(&isn_ctx
, (u_char
*) &tp
->t_inpcb
->inp_lport
,
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
));
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
));
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
);
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.
2470 tcp_drop_syn_sent(struct inpcb
*inp
, int errno
)
2472 struct tcpcb
*tp
= intotcpcb(inp
);
2474 if (tp
&& tp
->t_state
== TCPS_SYN_SENT
)
2475 tcp_drop(tp
, errno
);
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.
2490 struct tcpcb
*tp
= intotcpcb(inp
);
2492 struct rmxp_tao
*taop
;
2493 struct socket
*so
= inp
->inp_socket
;
2497 u_int32_t protoHdrOverhead
= sizeof (struct tcpiphdr
);
2499 int isipv6
= (tp
->t_inpcb
->inp_vflag
& INP_IPV6
) != 0;
2502 protoHdrOverhead
= sizeof(struct ip6_hdr
) +
2503 sizeof(struct tcphdr
);
2509 rt
= tcp_rtlookup6(inp
, IFSCOPE_NONE
);
2512 rt
= tcp_rtlookup(inp
, IFSCOPE_NONE
);
2513 if (!rt
|| !rt
->rt_rmx
.rmx_mtu
) {
2514 tp
->t_maxopd
= tp
->t_maxseg
=
2516 isipv6
? tcp_v6mssdflt
:
2520 /* Route locked during lookup above */
2525 taop
= rmx_taop(rt
->rt_rmx
);
2526 offered
= taop
->tao_mssopt
;
2527 mtu
= rt
->rt_rmx
.rmx_mtu
;
2529 /* Route locked during lookup above */
2533 // Adjust MTU if necessary.
2534 mtu
= necp_socket_get_effective_mtu(inp
, mtu
);
2536 mss
= mtu
- protoHdrOverhead
;
2539 mss
= min(mss
, offered
);
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.
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.
2557 if (tp
->t_maxopd
<= mss
)
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
;
2566 mss
-= mptcp_adj_mss(tp
, TRUE
);
2568 if (so
->so_snd
.sb_hiwat
< mss
)
2569 mss
= so
->so_snd
.sb_hiwat
;
2574 * Reset the slow-start flight size as it may depends on the
2577 if (CC_ALGO(tp
)->cwnd_init
!= NULL
)
2578 CC_ALGO(tp
)->cwnd_init(tp
);
2579 tcpstat
.tcps_mturesent
++;
2581 tp
->snd_nxt
= tp
->snd_una
;
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.
2594 tcp_rtlookup(struct inpcb
*inp
, unsigned int input_ifscope
)
2600 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2602 ro
= &inp
->inp_route
;
2603 if ((rt
= ro
->ro_rt
) != NULL
)
2606 if (ROUTE_UNUSABLE(ro
)) {
2612 /* No route yet, so try to acquire one */
2613 if (inp
->inp_faddr
.s_addr
!= INADDR_ANY
) {
2614 unsigned int ifscope
;
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
=
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).
2628 ifscope
= (inp
->inp_flags
& INP_BOUND_IF
) ?
2629 inp
->inp_boundifp
->if_index
: input_ifscope
;
2631 rtalloc_scoped(ro
, ifscope
);
2632 if ((rt
= ro
->ro_rt
) != NULL
)
2637 RT_LOCK_ASSERT_HELD(rt
);
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
2647 tp
= intotcpcb(inp
);
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
;
2653 tp
->t_flags
|= TF_PMTUD
;
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
;
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
;
2675 * Caller needs to call RT_UNLOCK(rt).
2682 tcp_rtlookup6(struct inpcb
*inp
, unsigned int input_ifscope
)
2684 struct route_in6
*ro6
;
2688 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2690 ro6
= &inp
->in6p_route
;
2691 if ((rt
= ro6
->ro_rt
) != NULL
)
2694 if (ROUTE_UNUSABLE(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
;
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
;
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).
2717 ifscope
= (inp
->inp_flags
& INP_BOUND_IF
) ?
2718 inp
->inp_boundifp
->if_index
: input_ifscope
;
2720 rtalloc_scoped((struct route
*)ro6
, ifscope
);
2721 if ((rt
= ro6
->ro_rt
) != NULL
)
2726 RT_LOCK_ASSERT_HELD(rt
);
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
2737 tp
= intotcpcb(inp
);
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
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
;
2751 tp
->t_flags
|= TF_PMTUD
;
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
;
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
;
2774 * Caller needs to call RT_UNLOCK(rt).
2781 /* compute ESP/AH header size for TCP, including outer IP header. */
2783 ipsec_hdrsiz_tcp(struct tcpcb
*tp
)
2790 struct ip6_hdr
*ip6
= NULL
;
2794 if ((tp
== NULL
) || ((inp
= tp
->t_inpcb
) == NULL
))
2796 MGETHDR(m
, M_DONTWAIT
, MT_DATA
); /* MAC-OK */
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
);
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
);
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.
2828 tcp_gettaocache(struct inpcb
*inp
)
2831 struct rmxp_tao
*taop
;
2834 if ((inp
->inp_vflag
& INP_IPV6
) != 0)
2835 rt
= tcp_rtlookup6(inp
, IFSCOPE_NONE
);
2838 rt
= tcp_rtlookup(inp
, IFSCOPE_NONE
);
2840 /* Make sure this is a host route and is up. */
2842 (rt
->rt_flags
& (RTF_UP
|RTF_HOST
)) != (RTF_UP
|RTF_HOST
)) {
2843 /* Route locked during lookup above */
2849 taop
= rmx_taop(rt
->rt_rmx
);
2850 /* Route locked during lookup above */
2856 * Clear all the TAO cache entries, called from tcp_init.
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.
2864 tcp_cleartaocache(void)
2869 tcp_lock(struct socket
*so
, int refcount
, void *lr
)
2874 lr_saved
= __builtin_return_address(0);
2878 if (so
->so_pcb
!= NULL
) {
2879 lck_mtx_lock(&((struct inpcb
*)so
->so_pcb
)->inpcb_mtx
);
2881 panic("tcp_lock: so=%p NO PCB! lr=%p lrh= %s\n",
2882 so
, lr_saved
, solockhistory_nr(so
));
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
));
2894 so
->lock_lr
[so
->next_lock_lr
] = lr_saved
;
2895 so
->next_lock_lr
= (so
->next_lock_lr
+1) % SO_LCKDBG_MAX
;
2900 tcp_unlock(struct socket
*so
, int refcount
, void *lr
)
2905 lr_saved
= __builtin_return_address(0);
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
));
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
));
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
));
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
);
2939 tcp_getlock(struct socket
*so
, __unused
int locktype
)
2941 struct inpcb
*inp
= sotoinpcb(so
);
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
);
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
);
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
2963 tcp_sbrcv_grow_rwin(struct tcpcb
*tp
, struct sockbuf
*sb
)
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
;
2970 * If message delivery is enabled, do not count
2971 * unordered bytes in receive buffer towards hiwat
2973 if (so
->so_flags
& SOF_ENABLE_MSGS
)
2974 rcvbuf
= rcvbuf
- so
->so_msg_state
->msg_uno_bytes
;
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
))) {
2985 min((sb
->sb_hiwat
+ rcvbufinc
), tcp_autorcvbuf_max
));
2990 tcp_sbspace(struct tcpcb
*tp
)
2992 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
2993 struct sockbuf
*sb
= &so
->so_rcv
;
2994 u_int32_t rcvbuf
= sb
->sb_hiwat
;
2996 int32_t pending
= 0;
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.
3005 if (so
->so_flags
& SOF_ENABLE_MSGS
)
3006 rcvbuf
= rcvbuf
- so
->so_msg_state
->msg_uno_bytes
;
3008 tcp_sbrcv_grow_rwin(tp
, sb
);
3010 space
= ((int32_t) imin((rcvbuf
- sb
->sb_cc
),
3011 (sb
->sb_mbmax
- sb
->sb_mbcnt
)));
3016 /* Compensate for data being processed by content filters */
3017 pending
= cfil_sock_data_space(sb
);
3018 #endif /* CONTENT_FILTER */
3019 if (pending
> space
)
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)
3030 if (space
< tp
->t_maxseg
)
3033 /* Clip window size for slower link */
3035 if (((tp
->t_flags
& TF_SLOWLINK
) != 0) && slowlink_wsize
> 0)
3036 return (imin(space
, slowlink_wsize
));
3041 * Checks TCP Segment Offloading capability for a given connection
3042 * and interface pair.
3045 tcp_set_tso(struct tcpcb
*tp
, struct ifnet
*ifp
)
3053 * We can't use TSO if this tcpcb belongs to an MPTCP session.
3055 if (tp
->t_mpflags
& TMPF_MPTCP_TRUE
) {
3056 tp
->t_flags
&= ~TF_TSO
;
3062 isipv6
= (inp
->inp_vflag
& INP_IPV6
) != 0;
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
;
3070 tp
->tso_max_segment_size
= TCP_MAXWIN
;
3072 tp
->t_flags
&= ~TF_TSO
;
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
;
3083 tp
->tso_max_segment_size
= TCP_MAXWIN
;
3085 tp
->t_flags
&= ~TF_TSO
;
3089 #define TIMEVAL_TO_TCPHZ(_tv_) ((_tv_).tv_sec * TCP_RETRANSHZ + \
3090 (_tv_).tv_usec / TCP_RETRANSHZ_TO_USEC)
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
3102 calculate_tcp_clock(void)
3104 struct timeval tv
= tcp_uptime
;
3105 struct timeval interval
= {0, TCP_RETRANSHZ_TO_USEC
};
3106 struct timeval now
, hold_now
;
3112 * Update coarse-grained networking timestamp (in sec.); the idea
3113 * is to update the counter returnable via net_uptime() when
3116 net_update_uptime_secs(now
.tv_sec
);
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
);
3131 timevalsub(&now
, &tv
);
3133 incr
= TIMEVAL_TO_TCPHZ(now
);
3135 tcp_uptime
= hold_now
;
3139 lck_spin_unlock(tcp_uptime_lock
);
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.
3150 tcp_set_max_rwinscale(struct tcpcb
*tp
, struct socket
*so
,
3151 u_int32_t rcvbuf_max
)
3153 u_int32_t maxsockbufsize
;
3154 if (!tcp_do_rfc1323
) {
3155 tp
->request_r_scale
= 0;
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
;
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
);
3171 tcp_notsent_lowat_check(struct socket
*so
) {
3172 struct inpcb
*inp
= sotoinpcb(so
);
3173 struct tcpcb
*tp
= NULL
;
3176 tp
= intotcpcb(inp
);
3179 notsent
= so
->so_snd
.sb_cc
-
3180 (tp
->snd_nxt
- tp
->snd_una
);
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.
3188 if (notsent
<= tp
->t_notsent_lowat
) {
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.
3197 if ((tp
->t_flags
& TF_NODELAY
) == 0 &&
3198 notsent
> 0 && notsent
< tp
->t_maxseg
) {
3205 tcp_rxtseg_insert(struct tcpcb
*tp
, tcp_seq start
, tcp_seq end
)
3207 struct tcp_rxt_seg
*rxseg
= NULL
, *prev
= NULL
, *next
= NULL
;
3208 u_int32_t rxcount
= 0;
3210 if (SLIST_EMPTY(&tp
->t_rxt_segments
))
3211 tp
->t_dsack_lastuna
= tp
->snd_una
;
3213 * First check if there is a segment already existing for this
3217 SLIST_FOREACH(rxseg
, &tp
->t_rxt_segments
, rx_link
) {
3218 if (SEQ_GT(rxseg
->rx_start
, start
))
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
)) {
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.
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;
3243 prev
->rx_end
= (start
- 1);
3244 rxcount
= prev
->rx_count
;
3248 if (next
!= NULL
&& SEQ_LT(next
->rx_start
, end
)) {
3249 if (SEQ_LEQ(next
->rx_end
, end
)) {
3250 end
= next
->rx_start
- 1;
3253 next
->rx_start
= end
+ 1;
3254 rxcount
= next
->rx_count
;
3257 if (!SEQ_LT(start
, end
))
3260 rxseg
= (struct tcp_rxt_seg
*) zalloc(tcp_rxt_seg_zone
);
3261 if (rxseg
== NULL
) {
3264 bzero(rxseg
, sizeof(*rxseg
));
3265 rxseg
->rx_start
= start
;
3266 rxseg
->rx_end
= end
;
3267 rxseg
->rx_count
= rxcount
+ 1;
3270 SLIST_INSERT_AFTER(prev
, rxseg
, rx_link
);
3272 SLIST_INSERT_HEAD(&tp
->t_rxt_segments
, rxseg
, rx_link
);
3276 struct tcp_rxt_seg
*
3277 tcp_rxtseg_find(struct tcpcb
*tp
, tcp_seq start
, tcp_seq end
)
3279 struct tcp_rxt_seg
*rxseg
;
3280 if (SLIST_EMPTY(&tp
->t_rxt_segments
))
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
))
3287 if (SEQ_GT(rxseg
->rx_start
, start
))
3294 tcp_rxtseg_clean(struct tcpcb
*tp
)
3296 struct tcp_rxt_seg
*rxseg
, *next
;
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
);
3303 tp
->t_dsack_lastuna
= tp
->snd_max
;
3307 tcp_rxtseg_detect_bad_rexmt(struct tcpcb
*tp
, tcp_seq th_ack
)
3309 boolean_t bad_rexmt
;
3310 struct tcp_rxt_seg
*rxseg
;
3312 if (SLIST_EMPTY(&tp
->t_rxt_segments
))
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.
3320 if (SEQ_LT(th_ack
, tp
->snd_recover
))
3324 SLIST_FOREACH(rxseg
, &tp
->t_rxt_segments
, rx_link
) {
3325 if (rxseg
->rx_count
> 1 ||
3326 !(rxseg
->rx_flags
& TCP_RXT_SPURIOUS
)) {
3335 tcp_rxtseg_dsack_for_tlp(struct tcpcb
*tp
)
3337 boolean_t dsack_for_tlp
= FALSE
;
3338 struct tcp_rxt_seg
*rxseg
;
3339 if (SLIST_EMPTY(&tp
->t_rxt_segments
))
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
;
3350 return (dsack_for_tlp
);
3354 tcp_rxtseg_total_size(struct tcpcb
*tp
)
3356 struct tcp_rxt_seg
*rxseg
;
3357 u_int32_t total_size
= 0;
3359 SLIST_FOREACH(rxseg
, &tp
->t_rxt_segments
, rx_link
) {
3360 total_size
+= (rxseg
->rx_end
- rxseg
->rx_start
) + 1;
3362 return (total_size
);
3366 tcp_get_connectivity_status(struct tcpcb
*tp
,
3367 struct tcp_conn_status
*connstatus
)
3369 if (tp
== NULL
|| connstatus
== NULL
)
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;
3376 connstatus
->conn_probe_failed
= 1;
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;
3387 tfo_enabled(const struct tcpcb
*tp
)
3389 return ((tp
->t_flagsext
& TF_FASTOPEN
)? TRUE
: FALSE
);
3393 tcp_disable_tfo(struct tcpcb
*tp
)
3395 tp
->t_flagsext
&= ~TF_FASTOPEN
;
3398 static struct mbuf
*
3399 tcp_make_keepalive_frame(struct tcpcb
*tp
, struct ifnet
*ifp
,
3402 struct inpcb
*inp
= tp
->t_inpcb
;
3409 * The code assumes the IP + TCP headers fit in an mbuf packet header
3411 _CASSERT(sizeof(struct ip
) + sizeof(struct tcphdr
) <= _MHLEN
);
3412 _CASSERT(sizeof(struct ip6_hdr
) + sizeof(struct tcphdr
) <= _MHLEN
);
3414 MGETHDR(m
, M_WAIT
, MT_HEADER
);
3418 m
->m_pkthdr
.pkt_proto
= IPPROTO_TCP
;
3420 data
= mbuf_datastart(m
);
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
;
3428 VERIFY(inp
->inp_vflag
& INP_IPV6
);
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
;
3438 tcp_fillheaders(tp
, data
, th
);
3440 if (inp
->inp_vflag
& INP_IPV4
) {
3443 ip
= (__typeof__(ip
))(void *)data
;
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
);
3451 struct ip6_hdr
*ip6
;
3453 ip6
= (__typeof__(ip6
))(void *)data
;
3455 ip6
->ip6_plen
= htons(sizeof(struct tcphdr
));
3456 ip6
->ip6_hlim
= in6_selecthlim(inp
, ifp
);
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;
3463 th
->th_flags
= TH_ACK
;
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
));
3471 th
->th_seq
= htonl(tp
->snd_una
- 1);
3473 th
->th_seq
= htonl(tp
->snd_una
);
3475 th
->th_ack
= htonl(tp
->rcv_nxt
);
3477 /* Force recompute TCP checksum to be the final value */
3479 if (inp
->inp_vflag
& INP_IPV4
) {
3480 th
->th_sum
= inet_cksum(m
, IPPROTO_TCP
,
3481 sizeof(struct ip
), sizeof(struct tcphdr
));
3483 th
->th_sum
= inet6_cksum(m
, IPPROTO_TCP
,
3484 sizeof(struct ip6_hdr
), sizeof(struct tcphdr
));
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
)
3498 u_int32_t frame_index
= *used_frames_count
;
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
)
3507 * This function is called outside the regular TCP processing
3508 * so we need to update the TCP clock.
3510 calculate_tcp_clock();
3512 lck_rw_lock_shared(tcbinfo
.ipi_lock
);
3513 gencnt
= tcbinfo
.ipi_gencnt
;
3514 LIST_FOREACH(inp
, tcbinfo
.ipi_listhead
, inp_list
) {
3516 struct ifnet_keepalive_offload_frame
*frame
;
3517 struct mbuf
*m
= NULL
;
3518 struct tcpcb
*tp
= intotcpcb(inp
);
3520 if (frame_index
>= frames_array_count
)
3523 if (inp
->inp_gencnt
> gencnt
||
3524 inp
->inp_state
== INPCB_STATE_DEAD
)
3527 if ((so
= inp
->inp_socket
) == NULL
||
3528 (so
->so_state
& SS_DEFUNCT
))
3531 * check for keepalive offload flag without socket
3532 * lock to avoid a deadlock
3534 if (!(inp
->inp_flags2
& INP2_KEEPALIVE_OFFLOAD
)) {
3538 if (!(inp
->inp_vflag
& (INP_IPV4
| INP_IPV6
))) {
3541 if (inp
->inp_ppcb
== NULL
||
3542 in_pcb_checkstate(inp
, WNT_ACQUIRE
, 0) == WNT_STOPUSING
)
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);
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);
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);
3563 if (inp
->inp_lport
== 0 || inp
->inp_fport
== 0) {
3564 tcp_unlock(so
, 1, 0);
3567 if (inp
->inp_last_outifp
== NULL
||
3568 inp
->inp_last_outifp
->if_index
!= ifp
->if_index
) {
3569 tcp_unlock(so
, 1, 0);
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);
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);
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
3588 if (tp
->t_state
!= TCPS_ESTABLISHED
) {
3589 tcp_unlock(so
, 1, 0);
3593 * This inp has all the information that is needed to
3594 * generate an offload frame.
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
:
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
;
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
));
3620 struct in6_addr
*ip6
;
3622 frame
->length
= frame_data_offset
+
3623 sizeof(struct ip6_hdr
) + sizeof(struct tcphdr
);
3624 frame
->reply_length
= frame
->length
;
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;
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;
3641 m
= tcp_make_keepalive_frame(tp
, ifp
, TRUE
);
3643 tcp_unlock(so
, 1, 0);
3646 bcopy(m
->m_data
, frame
->data
+ frame_data_offset
,
3651 * Now the response packet to incoming probes
3653 m
= tcp_make_keepalive_frame(tp
, ifp
, FALSE
);
3655 tcp_unlock(so
, 1, 0);
3658 bcopy(m
->m_data
, frame
->reply_data
+ frame_data_offset
,
3663 tcp_unlock(so
, 1, 0);
3665 lck_rw_done(tcbinfo
.ipi_lock
);
3666 *used_frames_count
= frame_index
;
3670 tcp_notify_ack_id_valid(struct tcpcb
*tp
, struct socket
*so
,
3671 u_int32_t notify_id
)
3673 struct tcp_notify_ack_marker
*elm
;
3675 if (so
->so_snd
.sb_cc
== 0)
3678 SLIST_FOREACH(elm
, &tp
->t_notify_ack
, notify_next
) {
3679 /* Duplicate id is not allowed */
3680 if (elm
->notify_id
== notify_id
)
3682 /* Duplicate position is not allowed */
3683 if (elm
->notify_snd_una
== tp
->snd_una
+ so
->so_snd
.sb_cc
)
3690 tcp_add_notify_ack_marker(struct tcpcb
*tp
, u_int32_t notify_id
)
3692 struct tcp_notify_ack_marker
*nm
, *elm
= NULL
;
3693 struct socket
*so
= tp
->t_inpcb
->inp_socket
;
3695 MALLOC(nm
, struct tcp_notify_ack_marker
*, sizeof (*nm
),
3696 M_TEMP
, M_WAIT
| M_ZERO
);
3699 nm
->notify_id
= notify_id
;
3700 nm
->notify_snd_una
= tp
->snd_una
+ so
->so_snd
.sb_cc
;
3702 SLIST_FOREACH(elm
, &tp
->t_notify_ack
, notify_next
) {
3703 if (SEQ_GT(nm
->notify_snd_una
, elm
->notify_snd_una
))
3708 VERIFY(SLIST_EMPTY(&tp
->t_notify_ack
));
3709 SLIST_INSERT_HEAD(&tp
->t_notify_ack
, nm
, notify_next
);
3711 SLIST_INSERT_AFTER(elm
, nm
, notify_next
);
3713 tp
->t_notify_ack_count
++;
3718 tcp_notify_ack_free(struct tcpcb
*tp
)
3720 struct tcp_notify_ack_marker
*elm
, *next
;
3721 if (SLIST_EMPTY(&tp
->t_notify_ack
))
3724 SLIST_FOREACH_SAFE(elm
, &tp
->t_notify_ack
, notify_next
, next
) {
3725 SLIST_REMOVE(&tp
->t_notify_ack
, elm
, tcp_notify_ack_marker
,
3729 SLIST_INIT(&tp
->t_notify_ack
);
3730 tp
->t_notify_ack_count
= 0;
3734 tcp_notify_acknowledgement(struct tcpcb
*tp
, struct socket
*so
)
3736 struct tcp_notify_ack_marker
*elm
;
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
);
3745 tcp_get_notify_ack_count(struct tcpcb
*tp
,
3746 struct tcp_notify_ack_complete
*retid
)
3748 struct tcp_notify_ack_marker
*elm
;
3749 size_t complete
= 0;
3751 SLIST_FOREACH(elm
, &tp
->t_notify_ack
, notify_next
) {
3752 if (SEQ_GEQ(tp
->snd_una
, elm
->notify_snd_una
))
3757 retid
->notify_pending
= tp
->t_notify_ack_count
- complete
;
3758 retid
->notify_complete_count
= min(TCP_MAX_NOTIFY_ACK
, complete
);
3762 tcp_get_notify_ack_ids(struct tcpcb
*tp
,
3763 struct tcp_notify_ack_complete
*retid
)
3766 struct tcp_notify_ack_marker
*elm
, *next
;
3768 SLIST_FOREACH_SAFE(elm
, &tp
->t_notify_ack
, notify_next
, next
) {
3769 if (i
>= retid
->notify_complete_count
)
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
);
3776 tp
->t_notify_ack_count
--;
3784 tcp_notify_ack_active(struct socket
*so
)
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
));
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
))
3801 inp_get_sndbytes_allunsent(struct socket
*so
, u_int32_t th_ack
)
3803 struct inpcb
*inp
= sotoinpcb(so
);
3804 struct tcpcb
*tp
= intotcpcb(inp
);
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
)
3812 unsent
= so
->so_snd
.sb_cc
- sent
;