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