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