1 /*
2 * Copyright (c) 2000-2024 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_timer.c 8.2 (Berkeley) 5/24/95
61 * $FreeBSD: src/sys/netinet/tcp_timer.c,v 1.34.2.11 2001/08/22 00:59:12 silby Exp $
62 */
63
64 #include "tcp_includes.h"
65
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/kernel.h>
69 #include <sys/mbuf.h>
70 #include <sys/sysctl.h>
71 #include <sys/socket.h>
72 #include <sys/socketvar.h>
73 #include <sys/protosw.h>
74 #include <sys/domain.h>
75 #include <sys/mcache.h>
76 #include <sys/queue.h>
77 #include <kern/locks.h>
78 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
79 #include <mach/boolean.h>
80
81 #include <net/route.h>
82 #include <net/if_var.h>
83 #include <net/ntstat.h>
84
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/in_pcb.h>
88 #include <netinet/in_var.h>
89 #include <netinet6/in6_pcb.h>
90 #include <netinet/ip_var.h>
91 #include <netinet/tcp.h>
92 #include <netinet/tcp_cache.h>
93 #include <netinet/tcp_fsm.h>
94 #include <netinet/tcp_seq.h>
95 #include <netinet/tcp_timer.h>
96 #include <netinet/tcp_var.h>
97 #include <netinet/tcp_cc.h>
98 #include <netinet6/tcp6_var.h>
99 #include <netinet/tcpip.h>
100 #include <netinet/tcp_log.h>
101
102 #include <sys/kdebug.h>
103 #include <mach/sdt.h>
104 #include <netinet/mptcp_var.h>
105 #include <net/content_filter.h>
106 #include <net/sockaddr_utils.h>
107
108 /* Max number of times a stretch ack can be delayed on a connection */
109 #define TCP_STRETCHACK_DELAY_THRESHOLD 5
110
111 /*
112 * If the host processor has been sleeping for too long, this is the threshold
113 * used to avoid sending stale retransmissions.
114 */
115 #define TCP_SLEEP_TOO_LONG (10 * 60 * 1000) /* 10 minutes in ms */
116
117 /* tcp timer list */
118 struct tcptimerlist tcp_timer_list;
119
120 /* List of pcbs in timewait state, protected by tcbinfo's ipi_lock */
121 struct tcptailq tcp_tw_tailq;
122
123
124 static int
125 sysctl_msec_to_ticks SYSCTL_HANDLER_ARGS
126 {
127 #pragma unused(arg2)
128 int error, temp;
129 long s, tt;
130
131 tt = *(int *)arg1;
132 s = tt * 1000 / TCP_RETRANSHZ;
133 if (tt < 0 || s > INT_MAX) {
134 return EINVAL;
135 }
136 temp = (int)s;
137
138 error = sysctl_handle_int(oidp, &temp, 0, req);
139 if (error || !req->newptr) {
140 return error;
141 }
142
143 tt = (long)temp * TCP_RETRANSHZ / 1000;
144 if (tt < 1 || tt > INT_MAX) {
145 return EINVAL;
146 }
147
148 *(int *)arg1 = (int)tt;
149 SYSCTL_SKMEM_UPDATE_AT_OFFSET(arg2, *(int*)arg1);
150 return 0;
151 }
152
153 #if SYSCTL_SKMEM
154 int tcp_keepinit = TCPTV_KEEP_INIT;
155 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPINIT, keepinit,
156 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
157 &tcp_keepinit, offsetof(skmem_sysctl, tcp.keepinit),
158 sysctl_msec_to_ticks, "I", "");
159
160 int tcp_keepidle = TCPTV_KEEP_IDLE;
161 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPIDLE, keepidle,
162 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
163 &tcp_keepidle, offsetof(skmem_sysctl, tcp.keepidle),
164 sysctl_msec_to_ticks, "I", "");
165
166 int tcp_keepintvl = TCPTV_KEEPINTVL;
167 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPINTVL, keepintvl,
168 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
169 &tcp_keepintvl, offsetof(skmem_sysctl, tcp.keepintvl),
170 sysctl_msec_to_ticks, "I", "");
171
172 SYSCTL_SKMEM_TCP_INT(OID_AUTO, keepcnt,
173 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
174 int, tcp_keepcnt, TCPTV_KEEPCNT, "number of times to repeat keepalive");
175
176 int tcp_msl = TCPTV_MSL;
177 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, msl,
178 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
179 &tcp_msl, offsetof(skmem_sysctl, tcp.msl),
180 sysctl_msec_to_ticks, "I", "Maximum segment lifetime");
181 #else /* SYSCTL_SKMEM */
182 int tcp_keepinit;
183 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPINIT, keepinit,
184 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
185 &tcp_keepinit, 0, sysctl_msec_to_ticks, "I", "");
186
187 int tcp_keepidle;
188 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPIDLE, keepidle,
189 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
190 &tcp_keepidle, 0, sysctl_msec_to_ticks, "I", "");
191
192 int tcp_keepintvl;
193 SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPINTVL, keepintvl,
194 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
195 &tcp_keepintvl, 0, sysctl_msec_to_ticks, "I", "");
196
197 int tcp_keepcnt;
198 SYSCTL_INT(_net_inet_tcp, OID_AUTO, keepcnt,
199 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
200 &tcp_keepcnt, 0, "number of times to repeat keepalive");
201
202 int tcp_msl;
203 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, msl,
204 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
205 &tcp_msl, 0, sysctl_msec_to_ticks, "I", "Maximum segment lifetime");
206 #endif /* SYSCTL_SKMEM */
207
208 /*
209 * Avoid DoS with connections half-closed in TIME_WAIT_2
210 */
211 int tcp_fin_timeout = TCPTV_FINWAIT2;
212
213 static int
214 sysctl_tcp_fin_timeout SYSCTL_HANDLER_ARGS
215 {
216 #pragma unused(arg2)
217 int error;
218 int value = tcp_fin_timeout;
219
220 error = sysctl_handle_int(oidp, &value, 0, req);
221 if (error != 0 || req->newptr == USER_ADDR_NULL) {
222 return error;
223 }
224
225 if (value == -1) {
226 /* Reset to default value */
227 value = TCPTV_FINWAIT2;
228 } else {
229 /* Convert from milliseconds */
230 long big_value = value * TCP_RETRANSHZ / 1000;
231
232 if (big_value < 0 || big_value > INT_MAX) {
233 return EINVAL;
234 }
235 value = (int)big_value;
236 }
237 tcp_fin_timeout = value;
238 SYSCTL_SKMEM_UPDATE_AT_OFFSET(arg2, value);
239 return 0;
240 }
241
242 #if SYSCTL_SKMEM
243 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, fin_timeout,
244 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
245 &tcp_fin_timeout, offsetof(skmem_sysctl, tcp.fin_timeout),
246 sysctl_tcp_fin_timeout, "I", "");
247 #else /* SYSCTL_SKMEM */
248 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, fin_timeout,
249 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
250 &tcp_fin_timeout, 0,
251 sysctl_tcp_fin_timeout, "I", "");
252 #endif /* SYSCTL_SKMEM */
253
254 /*
255 * Avoid DoS via TCP Robustness in Persist Condition
256 * (see http://www.ietf.org/id/draft-ananth-tcpm-persist-02.txt)
257 * by allowing a system wide maximum persistence timeout value when in
258 * Zero Window Probe mode.
259 *
260 * Expressed in milliseconds to be consistent without timeout related
261 * values, the TCP socket option is in seconds.
262 */
263 #if SYSCTL_SKMEM
264 u_int32_t tcp_max_persist_timeout = 0;
265 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, max_persist_timeout,
266 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
267 &tcp_max_persist_timeout, offsetof(skmem_sysctl, tcp.max_persist_timeout),
268 sysctl_msec_to_ticks, "I", "Maximum persistence timeout for ZWP");
269 #else /* SYSCTL_SKMEM */
270 u_int32_t tcp_max_persist_timeout = 0;
271 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, max_persist_timeout,
272 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
273 &tcp_max_persist_timeout, 0, sysctl_msec_to_ticks, "I",
274 "Maximum persistence timeout for ZWP");
275 #endif /* SYSCTL_SKMEM */
276
277 SYSCTL_SKMEM_TCP_INT(OID_AUTO, always_keepalive,
278 CTLFLAG_RW | CTLFLAG_LOCKED, static int, always_keepalive, 0,
279 "Assume SO_KEEPALIVE on all TCP connections");
280
281 /*
282 * This parameter determines how long the timer list will stay in fast or
283 * quick mode even though all connections are idle. In this state, the
284 * timer will run more frequently anticipating new data.
285 */
286 SYSCTL_SKMEM_TCP_INT(OID_AUTO, timer_fastmode_idlemax,
287 CTLFLAG_RW | CTLFLAG_LOCKED, int, timer_fastmode_idlemax,
288 TCP_FASTMODE_IDLERUN_MAX, "Maximum idle generations in fast mode");
289
290 /*
291 * See tcp_syn_backoff[] for interval values between SYN retransmits;
292 * the value set below defines the number of retransmits, before we
293 * disable the timestamp and window scaling options during subsequent
294 * SYN retransmits. Setting it to 0 disables the dropping off of those
295 * two options.
296 */
297 SYSCTL_SKMEM_TCP_INT(OID_AUTO, broken_peer_syn_rexmit_thres,
298 CTLFLAG_RW | CTLFLAG_LOCKED, static int, tcp_broken_peer_syn_rxmit_thres,
299 10, "Number of retransmitted SYNs before disabling RFC 1323 "
300 "options on local connections");
301
302 static int tcp_timer_advanced = 0;
303 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_timer_advanced,
304 CTLFLAG_RD | CTLFLAG_LOCKED, &tcp_timer_advanced, 0,
305 "Number of times one of the timers was advanced");
306
307 static int tcp_resched_timerlist = 0;
308 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_resched_timerlist,
309 CTLFLAG_RD | CTLFLAG_LOCKED, &tcp_resched_timerlist, 0,
310 "Number of times timer list was rescheduled as part of processing a packet");
311
312 SYSCTL_SKMEM_TCP_INT(OID_AUTO, pmtud_blackhole_detection,
313 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_pmtud_black_hole_detect, 1,
314 "Path MTU Discovery Black Hole Detection");
315
316 SYSCTL_SKMEM_TCP_INT(OID_AUTO, pmtud_blackhole_mss,
317 CTLFLAG_RW | CTLFLAG_LOCKED, int, tcp_pmtud_black_hole_mss, 1200,
318 "Path MTU Discovery Black Hole Detection lowered MSS");
319
320 #if (DEBUG || DEVELOPMENT)
321 int tcp_probe_if_fix_port = 0;
322 SYSCTL_INT(_net_inet_tcp, OID_AUTO, probe_if_fix_port,
323 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
324 &tcp_probe_if_fix_port, 0, "");
325 #endif /* (DEBUG || DEVELOPMENT) */
326
327 static u_int32_t tcp_mss_rec_medium = 1200;
328 static u_int32_t tcp_mss_rec_low = 512;
329
330 #define TCP_REPORT_STATS_INTERVAL 43200 /* 12 hours, in seconds */
331 int tcp_report_stats_interval = TCP_REPORT_STATS_INTERVAL;
332
333 /* performed garbage collection of "used" sockets */
334 static boolean_t tcp_gc_done = FALSE;
335
336 /* max idle probes */
337 int tcp_maxpersistidle = TCPTV_KEEP_IDLE;
338
339 /*
340 * TCP delack timer is set to 100 ms. Since the processing of timer list
341 * in fast mode will happen no faster than 100 ms, the delayed ack timer
342 * will fire some where between 100 and 200 ms.
343 */
344 int tcp_delack = TCP_RETRANSHZ / 10;
345
346 #if MPTCP
347 /*
348 * MP_JOIN retransmission of 3rd ACK will be every 500 msecs without backoff
349 */
350 int tcp_jack_rxmt = TCP_RETRANSHZ / 2;
351 #endif /* MPTCP */
352
353 static boolean_t tcp_itimer_done = FALSE;
354
355 static void tcp_remove_timer(struct tcpcb *tp);
356 static void tcp_sched_timerlist(uint32_t offset);
357 static u_int32_t tcp_run_conn_timer(struct tcpcb *tp, u_int16_t *mode,
358 u_int16_t probe_if_index);
359 static inline void tcp_set_lotimer_index(struct tcpcb *);
360 __private_extern__ void tcp_remove_from_time_wait(struct inpcb *inp);
361 static inline void tcp_update_mss_core(struct tcpcb *tp, struct ifnet *ifp);
362 __private_extern__ void tcp_report_stats(void);
363
364 static u_int64_t tcp_last_report_time;
365
366 /*
367 * Structure to store previously reported stats so that we can send
368 * incremental changes in each report interval.
369 */
370 struct tcp_last_report_stats {
371 u_int32_t tcps_connattempt;
372 u_int32_t tcps_accepts;
373 u_int32_t tcps_ecn_client_setup;
374 u_int32_t tcps_ecn_server_setup;
375 u_int32_t tcps_ecn_client_success;
376 u_int32_t tcps_ecn_server_success;
377 u_int32_t tcps_ecn_not_supported;
378 u_int32_t tcps_ecn_lost_syn;
379 u_int32_t tcps_ecn_lost_synack;
380 u_int32_t tcps_ecn_recv_ce;
381 u_int32_t tcps_ecn_recv_ece;
382 u_int32_t tcps_ecn_sent_ece;
383 u_int32_t tcps_ecn_conn_recv_ce;
384 u_int32_t tcps_ecn_conn_recv_ece;
385 u_int32_t tcps_ecn_conn_plnoce;
386 u_int32_t tcps_ecn_conn_pl_ce;
387 u_int32_t tcps_ecn_conn_nopl_ce;
388 u_int32_t tcps_ecn_fallback_synloss;
389 u_int32_t tcps_ecn_fallback_reorder;
390 u_int32_t tcps_ecn_fallback_ce;
391
392 /* TFO-related statistics */
393 u_int32_t tcps_tfo_syn_data_rcv;
394 u_int32_t tcps_tfo_cookie_req_rcv;
395 u_int32_t tcps_tfo_cookie_sent;
396 u_int32_t tcps_tfo_cookie_invalid;
397 u_int32_t tcps_tfo_cookie_req;
398 u_int32_t tcps_tfo_cookie_rcv;
399 u_int32_t tcps_tfo_syn_data_sent;
400 u_int32_t tcps_tfo_syn_data_acked;
401 u_int32_t tcps_tfo_syn_loss;
402 u_int32_t tcps_tfo_blackhole;
403 u_int32_t tcps_tfo_cookie_wrong;
404 u_int32_t tcps_tfo_no_cookie_rcv;
405 u_int32_t tcps_tfo_heuristics_disable;
406 u_int32_t tcps_tfo_sndblackhole;
407
408 /* MPTCP-related statistics */
409 u_int32_t tcps_mptcp_handover_attempt;
410 u_int32_t tcps_mptcp_interactive_attempt;
411 u_int32_t tcps_mptcp_aggregate_attempt;
412 u_int32_t tcps_mptcp_fp_handover_attempt;
413 u_int32_t tcps_mptcp_fp_interactive_attempt;
414 u_int32_t tcps_mptcp_fp_aggregate_attempt;
415 u_int32_t tcps_mptcp_heuristic_fallback;
416 u_int32_t tcps_mptcp_fp_heuristic_fallback;
417 u_int32_t tcps_mptcp_handover_success_wifi;
418 u_int32_t tcps_mptcp_handover_success_cell;
419 u_int32_t tcps_mptcp_interactive_success;
420 u_int32_t tcps_mptcp_aggregate_success;
421 u_int32_t tcps_mptcp_fp_handover_success_wifi;
422 u_int32_t tcps_mptcp_fp_handover_success_cell;
423 u_int32_t tcps_mptcp_fp_interactive_success;
424 u_int32_t tcps_mptcp_fp_aggregate_success;
425 u_int32_t tcps_mptcp_handover_cell_from_wifi;
426 u_int32_t tcps_mptcp_handover_wifi_from_cell;
427 u_int32_t tcps_mptcp_interactive_cell_from_wifi;
428 u_int64_t tcps_mptcp_handover_cell_bytes;
429 u_int64_t tcps_mptcp_interactive_cell_bytes;
430 u_int64_t tcps_mptcp_aggregate_cell_bytes;
431 u_int64_t tcps_mptcp_handover_all_bytes;
432 u_int64_t tcps_mptcp_interactive_all_bytes;
433 u_int64_t tcps_mptcp_aggregate_all_bytes;
434 u_int32_t tcps_mptcp_back_to_wifi;
435 u_int32_t tcps_mptcp_wifi_proxy;
436 u_int32_t tcps_mptcp_cell_proxy;
437 u_int32_t tcps_mptcp_triggered_cell;
438 };
439
440
441 /* Returns true if the timer is on the timer list */
442 #define TIMER_IS_ON_LIST(tp) ((tp)->t_flags & TF_TIMER_ONLIST)
443
444 /* Run the TCP timerlist atleast once every hour */
445 #define TCP_TIMERLIST_MAX_OFFSET (60 * 60 * TCP_RETRANSHZ)
446
447
448 static void add_to_time_wait_locked(struct tcpcb *tp, uint32_t delay);
449 static boolean_t tcp_garbage_collect(struct inpcb *, int);
450
451 #define TIMERENTRY_TO_TP(te) (__unsafe_forge_single(struct tcpcb *, ((uintptr_t)te - offsetof(struct tcpcb, tentry.le.le_next))))
452
453 #define VERIFY_NEXT_LINK(elm, field) do { \
454 if (LIST_NEXT((elm),field) != NULL && \
455 LIST_NEXT((elm),field)->field.le_prev != \
456 &((elm)->field.le_next)) \
457 panic("Bad link elm %p next->prev != elm", (elm)); \
458 } while(0)
459
460 #define VERIFY_PREV_LINK(elm, field) do { \
461 if (*(elm)->field.le_prev != (elm)) \
462 panic("Bad link elm %p prev->next != elm", (elm)); \
463 } while(0)
464
465 #define TCP_SET_TIMER_MODE(mode, i) do { \
466 if (IS_TIMER_HZ_10MS(i)) \
467 (mode) |= TCP_TIMERLIST_10MS_MODE; \
468 else if (IS_TIMER_HZ_100MS(i)) \
469 (mode) |= TCP_TIMERLIST_100MS_MODE; \
470 else \
471 (mode) |= TCP_TIMERLIST_500MS_MODE; \
472 } while(0)
473
474 #if (DEVELOPMENT || DEBUG)
475 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, mss_rec_medium,
476 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_mss_rec_medium, 0,
477 "Medium MSS based on recommendation in link status report");
478 SYSCTL_UINT(_net_inet_tcp, OID_AUTO, mss_rec_low,
479 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_mss_rec_low, 0,
480 "Low MSS based on recommendation in link status report");
481
482 static int32_t tcp_change_mss_recommended = 0;
483 static int
484 sysctl_change_mss_recommended SYSCTL_HANDLER_ARGS
485 {
486 #pragma unused(oidp, arg1, arg2)
487 int i, err = 0, changed = 0;
488 struct ifnet *ifp;
489 struct if_link_status ifsr;
490 struct if_cellular_status_v1 *new_cell_sr;
491 err = sysctl_io_number(req, tcp_change_mss_recommended,
492 sizeof(int32_t), &i, &changed);
493 if (changed) {
494 if (i < 0 || i > UINT16_MAX) {
495 return EINVAL;
496 }
497 ifnet_head_lock_shared();
498 TAILQ_FOREACH(ifp, &ifnet_head, if_link) {
499 if (IFNET_IS_CELLULAR(ifp)) {
500 bzero(&ifsr, sizeof(ifsr));
501 new_cell_sr = &ifsr.ifsr_u.ifsr_cell.if_cell_u.if_status_v1;
502 ifsr.ifsr_version = IF_CELLULAR_STATUS_REPORT_CURRENT_VERSION;
503 ifsr.ifsr_len = sizeof(*new_cell_sr);
504
505 /* Set MSS recommended */
506 new_cell_sr->valid_bitmask |= IF_CELL_UL_MSS_RECOMMENDED_VALID;
507 new_cell_sr->mss_recommended = (uint16_t)i;
508 err = ifnet_link_status_report(ifp, new_cell_sr, sizeof(new_cell_sr));
509 if (err == 0) {
510 tcp_change_mss_recommended = i;
511 } else {
512 break;
513 }
514 }
515 }
516 ifnet_head_done();
517 }
518 return err;
519 }
520
521 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, change_mss_recommended,
522 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_change_mss_recommended,
523 0, sysctl_change_mss_recommended, "IU", "Change MSS recommended");
524
525 SYSCTL_INT(_net_inet_tcp, OID_AUTO, report_stats_interval,
526 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_report_stats_interval, 0,
527 "Report stats interval");
528 #endif /* (DEVELOPMENT || DEBUG) */
529
530 /*
531 * Macro to compare two timers. If there is a reset of the sign bit,
532 * it is safe to assume that the timer has wrapped around. By doing
533 * signed comparision, we take care of wrap around such that the value
534 * with the sign bit reset is actually ahead of the other.
535 */
536 inline int32_t
timer_diff(uint32_t t1,uint32_t toff1,uint32_t t2,uint32_t toff2)537 timer_diff(uint32_t t1, uint32_t toff1, uint32_t t2, uint32_t toff2)
538 {
539 return (int32_t)((t1 + toff1) - (t2 + toff2));
540 }
541
542 /*
543 * Add to tcp timewait list, delay is given in milliseconds.
544 */
545 static void
add_to_time_wait_locked(struct tcpcb * tp,uint32_t delay)546 add_to_time_wait_locked(struct tcpcb *tp, uint32_t delay)
547 {
548 struct inpcbinfo *pcbinfo = &tcbinfo;
549 struct inpcb *inp = tp->t_inpcb;
550 uint32_t timer;
551
552 /* pcb list should be locked when we get here */
553 LCK_RW_ASSERT(&pcbinfo->ipi_lock, LCK_RW_ASSERT_EXCLUSIVE);
554
555 /* We may get here multiple times, so check */
556 if (!(inp->inp_flags2 & INP2_TIMEWAIT)) {
557 pcbinfo->ipi_twcount++;
558 inp->inp_flags2 |= INP2_TIMEWAIT;
559
560 /* Remove from global inp list */
561 LIST_REMOVE(inp, inp_list);
562 } else {
563 TAILQ_REMOVE(&tcp_tw_tailq, tp, t_twentry);
564 }
565
566 /* Compute the time at which this socket can be closed */
567 timer = tcp_now + delay;
568
569 /* We will use the TCPT_2MSL timer for tracking this delay */
570
571 if (TIMER_IS_ON_LIST(tp)) {
572 tcp_remove_timer(tp);
573 }
574 tp->t_timer[TCPT_2MSL] = timer;
575
576 TAILQ_INSERT_TAIL(&tcp_tw_tailq, tp, t_twentry);
577 }
578
579 void
add_to_time_wait(struct tcpcb * tp,uint32_t delay)580 add_to_time_wait(struct tcpcb *tp, uint32_t delay)
581 {
582 if (tp->t_inpcb->inp_socket->so_options & SO_NOWAKEFROMSLEEP) {
583 socket_post_kev_msg_closed(tp->t_inpcb->inp_socket);
584 }
585
586 tcp_del_fsw_flow(tp);
587
588 /* 19182803: Notify nstat that connection is closing before waiting. */
589 nstat_pcb_detach(tp->t_inpcb);
590
591 #if CONTENT_FILTER
592 if ((tp->t_inpcb->inp_socket->so_flags & SOF_CONTENT_FILTER) != 0) {
593 /* If filter present, allow filter to finish processing all queued up data before adding to time wait queue */
594 (void) cfil_sock_tcp_add_time_wait(tp->t_inpcb->inp_socket);
595 } else
596 #endif /* CONTENT_FILTER */
597 {
598 add_to_time_wait_now(tp, delay);
599 }
600 }
601
602 void
add_to_time_wait_now(struct tcpcb * tp,uint32_t delay)603 add_to_time_wait_now(struct tcpcb *tp, uint32_t delay)
604 {
605 struct inpcbinfo *pcbinfo = &tcbinfo;
606
607 if (!lck_rw_try_lock_exclusive(&pcbinfo->ipi_lock)) {
608 socket_unlock(tp->t_inpcb->inp_socket, 0);
609 lck_rw_lock_exclusive(&pcbinfo->ipi_lock);
610 socket_lock(tp->t_inpcb->inp_socket, 0);
611 }
612 add_to_time_wait_locked(tp, delay);
613 lck_rw_done(&pcbinfo->ipi_lock);
614
615 inpcb_gc_sched(pcbinfo, INPCB_TIMER_LAZY);
616 }
617
618 /* If this is on time wait queue, remove it. */
619 void
tcp_remove_from_time_wait(struct inpcb * inp)620 tcp_remove_from_time_wait(struct inpcb *inp)
621 {
622 struct tcpcb *tp = intotcpcb(inp);
623 if (inp->inp_flags2 & INP2_TIMEWAIT) {
624 TAILQ_REMOVE(&tcp_tw_tailq, tp, t_twentry);
625 }
626 }
627
628 static boolean_t
tcp_garbage_collect(struct inpcb * inp,int istimewait)629 tcp_garbage_collect(struct inpcb *inp, int istimewait)
630 {
631 boolean_t active = FALSE;
632 struct socket *so, *mp_so = NULL;
633 struct tcpcb *tp;
634
635 so = inp->inp_socket;
636 tp = intotcpcb(inp);
637
638 if (so->so_flags & SOF_MP_SUBFLOW) {
639 mp_so = mptetoso(tptomptp(tp)->mpt_mpte);
640 if (!socket_try_lock(mp_so)) {
641 mp_so = NULL;
642 active = TRUE;
643 goto out;
644 }
645 if (mpsotomppcb(mp_so)->mpp_inside > 0) {
646 os_log(mptcp_log_handle, "%s - %lx: Still inside %d usecount %d\n", __func__,
647 (unsigned long)VM_KERNEL_ADDRPERM(mpsotompte(mp_so)),
648 mpsotomppcb(mp_so)->mpp_inside,
649 mp_so->so_usecount);
650 socket_unlock(mp_so, 0);
651 mp_so = NULL;
652 active = TRUE;
653 goto out;
654 }
655 /* We call socket_unlock with refcount further below */
656 mp_so->so_usecount++;
657 tptomptp(tp)->mpt_mpte->mpte_mppcb->mpp_inside++;
658 }
659
660 /*
661 * Skip if still in use or busy; it would have been more efficient
662 * if we were to test so_usecount against 0, but this isn't possible
663 * due to the current implementation of tcp_dropdropablreq() where
664 * overflow sockets that are eligible for garbage collection have
665 * their usecounts set to 1.
666 */
667 if (!lck_mtx_try_lock_spin(&inp->inpcb_mtx)) {
668 active = TRUE;
669 goto out;
670 }
671
672 /* Check again under the lock */
673 if (so->so_usecount > 1) {
674 if (inp->inp_wantcnt == WNT_STOPUSING) {
675 active = TRUE;
676 }
677 lck_mtx_unlock(&inp->inpcb_mtx);
678 goto out;
679 }
680
681 if (istimewait && TSTMP_GEQ(tcp_now, tp->t_timer[TCPT_2MSL]) &&
682 tp->t_state != TCPS_CLOSED) {
683 /* Become a regular mutex */
684 lck_mtx_convert_spin(&inp->inpcb_mtx);
685 tcp_close(tp);
686 }
687
688 /*
689 * Overflowed socket dropped from the listening queue? Do this
690 * only if we are called to clean up the time wait slots, since
691 * tcp_dropdropablreq() considers a socket to have been fully
692 * dropped after add_to_time_wait() is finished.
693 * Also handle the case of connections getting closed by the peer
694 * while in the queue as seen with rdar://6422317
695 *
696 */
697 if (so->so_usecount == 1 &&
698 ((istimewait && (so->so_flags & SOF_OVERFLOW)) ||
699 ((tp != NULL) && (tp->t_state == TCPS_CLOSED) &&
700 (so->so_head != NULL) &&
701 ((so->so_state & (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE)) ==
702 (SS_INCOMP | SS_CANTSENDMORE | SS_CANTRCVMORE))))) {
703 if (inp->inp_state != INPCB_STATE_DEAD) {
704 /* Become a regular mutex */
705 lck_mtx_convert_spin(&inp->inpcb_mtx);
706 if (SOCK_CHECK_DOM(so, PF_INET6)) {
707 in6_pcbdetach(inp);
708 } else {
709 in_pcbdetach(inp);
710 }
711 }
712 VERIFY(so->so_usecount > 0);
713 so->so_usecount--;
714 if (inp->inp_wantcnt == WNT_STOPUSING) {
715 active = TRUE;
716 }
717 lck_mtx_unlock(&inp->inpcb_mtx);
718 goto out;
719 } else if (inp->inp_wantcnt != WNT_STOPUSING) {
720 lck_mtx_unlock(&inp->inpcb_mtx);
721 active = FALSE;
722 goto out;
723 }
724
725 /*
726 * We get here because the PCB is no longer searchable
727 * (WNT_STOPUSING); detach (if needed) and dispose if it is dead
728 * (usecount is 0). This covers all cases, including overflow
729 * sockets and those that are considered as "embryonic",
730 * i.e. created by sonewconn() in TCP input path, and have
731 * not yet been committed. For the former, we reduce the usecount
732 * to 0 as done by the code above. For the latter, the usecount
733 * would have reduced to 0 as part calling soabort() when the
734 * socket is dropped at the end of tcp_input().
735 */
736 if (so->so_usecount == 0) {
737 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
738 struct tcpcb *, tp, int32_t, TCPS_CLOSED);
739 /* Become a regular mutex */
740 lck_mtx_convert_spin(&inp->inpcb_mtx);
741
742 /*
743 * If this tp still happens to be on the timer list,
744 * take it out
745 */
746 if (TIMER_IS_ON_LIST(tp)) {
747 tcp_remove_timer(tp);
748 }
749
750 if (inp->inp_state != INPCB_STATE_DEAD) {
751 if (SOCK_CHECK_DOM(so, PF_INET6)) {
752 in6_pcbdetach(inp);
753 } else {
754 in_pcbdetach(inp);
755 }
756 }
757
758 if (mp_so) {
759 mptcp_subflow_del(tptomptp(tp)->mpt_mpte, tp->t_mpsub);
760
761 /* so is now unlinked from mp_so - let's drop the lock */
762 socket_unlock(mp_so, 1);
763 mp_so = NULL;
764 }
765
766 in_pcbdispose(inp);
767 active = FALSE;
768 goto out;
769 }
770
771 lck_mtx_unlock(&inp->inpcb_mtx);
772 active = TRUE;
773
774 out:
775 if (mp_so) {
776 socket_unlock(mp_so, 1);
777 }
778
779 return active;
780 }
781
782 /*
783 * TCP garbage collector callback (inpcb_timer_func_t).
784 *
785 * Returns the number of pcbs that will need to be gc-ed soon,
786 * returnining > 0 will keep timer active.
787 */
788 void
tcp_gc(struct inpcbinfo * ipi)789 tcp_gc(struct inpcbinfo *ipi)
790 {
791 struct inpcb *inp, *nxt;
792 struct tcpcb *tw_tp, *tw_ntp;
793 #if KDEBUG
794 static int tws_checked = 0;
795 #endif
796
797 KERNEL_DEBUG(DBG_FNC_TCP_SLOW | DBG_FUNC_START, 0, 0, 0, 0, 0);
798
799 /*
800 * Update tcp_now here as it may get used while
801 * processing the slow timer.
802 */
803 calculate_tcp_clock();
804
805 /*
806 * Garbage collect socket/tcpcb: We need to acquire the list lock
807 * exclusively to do this
808 */
809
810 if (lck_rw_try_lock_exclusive(&ipi->ipi_lock) == FALSE) {
811 /* don't sweat it this time; cleanup was done last time */
812 if (tcp_gc_done == TRUE) {
813 tcp_gc_done = FALSE;
814 KERNEL_DEBUG(DBG_FNC_TCP_SLOW | DBG_FUNC_END,
815 tws_checked, cur_tw_slot, 0, 0, 0);
816 /* Lock upgrade failed, give up this round */
817 os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
818 return;
819 }
820 /* Upgrade failed, lost lock now take it again exclusive */
821 lck_rw_lock_exclusive(&ipi->ipi_lock);
822 }
823 tcp_gc_done = TRUE;
824
825 LIST_FOREACH_SAFE(inp, &tcb, inp_list, nxt) {
826 if (tcp_garbage_collect(inp, 0)) {
827 os_atomic_inc(&ipi->ipi_gc_req.intimer_fast, relaxed);
828 }
829 }
830
831 /* Now cleanup the time wait ones */
832 TAILQ_FOREACH_SAFE(tw_tp, &tcp_tw_tailq, t_twentry, tw_ntp) {
833 /*
834 * We check the timestamp here without holding the
835 * socket lock for better performance. If there are
836 * any pcbs in time-wait, the timer will get rescheduled.
837 * Hence some error in this check can be tolerated.
838 *
839 * Sometimes a socket on time-wait queue can be closed if
840 * 2MSL timer expired but the application still has a
841 * usecount on it.
842 */
843 if (tw_tp->t_state == TCPS_CLOSED ||
844 TSTMP_GEQ(tcp_now, tw_tp->t_timer[TCPT_2MSL])) {
845 if (tcp_garbage_collect(tw_tp->t_inpcb, 1)) {
846 os_atomic_inc(&ipi->ipi_gc_req.intimer_lazy, relaxed);
847 }
848 }
849 }
850
851 /* take into account pcbs that are still in time_wait_slots */
852 os_atomic_add(&ipi->ipi_gc_req.intimer_lazy, ipi->ipi_twcount, relaxed);
853
854 lck_rw_done(&ipi->ipi_lock);
855
856 /* Clean up the socache while we are here */
857 if (so_cache_timer()) {
858 os_atomic_inc(&ipi->ipi_gc_req.intimer_lazy, relaxed);
859 }
860
861 KERNEL_DEBUG(DBG_FNC_TCP_SLOW | DBG_FUNC_END, tws_checked,
862 cur_tw_slot, 0, 0, 0);
863
864 return;
865 }
866
867 /*
868 * Cancel all timers for TCP tp.
869 */
870 void
tcp_canceltimers(struct tcpcb * tp)871 tcp_canceltimers(struct tcpcb *tp)
872 {
873 int i;
874
875 tcp_remove_timer(tp);
876 for (i = 0; i < TCPT_NTIMERS; i++) {
877 tp->t_timer[i] = 0;
878 }
879 tp->tentry.timer_start = tcp_now;
880 tp->tentry.index = TCPT_NONE;
881 }
882
883 int tcp_syn_backoff[TCP_MAXRXTSHIFT + 1] =
884 { 1, 1, 1, 1, 1, 2, 4, 8, 16, 32, 64, 64, 64 };
885
886 int tcp_backoff[TCP_MAXRXTSHIFT + 1] =
887 { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };
888
889 static int tcp_totbackoff = 511; /* sum of tcp_backoff[] */
890
891 void
tcp_rexmt_save_state(struct tcpcb * tp)892 tcp_rexmt_save_state(struct tcpcb *tp)
893 {
894 u_int32_t fsize;
895 if (TSTMP_SUPPORTED(tp)) {
896 /*
897 * Since timestamps are supported on the connection,
898 * we can do recovery as described in rfc 4015.
899 */
900 fsize = tp->snd_max - tp->snd_una;
901 tp->snd_ssthresh_prev = max(fsize, tp->snd_ssthresh);
902 tp->snd_recover_prev = tp->snd_recover;
903 } else {
904 /*
905 * Timestamp option is not supported on this connection.
906 * Record ssthresh and cwnd so they can
907 * be recovered if this turns out to be a "bad" retransmit.
908 * A retransmit is considered "bad" if an ACK for this
909 * segment is received within RTT/2 interval; the assumption
910 * here is that the ACK was already in flight. See
911 * "On Estimating End-to-End Network Path Properties" by
912 * Allman and Paxson for more details.
913 */
914 tp->snd_cwnd_prev = tp->snd_cwnd;
915 tp->snd_ssthresh_prev = tp->snd_ssthresh;
916 tp->snd_recover_prev = tp->snd_recover;
917 if (IN_FASTRECOVERY(tp)) {
918 tp->t_flags |= TF_WASFRECOVERY;
919 } else {
920 tp->t_flags &= ~TF_WASFRECOVERY;
921 }
922 }
923 tp->t_srtt_prev = (tp->t_srtt >> TCP_RTT_SHIFT) + 2;
924 tp->t_rttvar_prev = (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
925 tp->t_flagsext &= ~(TF_RECOMPUTE_RTT);
926 }
927
928 /*
929 * Revert to the older segment size if there is an indication that PMTU
930 * blackhole detection was not needed.
931 */
932 void
tcp_pmtud_revert_segment_size(struct tcpcb * tp)933 tcp_pmtud_revert_segment_size(struct tcpcb *tp)
934 {
935 int32_t optlen;
936
937 VERIFY(tp->t_pmtud_saved_maxopd > 0);
938 tp->t_flags |= TF_PMTUD;
939 tp->t_flags &= ~TF_BLACKHOLE;
940 optlen = tp->t_maxopd - tp->t_maxseg;
941 tp->t_maxopd = tp->t_pmtud_saved_maxopd;
942 tp->t_maxseg = tp->t_maxopd - optlen;
943
944 /*
945 * Reset the slow-start flight size as it
946 * may depend on the new MSS
947 */
948 if (CC_ALGO(tp)->cwnd_init != NULL) {
949 CC_ALGO(tp)->cwnd_init(tp);
950 }
951
952 if (TCP_USE_RLEDBAT(tp, tp->t_inpcb->inp_socket) &&
953 tcp_cc_rledbat.rwnd_init != NULL) {
954 tcp_cc_rledbat.rwnd_init(tp);
955 }
956
957 tp->t_pmtud_start_ts = 0;
958 tcpstat.tcps_pmtudbh_reverted++;
959
960 /* change MSS according to recommendation, if there was one */
961 tcp_update_mss_locked(tp->t_inpcb->inp_socket, NULL);
962 }
963
964 static uint32_t
tcp_pmtud_black_holed_next_mss(struct tcpcb * tp)965 tcp_pmtud_black_holed_next_mss(struct tcpcb *tp)
966 {
967 /* Reduce the MSS to intermediary value */
968 if (tp->t_maxopd > tcp_pmtud_black_hole_mss) {
969 return tcp_pmtud_black_hole_mss;
970 } else {
971 if (tp->t_inpcb->inp_vflag & INP_IPV4) {
972 return tcp_mssdflt;
973 } else {
974 return tcp_v6mssdflt;
975 }
976 }
977 }
978
979 /*
980 * Send a packet designed to force a response
981 * if the peer is up and reachable:
982 * either an ACK if the connection is still alive,
983 * or an RST if the peer has closed the connection
984 * due to timeout or reboot.
985 * Using sequence number tp->snd_una-1
986 * causes the transmitted zero-length segment
987 * to lie outside the receive window;
988 * by the protocol spec, this requires the
989 * correspondent TCP to respond.
990 */
991 static bool
tcp_send_keep_alive(struct tcpcb * tp)992 tcp_send_keep_alive(struct tcpcb *tp)
993 {
994 struct tcptemp *__single t_template;
995 struct mbuf *__single m;
996
997 tcpstat.tcps_keepprobe++;
998 t_template = tcp_maketemplate(tp, &m);
999 if (t_template != NULL) {
1000 struct inpcb *inp = tp->t_inpcb;
1001 struct tcp_respond_args tra;
1002
1003 bzero(&tra, sizeof(tra));
1004 tra.nocell = INP_NO_CELLULAR(inp) ? 1 : 0;
1005 tra.noexpensive = INP_NO_EXPENSIVE(inp) ? 1 : 0;
1006 tra.noconstrained = INP_NO_CONSTRAINED(inp) ? 1 : 0;
1007 tra.awdl_unrestricted = INP_AWDL_UNRESTRICTED(inp) ? 1 : 0;
1008 tra.intcoproc_allowed = INP_INTCOPROC_ALLOWED(inp) ? 1 : 0;
1009 tra.management_allowed = INP_MANAGEMENT_ALLOWED(inp) ? 1 : 0;
1010 tra.keep_alive = 1;
1011 if (tp->t_inpcb->inp_flags & INP_BOUND_IF) {
1012 tra.ifscope = tp->t_inpcb->inp_boundifp->if_index;
1013 } else {
1014 tra.ifscope = IFSCOPE_NONE;
1015 }
1016 tcp_respond(tp, t_template->tt_ipgen,
1017 &t_template->tt_t, (struct mbuf *)NULL,
1018 tp->rcv_nxt, tp->snd_una - 1, 0, &tra);
1019 (void) m_free(m);
1020 return true;
1021 } else {
1022 return false;
1023 }
1024 }
1025
1026 /*
1027 * TCP timer processing.
1028 */
1029 struct tcpcb *
tcp_timers(struct tcpcb * tp,int timer)1030 tcp_timers(struct tcpcb *tp, int timer)
1031 {
1032 int32_t rexmt, optlen = 0, idle_time = 0;
1033 struct socket *so;
1034 u_int64_t accsleep_ms;
1035 u_int64_t last_sleep_ms = 0;
1036
1037 so = tp->t_inpcb->inp_socket;
1038 idle_time = tcp_now - tp->t_rcvtime;
1039
1040 switch (timer) {
1041 /*
1042 * 2 MSL timeout in shutdown went off. If we're closed but
1043 * still waiting for peer to close and connection has been idle
1044 * too long, or if 2MSL time is up from TIME_WAIT or FIN_WAIT_2,
1045 * delete connection control block.
1046 * Otherwise, (this case shouldn't happen) check again in a bit
1047 * we keep the socket in the main list in that case.
1048 */
1049 case TCPT_2MSL:
1050 tcp_free_sackholes(tp);
1051 if (tp->t_state != TCPS_TIME_WAIT &&
1052 tp->t_state != TCPS_FIN_WAIT_2 &&
1053 ((idle_time > 0) && (idle_time < TCP_CONN_MAXIDLE(tp)))) {
1054 tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp,
1055 (u_int32_t)TCP_CONN_KEEPINTVL(tp));
1056 } else {
1057 if (tp->t_state == TCPS_FIN_WAIT_2) {
1058 TCP_LOG_DROP_PCB(NULL, NULL, tp, false,
1059 "FIN wait timeout drop");
1060 tcpstat.tcps_fin_timeout_drops++;
1061 tp = tcp_drop(tp, 0);
1062 } else {
1063 tp = tcp_close(tp);
1064 }
1065 return tp;
1066 }
1067 break;
1068
1069 /*
1070 * Retransmission timer went off. Message has not
1071 * been acked within retransmit interval. Back off
1072 * to a longer retransmit interval and retransmit one segment.
1073 */
1074 case TCPT_REXMT:
1075 absolutetime_to_nanoseconds(mach_absolutetime_asleep,
1076 &accsleep_ms);
1077 accsleep_ms = accsleep_ms / 1000000UL;
1078 if (accsleep_ms > tp->t_accsleep_ms) {
1079 last_sleep_ms = accsleep_ms - tp->t_accsleep_ms;
1080 }
1081 /*
1082 * Drop a connection in the retransmit timer
1083 * 1. If we have retransmitted more than TCP_MAXRXTSHIFT
1084 * times
1085 * 2. If the time spent in this retransmission episode is
1086 * more than the time limit set with TCP_RXT_CONNDROPTIME
1087 * socket option
1088 * 3. If TCP_RXT_FINDROP socket option was set and
1089 * we have already retransmitted the FIN 3 times without
1090 * receiving an ack
1091 */
1092 if (++tp->t_rxtshift > TCP_MAXRXTSHIFT ||
1093 (tp->t_rxt_conndroptime > 0 && tp->t_rxtstart > 0 &&
1094 (tcp_now - tp->t_rxtstart) >= tp->t_rxt_conndroptime) ||
1095 ((tp->t_flagsext & TF_RXTFINDROP) != 0 &&
1096 (tp->t_flags & TF_SENTFIN) != 0 && tp->t_rxtshift >= 4) ||
1097 (tp->t_rxtshift > 4 && last_sleep_ms >= TCP_SLEEP_TOO_LONG)) {
1098 if (tp->t_state == TCPS_ESTABLISHED &&
1099 tp->t_rxt_minimum_timeout > 0) {
1100 /*
1101 * Avoid dropping a connection if minimum
1102 * timeout is set and that time did not
1103 * pass. We will retry sending
1104 * retransmissions at the maximum interval
1105 */
1106 if (TSTMP_LT(tcp_now, (tp->t_rxtstart +
1107 tp->t_rxt_minimum_timeout))) {
1108 tp->t_rxtshift = TCP_MAXRXTSHIFT - 1;
1109 goto retransmit_packet;
1110 }
1111 }
1112 if ((tp->t_flagsext & TF_RXTFINDROP) != 0) {
1113 tcpstat.tcps_rxtfindrop++;
1114 } else if (last_sleep_ms >= TCP_SLEEP_TOO_LONG) {
1115 tcpstat.tcps_drop_after_sleep++;
1116 } else {
1117 tcpstat.tcps_timeoutdrop++;
1118 }
1119 if (tp->t_rxtshift >= TCP_MAXRXTSHIFT) {
1120 if (TCP_ECN_ENABLED(tp)) {
1121 INP_INC_IFNET_STAT(tp->t_inpcb,
1122 ecn_on.rxmit_drop);
1123 } else {
1124 INP_INC_IFNET_STAT(tp->t_inpcb,
1125 ecn_off.rxmit_drop);
1126 }
1127 }
1128 tp->t_rxtshift = TCP_MAXRXTSHIFT;
1129 soevent(so,
1130 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_TIMEOUT));
1131
1132 if (TCP_ECN_ENABLED(tp) &&
1133 tp->t_state == TCPS_ESTABLISHED) {
1134 tcp_heuristic_ecn_droprxmt(tp);
1135 }
1136
1137 TCP_LOG_DROP_PCB(NULL, NULL, tp, false,
1138 "retransmission timeout drop");
1139 tp = tcp_drop(tp, tp->t_softerror ?
1140 tp->t_softerror : ETIMEDOUT);
1141
1142 break;
1143 }
1144 retransmit_packet:
1145 tcpstat.tcps_rexmttimeo++;
1146 tp->t_accsleep_ms = accsleep_ms;
1147
1148 if (tp->t_rxtshift == 1 &&
1149 tp->t_state == TCPS_ESTABLISHED) {
1150 /* Set the time at which retransmission started. */
1151 tp->t_rxtstart = tcp_now;
1152
1153 /*
1154 * if this is the first retransmit timeout, save
1155 * the state so that we can recover if the timeout
1156 * is spurious.
1157 */
1158 tcp_rexmt_save_state(tp);
1159 tcp_ccdbg_trace(tp, NULL, TCP_CC_FIRST_REXMT);
1160 }
1161 #if MPTCP
1162 if ((tp->t_rxtshift >= mptcp_fail_thresh) &&
1163 (tp->t_state == TCPS_ESTABLISHED) &&
1164 (tp->t_mpflags & TMPF_MPTCP_TRUE)) {
1165 mptcp_act_on_txfail(so);
1166 }
1167
1168 if (TCPS_HAVEESTABLISHED(tp->t_state) &&
1169 (so->so_flags & SOF_MP_SUBFLOW)) {
1170 struct mptses *mpte = tptomptp(tp)->mpt_mpte;
1171
1172 if (mpte->mpte_svctype == MPTCP_SVCTYPE_HANDOVER ||
1173 mpte->mpte_svctype == MPTCP_SVCTYPE_PURE_HANDOVER) {
1174 mptcp_check_subflows_and_add(mpte);
1175 }
1176 }
1177 #endif /* MPTCP */
1178
1179 if (tp->t_adaptive_wtimo > 0 &&
1180 tp->t_rxtshift > tp->t_adaptive_wtimo &&
1181 TCPS_HAVEESTABLISHED(tp->t_state)) {
1182 /* Send an event to the application */
1183 soevent(so,
1184 (SO_FILT_HINT_LOCKED |
1185 SO_FILT_HINT_ADAPTIVE_WTIMO));
1186 }
1187
1188 /*
1189 * If this is a retransmit timeout after PTO, the PTO
1190 * was not effective
1191 */
1192 if (tp->t_flagsext & TF_SENT_TLPROBE) {
1193 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1194 tcpstat.tcps_rto_after_pto++;
1195 }
1196
1197 if (tp->t_flagsext & TF_DELAY_RECOVERY) {
1198 /*
1199 * Retransmit timer fired before entering recovery
1200 * on a connection with packet re-ordering. This
1201 * suggests that the reordering metrics computed
1202 * are not accurate.
1203 */
1204 tp->t_reorderwin = 0;
1205 tp->t_timer[TCPT_DELAYFR] = 0;
1206 tp->t_flagsext &= ~(TF_DELAY_RECOVERY);
1207 }
1208
1209 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
1210 tp->t_state == TCPS_SYN_RECEIVED) {
1211 tcp_disable_tfo(tp);
1212 }
1213
1214 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
1215 !(tp->t_tfo_flags & TFO_F_HEURISTIC_DONE) &&
1216 (tp->t_tfo_stats & TFO_S_SYN_DATA_SENT) &&
1217 !(tp->t_tfo_flags & TFO_F_NO_SNDPROBING) &&
1218 ((tp->t_state != TCPS_SYN_SENT && tp->t_rxtshift > 1) ||
1219 tp->t_rxtshift > 4)) {
1220 /*
1221 * For regular retransmissions, a first one is being
1222 * done for tail-loss probe.
1223 * Thus, if rxtshift > 1, this means we have sent the segment
1224 * a total of 3 times.
1225 *
1226 * If we are in SYN-SENT state, then there is no tail-loss
1227 * probe thus we have to let rxtshift go up to 3.
1228 */
1229 tcp_heuristic_tfo_middlebox(tp);
1230
1231 so->so_error = ENODATA;
1232 soevent(so,
1233 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MP_SUB_ERROR));
1234 sorwakeup(so);
1235 sowwakeup(so);
1236
1237 tp->t_tfo_stats |= TFO_S_SEND_BLACKHOLE;
1238 tcpstat.tcps_tfo_sndblackhole++;
1239 }
1240
1241 if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
1242 !(tp->t_tfo_flags & TFO_F_HEURISTIC_DONE) &&
1243 (tp->t_tfo_stats & TFO_S_SYN_DATA_ACKED) &&
1244 tp->t_rxtshift > 3) {
1245 if (TSTMP_GT(tp->t_sndtime - 10 * TCP_RETRANSHZ, tp->t_rcvtime)) {
1246 tcp_heuristic_tfo_middlebox(tp);
1247
1248 so->so_error = ENODATA;
1249 soevent(so,
1250 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MP_SUB_ERROR));
1251 sorwakeup(so);
1252 sowwakeup(so);
1253 }
1254 }
1255
1256 if (tp->t_state == TCPS_SYN_SENT) {
1257 rexmt = TCP_REXMTVAL(tp) * tcp_syn_backoff[tp->t_rxtshift];
1258 tp->t_stat.synrxtshift = tp->t_rxtshift;
1259 tp->t_stat.rxmitsyns++;
1260
1261 /* When retransmitting, disable TFO */
1262 if (TFO_ENABLED(tp) &&
1263 !(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE)) {
1264 tcp_disable_tfo(tp);
1265 tp->t_tfo_flags |= TFO_F_SYN_LOSS;
1266 }
1267 } else {
1268 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
1269 }
1270
1271 TCPT_RANGESET(tp->t_rxtcur, rexmt, tp->t_rttmin, TCPTV_REXMTMAX,
1272 TCP_ADD_REXMTSLOP(tp));
1273 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
1274
1275 TCP_LOG_RTT_INFO(tp);
1276
1277 if (INP_WAIT_FOR_IF_FEEDBACK(tp->t_inpcb)) {
1278 goto fc_output;
1279 }
1280
1281 tcp_free_sackholes(tp);
1282 if (TCP_RACK_ENABLED(tp)) {
1283 tcp_segs_clear_sacked(tp);
1284 tcp_rack_loss_on_rto(tp, true);
1285 }
1286 /*
1287 * Check for potential Path MTU Discovery Black Hole
1288 */
1289 if (tcp_pmtud_black_hole_detect &&
1290 !(tp->t_flagsext & TF_NOBLACKHOLE_DETECTION) &&
1291 (tp->t_state == TCPS_ESTABLISHED)) {
1292 if ((tp->t_flags & TF_PMTUD) &&
1293 tp->t_pmtud_lastseg_size > tcp_pmtud_black_holed_next_mss(tp) &&
1294 tp->t_rxtshift == 2) {
1295 /*
1296 * Enter Path MTU Black-hole Detection mechanism:
1297 * - Disable Path MTU Discovery (IP "DF" bit).
1298 * - Reduce MTU to lower value than what we
1299 * negotiated with the peer.
1300 */
1301 /* Disable Path MTU Discovery for now */
1302 tp->t_flags &= ~TF_PMTUD;
1303 /* Record that we may have found a black hole */
1304 tp->t_flags |= TF_BLACKHOLE;
1305 optlen = tp->t_maxopd - tp->t_maxseg;
1306 /* Keep track of previous MSS */
1307 tp->t_pmtud_saved_maxopd = tp->t_maxopd;
1308 tp->t_pmtud_start_ts = tcp_now;
1309 if (tp->t_pmtud_start_ts == 0) {
1310 tp->t_pmtud_start_ts++;
1311 }
1312 /* Reduce the MSS to intermediary value */
1313 tp->t_maxopd = tcp_pmtud_black_holed_next_mss(tp);
1314 tp->t_maxseg = tp->t_maxopd - optlen;
1315
1316 /*
1317 * Reset the slow-start flight size
1318 * as it may depend on the new MSS
1319 */
1320 if (CC_ALGO(tp)->cwnd_init != NULL) {
1321 CC_ALGO(tp)->cwnd_init(tp);
1322 }
1323 tp->snd_cwnd = tp->t_maxseg;
1324
1325 if (TCP_USE_RLEDBAT(tp, so) &&
1326 tcp_cc_rledbat.rwnd_init != NULL) {
1327 tcp_cc_rledbat.rwnd_init(tp);
1328 }
1329 }
1330 /*
1331 * If further retransmissions are still
1332 * unsuccessful with a lowered MTU, maybe this
1333 * isn't a Black Hole and we restore the previous
1334 * MSS and blackhole detection flags.
1335 */
1336 else {
1337 if ((tp->t_flags & TF_BLACKHOLE) &&
1338 (tp->t_rxtshift > 4)) {
1339 tcp_pmtud_revert_segment_size(tp);
1340 tp->snd_cwnd = tp->t_maxseg;
1341 }
1342 }
1343 }
1344
1345 /*
1346 * Disable rfc1323 and rfc1644 if we haven't got any
1347 * response to our SYN (after we reach the threshold)
1348 * to work-around some broken terminal servers (most of
1349 * which have hopefully been retired) that have bad VJ
1350 * header compression code which trashes TCP segments
1351 * containing unknown-to-them TCP options.
1352 * Do this only on non-local connections.
1353 */
1354 if (tp->t_state == TCPS_SYN_SENT &&
1355 tp->t_rxtshift == tcp_broken_peer_syn_rxmit_thres) {
1356 tp->t_flags &= ~(TF_REQ_SCALE | TF_REQ_TSTMP);
1357 }
1358
1359 /*
1360 * If losing, let the lower level know and try for
1361 * a better route. Also, if we backed off this far,
1362 * our srtt estimate is probably bogus. Clobber it
1363 * so we'll take the next rtt measurement as our srtt;
1364 * move the current srtt into rttvar to keep the current
1365 * retransmit times until then.
1366 */
1367 if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
1368 if (!(tp->t_inpcb->inp_vflag & INP_IPV4)) {
1369 in6_losing(tp->t_inpcb);
1370 } else {
1371 in_losing(tp->t_inpcb);
1372 }
1373 tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
1374 tp->t_srtt = 0;
1375 }
1376 tp->snd_nxt = tp->snd_una;
1377 /*
1378 * Note: We overload snd_recover to function also as the
1379 * snd_last variable described in RFC 2582
1380 */
1381 tp->snd_recover = tp->snd_max;
1382 /*
1383 * Force a segment to be sent.
1384 */
1385 tp->t_flags |= TF_ACKNOW;
1386
1387 /* If timing a segment in this window, stop the timer */
1388 tp->t_rtttime = 0;
1389
1390 if (!IN_FASTRECOVERY(tp) && tp->t_rxtshift == 1) {
1391 tcpstat.tcps_tailloss_rto++;
1392 }
1393
1394
1395 /*
1396 * RFC 5681 says: when a TCP sender detects segment loss
1397 * using retransmit timer and the given segment has already
1398 * been retransmitted by way of the retransmission timer at
1399 * least once, the value of ssthresh is held constant
1400 */
1401 if (tp->t_rxtshift == 1 &&
1402 CC_ALGO(tp)->after_timeout != NULL) {
1403 CC_ALGO(tp)->after_timeout(tp);
1404 /*
1405 * CWR notifications are to be sent on new data
1406 * right after Fast Retransmits and ECE
1407 * notification receipts.
1408 */
1409 if (!TCP_ACC_ECN_ON(tp) && TCP_ECN_ENABLED(tp)) {
1410 tp->ecn_flags |= TE_SENDCWR;
1411 }
1412 }
1413
1414 EXIT_FASTRECOVERY(tp);
1415
1416 /* Exit cwnd non validated phase */
1417 tp->t_flagsext &= ~TF_CWND_NONVALIDATED;
1418
1419
1420 fc_output:
1421 tcp_ccdbg_trace(tp, NULL, TCP_CC_REXMT_TIMEOUT);
1422
1423 (void) tcp_output(tp);
1424 break;
1425
1426 /*
1427 * Persistance timer into zero window.
1428 * Force a byte to be output, if possible.
1429 */
1430 case TCPT_PERSIST:
1431 tcpstat.tcps_persisttimeo++;
1432 /*
1433 * Hack: if the peer is dead/unreachable, we do not
1434 * time out if the window is closed. After a full
1435 * backoff, drop the connection if the idle time
1436 * (no responses to probes) reaches the maximum
1437 * backoff that we would use if retransmitting.
1438 *
1439 * Drop the connection if we reached the maximum allowed time for
1440 * Zero Window Probes without a non-zero update from the peer.
1441 * See rdar://5805356
1442 */
1443 if ((tp->t_rxtshift == TCP_MAXRXTSHIFT &&
1444 (idle_time >= tcp_maxpersistidle ||
1445 idle_time >= TCP_REXMTVAL(tp) * tcp_totbackoff)) ||
1446 ((tp->t_persist_stop != 0) &&
1447 TSTMP_LEQ(tp->t_persist_stop, tcp_now))) {
1448 TCP_LOG_DROP_PCB(NULL, NULL, tp, false, "persist timeout drop");
1449 tcpstat.tcps_persistdrop++;
1450 soevent(so,
1451 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_TIMEOUT));
1452 tp = tcp_drop(tp, ETIMEDOUT);
1453 break;
1454 }
1455 tcp_setpersist(tp);
1456 tp->t_flagsext |= TF_FORCE;
1457 (void) tcp_output(tp);
1458 tp->t_flagsext &= ~TF_FORCE;
1459 break;
1460
1461 /*
1462 * Keep-alive timer went off; send something
1463 * or drop connection if idle for too long.
1464 */
1465 case TCPT_KEEP:
1466 #if FLOW_DIVERT
1467 if (tp->t_inpcb->inp_socket->so_flags & SOF_FLOW_DIVERT) {
1468 break;
1469 }
1470 #endif /* FLOW_DIVERT */
1471
1472 tcpstat.tcps_keeptimeo++;
1473 #if MPTCP
1474 /*
1475 * Regular TCP connections do not send keepalives after closing
1476 * MPTCP must not also, after sending Data FINs.
1477 */
1478 struct mptcb *mp_tp = tptomptp(tp);
1479 if ((tp->t_mpflags & TMPF_MPTCP_TRUE) &&
1480 (tp->t_state > TCPS_ESTABLISHED)) {
1481 goto dropit;
1482 } else if (mp_tp != NULL) {
1483 if ((mptcp_ok_to_keepalive(mp_tp) == 0)) {
1484 goto dropit;
1485 }
1486 }
1487 #endif /* MPTCP */
1488 if (tp->t_state < TCPS_ESTABLISHED) {
1489 goto dropit;
1490 }
1491 if ((always_keepalive ||
1492 (tp->t_inpcb->inp_socket->so_options & SO_KEEPALIVE) ||
1493 (tp->t_flagsext & TF_DETECT_READSTALL) ||
1494 (tp->t_tfo_probe_state == TFO_PROBE_PROBING)) &&
1495 (tp->t_state <= TCPS_CLOSING || tp->t_state == TCPS_FIN_WAIT_2)) {
1496 if (idle_time >= TCP_CONN_KEEPIDLE(tp) + TCP_CONN_MAXIDLE(tp)) {
1497 TCP_LOG_DROP_PCB(NULL, NULL, tp, false,
1498 "keep alive timeout drop");
1499 goto dropit;
1500 }
1501
1502 if (tcp_send_keep_alive(tp)) {
1503 if (tp->t_flagsext & TF_DETECT_READSTALL) {
1504 tp->t_rtimo_probes++;
1505 }
1506
1507 TCP_LOG_KEEP_ALIVE(tp, idle_time);
1508 }
1509
1510 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
1511 TCP_CONN_KEEPINTVL(tp));
1512 } else {
1513 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
1514 TCP_CONN_KEEPIDLE(tp));
1515 }
1516 if (tp->t_flagsext & TF_DETECT_READSTALL) {
1517 struct ifnet *outifp = tp->t_inpcb->inp_last_outifp;
1518 bool reenable_probe = false;
1519 /*
1520 * The keep alive packets sent to detect a read
1521 * stall did not get a response from the
1522 * peer. Generate more keep-alives to confirm this.
1523 * If the number of probes sent reaches the limit,
1524 * generate an event.
1525 */
1526 if (tp->t_adaptive_rtimo > 0) {
1527 if (tp->t_rtimo_probes > tp->t_adaptive_rtimo) {
1528 /* Generate an event */
1529 soevent(so,
1530 (SO_FILT_HINT_LOCKED |
1531 SO_FILT_HINT_ADAPTIVE_RTIMO));
1532 tcp_keepalive_reset(tp);
1533 } else {
1534 reenable_probe = true;
1535 }
1536 } else if (outifp != NULL &&
1537 (outifp->if_eflags & IFEF_PROBE_CONNECTIVITY) &&
1538 tp->t_rtimo_probes <= TCP_CONNECTIVITY_PROBES_MAX) {
1539 reenable_probe = true;
1540 } else {
1541 tp->t_flagsext &= ~TF_DETECT_READSTALL;
1542 }
1543 if (reenable_probe) {
1544 int ind = min(tp->t_rtimo_probes,
1545 TCP_MAXRXTSHIFT);
1546 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(
1547 tp, tcp_backoff[ind] * TCP_REXMTVAL(tp));
1548 }
1549 }
1550 if (tp->t_tfo_probe_state == TFO_PROBE_PROBING) {
1551 int ind;
1552
1553 tp->t_tfo_probes++;
1554 ind = min(tp->t_tfo_probes, TCP_MAXRXTSHIFT);
1555
1556 /*
1557 * We take the minimum among the time set by true
1558 * keepalive (see above) and the backoff'd RTO. That
1559 * way we backoff in case of packet-loss but will never
1560 * timeout slower than regular keepalive due to the
1561 * backing off.
1562 */
1563 tp->t_timer[TCPT_KEEP] = min(OFFSET_FROM_START(
1564 tp, tcp_backoff[ind] * TCP_REXMTVAL(tp)),
1565 tp->t_timer[TCPT_KEEP]);
1566 } else if (!(tp->t_flagsext & TF_FASTOPEN_FORCE_ENABLE) &&
1567 !(tp->t_tfo_flags & TFO_F_HEURISTIC_DONE) &&
1568 tp->t_tfo_probe_state == TFO_PROBE_WAIT_DATA) {
1569 /* Still no data! Let's assume a TFO-error and err out... */
1570 tcp_heuristic_tfo_middlebox(tp);
1571
1572 so->so_error = ENODATA;
1573 soevent(so,
1574 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_MP_SUB_ERROR));
1575 sorwakeup(so);
1576 tp->t_tfo_stats |= TFO_S_RECV_BLACKHOLE;
1577 tcpstat.tcps_tfo_blackhole++;
1578 }
1579 break;
1580 case TCPT_DELACK:
1581 if (tcp_delack_enabled && (tp->t_flags & TF_DELACK)) {
1582 tp->t_flags &= ~TF_DELACK;
1583 tp->t_timer[TCPT_DELACK] = 0;
1584 tp->t_flags |= TF_ACKNOW;
1585
1586 /*
1587 * If delayed ack timer fired while stretching
1588 * acks, count the number of times the streaming
1589 * detection was not correct. If this exceeds a
1590 * threshold, disable strech ack on this
1591 * connection
1592 *
1593 * Also, go back to acking every other packet.
1594 */
1595 if ((tp->t_flags & TF_STRETCHACK)) {
1596 if (tp->t_unacksegs > 1 &&
1597 tp->t_unacksegs < maxseg_unacked) {
1598 tp->t_stretchack_delayed++;
1599 }
1600
1601 if (tp->t_stretchack_delayed >
1602 TCP_STRETCHACK_DELAY_THRESHOLD) {
1603 tp->t_flagsext |= TF_DISABLE_STRETCHACK;
1604 /*
1605 * Note the time at which stretch
1606 * ack was disabled automatically
1607 */
1608 tp->rcv_nostrack_ts = tcp_now;
1609 tcpstat.tcps_nostretchack++;
1610 tp->t_stretchack_delayed = 0;
1611 tp->rcv_nostrack_pkts = 0;
1612 }
1613 tcp_reset_stretch_ack(tp);
1614 }
1615 tp->t_forced_acks = TCP_FORCED_ACKS_COUNT;
1616
1617 /*
1618 * If we are measuring inter packet arrival jitter
1619 * for throttling a connection, this delayed ack
1620 * might be the reason for accumulating some
1621 * jitter. So let's restart the measurement.
1622 */
1623 CLEAR_IAJ_STATE(tp);
1624
1625 tcpstat.tcps_delack++;
1626 tp->t_stat.delayed_acks_sent++;
1627 (void) tcp_output(tp);
1628 }
1629 break;
1630
1631 #if MPTCP
1632 case TCPT_JACK_RXMT:
1633 if ((tp->t_state == TCPS_ESTABLISHED) &&
1634 (tp->t_mpflags & TMPF_PREESTABLISHED) &&
1635 (tp->t_mpflags & TMPF_JOINED_FLOW)) {
1636 if (++tp->t_mprxtshift > TCP_MAXRXTSHIFT) {
1637 tcpstat.tcps_timeoutdrop++;
1638 soevent(so,
1639 (SO_FILT_HINT_LOCKED |
1640 SO_FILT_HINT_TIMEOUT));
1641 tp = tcp_drop(tp, tp->t_softerror ?
1642 tp->t_softerror : ETIMEDOUT);
1643 break;
1644 }
1645 tcpstat.tcps_join_rxmts++;
1646 tp->t_mpflags |= TMPF_SND_JACK;
1647 tp->t_flags |= TF_ACKNOW;
1648
1649 /*
1650 * No backoff is implemented for simplicity for this
1651 * corner case.
1652 */
1653 (void) tcp_output(tp);
1654 }
1655 break;
1656 case TCPT_CELLICON:
1657 {
1658 struct mptses *mpte = tptomptp(tp)->mpt_mpte;
1659
1660 tp->t_timer[TCPT_CELLICON] = 0;
1661
1662 if (mpte->mpte_cellicon_increments == 0) {
1663 /* Cell-icon not set by this connection */
1664 break;
1665 }
1666
1667 if (TSTMP_LT(mpte->mpte_last_cellicon_set + MPTCP_CELLICON_TOGGLE_RATE, tcp_now)) {
1668 mptcp_unset_cellicon(mpte, NULL, 1);
1669 }
1670
1671 if (mpte->mpte_cellicon_increments) {
1672 tp->t_timer[TCPT_CELLICON] = OFFSET_FROM_START(tp, MPTCP_CELLICON_TOGGLE_RATE);
1673 }
1674
1675 break;
1676 }
1677 #endif /* MPTCP */
1678
1679 case TCPT_PTO:
1680 {
1681 int32_t ret = 0;
1682
1683 if (!(tp->t_flagsext & TF_IF_PROBING)) {
1684 tp->t_flagsext &= ~(TF_SENT_TLPROBE);
1685 }
1686 /*
1687 * Check if the connection is in the right state to
1688 * send a probe
1689 */
1690 if ((tp->t_state != TCPS_ESTABLISHED ||
1691 tp->t_rxtshift > 0 ||
1692 tp->snd_max == tp->snd_una ||
1693 !SACK_ENABLED(tp) || IN_FASTRECOVERY(tp)) &&
1694 !(tp->t_flagsext & TF_IF_PROBING)) {
1695 break;
1696 }
1697
1698 /*
1699 * When the interface state is changed explicitly reset the retransmission
1700 * timer state for both SYN and data packets because we do not want to
1701 * wait unnecessarily or timeout too quickly if the link characteristics
1702 * have changed drastically
1703 */
1704 if (tp->t_flagsext & TF_IF_PROBING) {
1705 tp->t_rxtshift = 0;
1706 if (tp->t_state == TCPS_SYN_SENT) {
1707 tp->t_stat.synrxtshift = tp->t_rxtshift;
1708 }
1709 /*
1710 * Reset to the the default RTO
1711 */
1712 tp->t_srtt = TCPTV_SRTTBASE;
1713 tp->t_rttvar =
1714 ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
1715 tp->t_rttmin = tp->t_flags & TF_LOCAL ? tcp_TCPTV_MIN :
1716 TCPTV_REXMTMIN;
1717 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1718 tp->t_rttmin, TCPTV_REXMTMAX, TCP_ADD_REXMTSLOP(tp));
1719 TCP_LOG_RTT_INFO(tp);
1720 }
1721
1722 if (tp->t_state == TCPS_SYN_SENT) {
1723 /*
1724 * The PTO for SYN_SENT reinitializes TCP as if it was a fresh
1725 * connection attempt
1726 */
1727 tp->snd_nxt = tp->snd_una;
1728 /*
1729 * Note: We overload snd_recover to function also as the
1730 * snd_last variable described in RFC 2582
1731 */
1732 tp->snd_recover = tp->snd_max;
1733 /*
1734 * Force a segment to be sent.
1735 */
1736 tp->t_flags |= TF_ACKNOW;
1737
1738 /* If timing a segment in this window, stop the timer */
1739 tp->t_rtttime = 0;
1740 } else {
1741 int32_t snd_len;
1742
1743 /*
1744 * If there is no new data to send or if the
1745 * connection is limited by receive window then
1746 * retransmit the last segment, otherwise send
1747 * new data.
1748 */
1749 snd_len = min(so->so_snd.sb_cc, tp->snd_wnd)
1750 - (tp->snd_max - tp->snd_una);
1751 if (snd_len > 0) {
1752 tp->snd_nxt = tp->snd_max;
1753 } else {
1754 snd_len = min((tp->snd_max - tp->snd_una),
1755 tp->t_maxseg);
1756 tp->snd_nxt = tp->snd_max - snd_len;
1757 }
1758 }
1759
1760 tcpstat.tcps_pto++;
1761 if (tp->t_flagsext & TF_IF_PROBING) {
1762 tcpstat.tcps_probe_if++;
1763 }
1764
1765 /* If timing a segment in this window, stop the timer */
1766 tp->t_rtttime = 0;
1767 /* Note that tail loss probe is being sent. Exclude IF probe */
1768 if (!(tp->t_flagsext & TF_IF_PROBING)) {
1769 tp->t_flagsext |= TF_SENT_TLPROBE;
1770 tp->t_tlpstart = tcp_now;
1771 }
1772
1773 tp->snd_cwnd += tp->t_maxseg;
1774 /*
1775 * When tail-loss-probe fires, we reset the RTO timer, because
1776 * a probe just got sent, so we are good to push out the timer.
1777 *
1778 * Set to 0 to ensure that tcp_output() will reschedule it
1779 */
1780 tp->t_timer[TCPT_REXMT] = 0;
1781 ret = tcp_output(tp);
1782
1783 #if (DEBUG || DEVELOPMENT)
1784 if ((tp->t_flagsext & TF_IF_PROBING) &&
1785 ((IFNET_IS_COMPANION_LINK(tp->t_inpcb->inp_last_outifp)) ||
1786 tp->t_state == TCPS_SYN_SENT)) {
1787 if (ret == 0 && tcp_probe_if_fix_port > 0 &&
1788 tcp_probe_if_fix_port <= IPPORT_HILASTAUTO) {
1789 tp->t_timer[TCPT_REXMT] = 0;
1790 tcp_set_lotimer_index(tp);
1791 }
1792
1793 os_log(OS_LOG_DEFAULT,
1794 "%s: sent %s probe for %u > %u on interface %s"
1795 " (%u) %s(%d)",
1796 __func__,
1797 tp->t_state == TCPS_SYN_SENT ? "SYN" : "data",
1798 ntohs(tp->t_inpcb->inp_lport),
1799 ntohs(tp->t_inpcb->inp_fport),
1800 if_name(tp->t_inpcb->inp_last_outifp),
1801 tp->t_inpcb->inp_last_outifp->if_index,
1802 ret == 0 ? "succeeded" :"failed", ret);
1803 }
1804 #endif /* DEBUG || DEVELOPMENT */
1805
1806 /*
1807 * When there is data (or a SYN) to send, the above call to
1808 * tcp_output() should have armed either the REXMT or the
1809 * PERSIST timer. If it didn't, something is wrong and this
1810 * connection would idle around forever. Let's make sure that
1811 * at least the REXMT timer is set.
1812 */
1813 if (tp->t_timer[TCPT_REXMT] == 0 && tp->t_timer[TCPT_PERSIST] == 0 &&
1814 (tp->t_inpcb->inp_socket->so_snd.sb_cc != 0 || tp->t_state == TCPS_SYN_SENT ||
1815 tp->t_state == TCPS_SYN_RECEIVED)) {
1816 tp->t_timer[TCPT_REXMT] =
1817 OFFSET_FROM_START(tp, tp->t_rxtcur);
1818
1819 os_log(OS_LOG_DEFAULT,
1820 "%s: tcp_output() returned %u with retransmission timer disabled "
1821 "for %u > %u in state %d, reset timer to %d",
1822 __func__, ret,
1823 ntohs(tp->t_inpcb->inp_lport),
1824 ntohs(tp->t_inpcb->inp_fport),
1825 tp->t_state,
1826 tp->t_timer[TCPT_REXMT]);
1827
1828 tcp_check_timer_state(tp);
1829 }
1830 tp->snd_cwnd -= tp->t_maxseg;
1831
1832 if (!(tp->t_flagsext & TF_IF_PROBING)) {
1833 tp->t_tlphighrxt = tp->snd_nxt;
1834 tp->t_tlphightrxt_persist = tp->snd_nxt;
1835 }
1836 break;
1837 }
1838 case TCPT_DELAYFR:
1839 tp->t_flagsext &= ~TF_DELAY_RECOVERY;
1840
1841 /*
1842 * Don't do anything if one of the following is true:
1843 * - the connection is already in recovery
1844 * - sequence until snd_recover has been acknowledged.
1845 * - retransmit timeout has fired
1846 */
1847 if (IN_FASTRECOVERY(tp) ||
1848 SEQ_GEQ(tp->snd_una, tp->snd_recover) ||
1849 tp->t_rxtshift > 0) {
1850 break;
1851 }
1852
1853 VERIFY(SACK_ENABLED(tp));
1854 tcp_rexmt_save_state(tp);
1855 if (CC_ALGO(tp)->pre_fr != NULL) {
1856 CC_ALGO(tp)->pre_fr(tp);
1857 if (!TCP_ACC_ECN_ON(tp) && TCP_ECN_ENABLED(tp)) {
1858 tp->ecn_flags |= TE_SENDCWR;
1859 }
1860 }
1861 ENTER_FASTRECOVERY(tp);
1862
1863 tp->t_timer[TCPT_REXMT] = 0;
1864 tcpstat.tcps_sack_recovery_episode++;
1865 tp->t_sack_recovery_episode++;
1866 tp->snd_cwnd = tp->t_maxseg;
1867 tcp_ccdbg_trace(tp, NULL, TCP_CC_ENTER_FASTRECOVERY);
1868 (void) tcp_output(tp);
1869 break;
1870
1871 dropit:
1872 tcpstat.tcps_keepdrops++;
1873 soevent(so,
1874 (SO_FILT_HINT_LOCKED | SO_FILT_HINT_TIMEOUT));
1875 tp = tcp_drop(tp, ETIMEDOUT);
1876 break;
1877 case TCPT_REORDER:
1878 if (TCP_RACK_ENABLED(tp)) {
1879 tcp_rack_reordering_timeout(tp, 0);
1880 }
1881 break;
1882 }
1883 return tp;
1884 }
1885
1886 /* Remove a timer entry from timer list */
1887 void
tcp_remove_timer(struct tcpcb * tp)1888 tcp_remove_timer(struct tcpcb *tp)
1889 {
1890 struct tcptimerlist *listp = &tcp_timer_list;
1891
1892 socket_lock_assert_owned(tp->t_inpcb->inp_socket);
1893 if (!(TIMER_IS_ON_LIST(tp))) {
1894 return;
1895 }
1896 lck_mtx_lock(&listp->mtx);
1897
1898 /* Check if pcb is on timer list again after acquiring the lock */
1899 if (!(TIMER_IS_ON_LIST(tp))) {
1900 lck_mtx_unlock(&listp->mtx);
1901 return;
1902 }
1903
1904 if (listp->next_te != NULL && listp->next_te == &tp->tentry) {
1905 listp->next_te = LIST_NEXT(&tp->tentry, le);
1906 }
1907
1908 LIST_REMOVE(&tp->tentry, le);
1909 tp->t_flags &= ~(TF_TIMER_ONLIST);
1910
1911 listp->entries--;
1912
1913 tp->tentry.le.le_next = NULL;
1914 tp->tentry.le.le_prev = NULL;
1915 lck_mtx_unlock(&listp->mtx);
1916 }
1917
1918 /*
1919 * Function to check if the timerlist needs to be rescheduled to run
1920 * the timer entry correctly. Basically, this is to check if we can avoid
1921 * taking the list lock.
1922 */
1923
1924 static boolean_t
need_to_resched_timerlist(u_int32_t runtime,u_int16_t mode)1925 need_to_resched_timerlist(u_int32_t runtime, u_int16_t mode)
1926 {
1927 struct tcptimerlist *listp = &tcp_timer_list;
1928 int32_t diff;
1929
1930 /*
1931 * If the list is being processed then the state of the list is
1932 * in flux. In this case always acquire the lock and set the state
1933 * correctly.
1934 */
1935 if (listp->running) {
1936 return TRUE;
1937 }
1938
1939 if (!listp->scheduled) {
1940 return TRUE;
1941 }
1942
1943 diff = timer_diff(listp->runtime, 0, runtime, 0);
1944 if (diff <= 0) {
1945 /* The list is going to run before this timer */
1946 return FALSE;
1947 } else {
1948 if (mode & TCP_TIMERLIST_10MS_MODE) {
1949 if (diff <= TCP_TIMER_10MS_QUANTUM) {
1950 return FALSE;
1951 }
1952 } else if (mode & TCP_TIMERLIST_100MS_MODE) {
1953 if (diff <= TCP_TIMER_100MS_QUANTUM) {
1954 return FALSE;
1955 }
1956 } else {
1957 if (diff <= TCP_TIMER_500MS_QUANTUM) {
1958 return FALSE;
1959 }
1960 }
1961 }
1962 return TRUE;
1963 }
1964
1965 void
tcp_sched_timerlist(uint32_t offset)1966 tcp_sched_timerlist(uint32_t offset)
1967 {
1968 uint64_t deadline = 0;
1969 struct tcptimerlist *listp = &tcp_timer_list;
1970
1971 LCK_MTX_ASSERT(&listp->mtx, LCK_MTX_ASSERT_OWNED);
1972
1973 offset = min(offset, TCP_TIMERLIST_MAX_OFFSET);
1974 listp->runtime = tcp_now + offset;
1975 listp->schedtime = tcp_now;
1976 if (listp->runtime == 0) {
1977 listp->runtime++;
1978 offset++;
1979 }
1980
1981 clock_interval_to_deadline(offset, USEC_PER_SEC, &deadline);
1982
1983 thread_call_enter_delayed(listp->call, deadline);
1984 listp->scheduled = TRUE;
1985 }
1986
1987 /*
1988 * Function to run the timers for a connection.
1989 *
1990 * Returns the offset of next timer to be run for this connection which
1991 * can be used to reschedule the timerlist.
1992 *
1993 * te_mode is an out parameter that indicates the modes of active
1994 * timers for this connection.
1995 */
1996 u_int32_t
tcp_run_conn_timer(struct tcpcb * tp,u_int16_t * te_mode,u_int16_t probe_if_index)1997 tcp_run_conn_timer(struct tcpcb *tp, u_int16_t *te_mode,
1998 u_int16_t probe_if_index)
1999 {
2000 struct socket *so;
2001 u_int16_t i = 0, index = TCPT_NONE, lo_index = TCPT_NONE;
2002 u_int32_t timer_val, offset = 0, lo_timer = 0;
2003 int32_t diff;
2004 boolean_t needtorun[TCPT_NTIMERS];
2005 int count = 0;
2006
2007 VERIFY(tp != NULL);
2008 bzero(needtorun, sizeof(needtorun));
2009 *te_mode = 0;
2010
2011 socket_lock(tp->t_inpcb->inp_socket, 1);
2012
2013 so = tp->t_inpcb->inp_socket;
2014 /* Release the want count on inp */
2015 if (in_pcb_checkstate(tp->t_inpcb, WNT_RELEASE, 1)
2016 == WNT_STOPUSING) {
2017 if (TIMER_IS_ON_LIST(tp)) {
2018 tcp_remove_timer(tp);
2019 }
2020
2021 /* Looks like the TCP connection got closed while we
2022 * were waiting for the lock.. Done
2023 */
2024 goto done;
2025 }
2026
2027 /*
2028 * If this connection is over an interface that needs to
2029 * be probed, send probe packets to reinitiate communication.
2030 */
2031 if (TCP_IF_STATE_CHANGED(tp, probe_if_index)) {
2032 tp->t_flagsext |= TF_IF_PROBING;
2033 tcp_timers(tp, TCPT_PTO);
2034 tp->t_timer[TCPT_PTO] = 0;
2035 tp->t_flagsext &= ~TF_IF_PROBING;
2036 }
2037
2038 /*
2039 * Since the timer thread needs to wait for tcp lock, it may race
2040 * with another thread that can cancel or reschedule the timer
2041 * that is about to run. Check if we need to run anything.
2042 */
2043 if ((index = tp->tentry.index) == TCPT_NONE) {
2044 goto done;
2045 }
2046
2047 timer_val = tp->t_timer[index];
2048
2049 diff = timer_diff(tp->tentry.runtime, 0, tcp_now, 0);
2050 if (diff > 0) {
2051 if (tp->tentry.index != TCPT_NONE) {
2052 offset = diff;
2053 *(te_mode) = tp->tentry.mode;
2054 }
2055 goto done;
2056 }
2057
2058 tp->t_timer[index] = 0;
2059 if (timer_val > 0) {
2060 tp = tcp_timers(tp, index);
2061 if (tp == NULL) {
2062 goto done;
2063 }
2064 }
2065
2066 /*
2067 * Check if there are any other timers that need to be run.
2068 * While doing it, adjust the timer values wrt tcp_now.
2069 */
2070 tp->tentry.mode = 0;
2071 for (i = 0; i < TCPT_NTIMERS; ++i) {
2072 if (tp->t_timer[i] != 0) {
2073 diff = timer_diff(tp->tentry.timer_start,
2074 tp->t_timer[i], tcp_now, 0);
2075 if (diff <= 0) {
2076 needtorun[i] = TRUE;
2077 count++;
2078 } else {
2079 tp->t_timer[i] = diff;
2080 needtorun[i] = FALSE;
2081 if (lo_timer == 0 || diff < lo_timer) {
2082 lo_timer = diff;
2083 lo_index = i;
2084 }
2085 TCP_SET_TIMER_MODE(tp->tentry.mode, i);
2086 }
2087 }
2088 }
2089
2090 tp->tentry.timer_start = tcp_now;
2091 tp->tentry.index = lo_index;
2092 VERIFY(tp->tentry.index == TCPT_NONE || tp->tentry.mode > 0);
2093
2094 if (tp->tentry.index != TCPT_NONE) {
2095 tp->tentry.runtime = tp->tentry.timer_start +
2096 tp->t_timer[tp->tentry.index];
2097 if (tp->tentry.runtime == 0) {
2098 tp->tentry.runtime++;
2099 }
2100 }
2101
2102 if (count > 0) {
2103 /* run any other timers outstanding at this time. */
2104 for (i = 0; i < TCPT_NTIMERS; ++i) {
2105 if (needtorun[i]) {
2106 tp->t_timer[i] = 0;
2107 tp = tcp_timers(tp, i);
2108 if (tp == NULL) {
2109 offset = 0;
2110 *(te_mode) = 0;
2111 goto done;
2112 }
2113 }
2114 }
2115 tcp_set_lotimer_index(tp);
2116 }
2117
2118 if (tp->tentry.index < TCPT_NONE) {
2119 offset = tp->t_timer[tp->tentry.index];
2120 *(te_mode) = tp->tentry.mode;
2121 }
2122
2123 done:
2124 if (tp != NULL && tp->tentry.index == TCPT_NONE) {
2125 tcp_remove_timer(tp);
2126 offset = 0;
2127 }
2128
2129 socket_unlock(so, 1);
2130 return offset;
2131 }
2132
2133 void
tcp_run_timerlist(void * arg1,void * arg2)2134 tcp_run_timerlist(void * arg1, void * arg2)
2135 {
2136 #pragma unused(arg1, arg2)
2137 struct tcptimerentry *te, *__single next_te;
2138 struct tcptimerlist *__single listp = &tcp_timer_list;
2139 struct tcpcb *__single tp;
2140 uint32_t next_timer = 0; /* offset of the next timer on the list */
2141 u_int16_t te_mode = 0; /* modes of all active timers in a tcpcb */
2142 u_int16_t list_mode = 0; /* cumulative of modes of all tcpcbs */
2143 uint32_t active_count = 0;
2144
2145 calculate_tcp_clock();
2146
2147 lck_mtx_lock(&listp->mtx);
2148
2149 int32_t drift = tcp_now - listp->runtime;
2150 if (drift <= 1) {
2151 tcpstat.tcps_timer_drift_le_1_ms++;
2152 } else if (drift <= 10) {
2153 tcpstat.tcps_timer_drift_le_10_ms++;
2154 } else if (drift <= 20) {
2155 tcpstat.tcps_timer_drift_le_20_ms++;
2156 } else if (drift <= 50) {
2157 tcpstat.tcps_timer_drift_le_50_ms++;
2158 } else if (drift <= 100) {
2159 tcpstat.tcps_timer_drift_le_100_ms++;
2160 } else if (drift <= 200) {
2161 tcpstat.tcps_timer_drift_le_200_ms++;
2162 } else if (drift <= 500) {
2163 tcpstat.tcps_timer_drift_le_500_ms++;
2164 } else if (drift <= 1000) {
2165 tcpstat.tcps_timer_drift_le_1000_ms++;
2166 } else {
2167 tcpstat.tcps_timer_drift_gt_1000_ms++;
2168 }
2169
2170 listp->running = TRUE;
2171
2172 LIST_FOREACH_SAFE(te, &listp->lhead, le, next_te) {
2173 uint32_t offset = 0;
2174 uint32_t runtime = te->runtime;
2175
2176 tp = TIMERENTRY_TO_TP(te);
2177
2178 /*
2179 * An interface probe may need to happen before the previously scheduled runtime
2180 */
2181 if (te->index < TCPT_NONE && TSTMP_GT(runtime, tcp_now) &&
2182 !TCP_IF_STATE_CHANGED(tp, listp->probe_if_index)) {
2183 offset = timer_diff(runtime, 0, tcp_now, 0);
2184 if (next_timer == 0 || offset < next_timer) {
2185 next_timer = offset;
2186 }
2187 list_mode |= te->mode;
2188 continue;
2189 }
2190
2191 /*
2192 * Acquire an inp wantcnt on the inpcb so that the socket
2193 * won't get detached even if tcp_close is called
2194 */
2195 if (in_pcb_checkstate(tp->t_inpcb, WNT_ACQUIRE, 0)
2196 == WNT_STOPUSING) {
2197 /*
2198 * Some how this pcb went into dead state while
2199 * on the timer list, just take it off the list.
2200 * Since the timer list entry pointers are
2201 * protected by the timer list lock, we can
2202 * do it here without the socket lock.
2203 */
2204 if (TIMER_IS_ON_LIST(tp)) {
2205 tp->t_flags &= ~(TF_TIMER_ONLIST);
2206 LIST_REMOVE(&tp->tentry, le);
2207 listp->entries--;
2208
2209 tp->tentry.le.le_next = NULL;
2210 tp->tentry.le.le_prev = NULL;
2211 }
2212 continue;
2213 }
2214 active_count++;
2215
2216 /*
2217 * Store the next timerentry pointer before releasing the
2218 * list lock. If that entry has to be removed when we
2219 * release the lock, this pointer will be updated to the
2220 * element after that.
2221 */
2222 listp->next_te = next_te;
2223
2224 VERIFY_NEXT_LINK(&tp->tentry, le);
2225 VERIFY_PREV_LINK(&tp->tentry, le);
2226
2227 lck_mtx_unlock(&listp->mtx);
2228
2229 offset = tcp_run_conn_timer(tp, &te_mode,
2230 listp->probe_if_index);
2231
2232 lck_mtx_lock(&listp->mtx);
2233
2234 next_te = listp->next_te;
2235 listp->next_te = NULL;
2236
2237 if (offset > 0 && te_mode != 0) {
2238 list_mode |= te_mode;
2239
2240 if (next_timer == 0 || offset < next_timer) {
2241 next_timer = offset;
2242 }
2243 }
2244 }
2245
2246 if (!LIST_EMPTY(&listp->lhead)) {
2247 uint32_t next_mode = 0;
2248 if ((list_mode & TCP_TIMERLIST_10MS_MODE) ||
2249 (listp->pref_mode & TCP_TIMERLIST_10MS_MODE)) {
2250 next_mode = TCP_TIMERLIST_10MS_MODE;
2251 } else if ((list_mode & TCP_TIMERLIST_100MS_MODE) ||
2252 (listp->pref_mode & TCP_TIMERLIST_100MS_MODE)) {
2253 next_mode = TCP_TIMERLIST_100MS_MODE;
2254 } else {
2255 next_mode = TCP_TIMERLIST_500MS_MODE;
2256 }
2257
2258 if (next_mode != TCP_TIMERLIST_500MS_MODE) {
2259 listp->idleruns = 0;
2260 } else {
2261 /*
2262 * the next required mode is slow mode, but if
2263 * the last one was a faster mode and we did not
2264 * have enough idle runs, repeat the last mode.
2265 *
2266 * We try to keep the timer list in fast mode for
2267 * some idle time in expectation of new data.
2268 */
2269 if (listp->mode != next_mode &&
2270 listp->idleruns < timer_fastmode_idlemax) {
2271 listp->idleruns++;
2272 next_mode = listp->mode;
2273 next_timer = TCP_TIMER_100MS_QUANTUM;
2274 } else {
2275 listp->idleruns = 0;
2276 }
2277 }
2278 listp->mode = next_mode;
2279 if (listp->pref_offset != 0) {
2280 next_timer = min(listp->pref_offset, next_timer);
2281 }
2282
2283 if (listp->mode == TCP_TIMERLIST_500MS_MODE) {
2284 next_timer = max(next_timer,
2285 TCP_TIMER_500MS_QUANTUM);
2286 }
2287
2288 tcp_sched_timerlist(next_timer);
2289 } else {
2290 /*
2291 * No need to reschedule this timer, but always run
2292 * periodically at a much higher granularity.
2293 */
2294 tcp_sched_timerlist(TCP_TIMERLIST_MAX_OFFSET);
2295 }
2296
2297 listp->running = FALSE;
2298 listp->pref_mode = 0;
2299 listp->pref_offset = 0;
2300 listp->probe_if_index = 0;
2301
2302 lck_mtx_unlock(&listp->mtx);
2303 }
2304
2305 /*
2306 * Function to check if the timerlist needs to be rescheduled to run this
2307 * connection's timers correctly.
2308 */
2309 void
tcp_sched_timers(struct tcpcb * tp)2310 tcp_sched_timers(struct tcpcb *tp)
2311 {
2312 struct tcptimerentry *te = &tp->tentry;
2313 u_int16_t index = te->index;
2314 u_int16_t mode = te->mode;
2315 struct tcptimerlist *listp = &tcp_timer_list;
2316 int32_t offset = 0;
2317 boolean_t list_locked = FALSE;
2318
2319 if (tp->t_inpcb->inp_state == INPCB_STATE_DEAD) {
2320 /* Just return without adding the dead pcb to the list */
2321 if (TIMER_IS_ON_LIST(tp)) {
2322 tcp_remove_timer(tp);
2323 }
2324 return;
2325 }
2326
2327 if (index == TCPT_NONE) {
2328 /* Nothing to run */
2329 tcp_remove_timer(tp);
2330 return;
2331 }
2332
2333 /*
2334 * compute the offset at which the next timer for this connection
2335 * has to run.
2336 */
2337 offset = timer_diff(te->runtime, 0, tcp_now, 0);
2338 if (offset <= 0) {
2339 offset = 1;
2340 tcp_timer_advanced++;
2341 }
2342
2343 if (!TIMER_IS_ON_LIST(tp)) {
2344 if (!list_locked) {
2345 lck_mtx_lock(&listp->mtx);
2346 list_locked = TRUE;
2347 }
2348
2349 if (!TIMER_IS_ON_LIST(tp)) {
2350 LIST_INSERT_HEAD(&listp->lhead, te, le);
2351 tp->t_flags |= TF_TIMER_ONLIST;
2352
2353 listp->entries++;
2354 if (listp->entries > listp->maxentries) {
2355 listp->maxentries = listp->entries;
2356 }
2357
2358 /* if the list is not scheduled, just schedule it */
2359 if (!listp->scheduled) {
2360 goto schedule;
2361 }
2362 }
2363 }
2364
2365 /*
2366 * Timer entry is currently on the list, check if the list needs
2367 * to be rescheduled.
2368 */
2369 if (need_to_resched_timerlist(te->runtime, mode)) {
2370 tcp_resched_timerlist++;
2371
2372 if (!list_locked) {
2373 lck_mtx_lock(&listp->mtx);
2374 list_locked = TRUE;
2375 }
2376
2377 VERIFY_NEXT_LINK(te, le);
2378 VERIFY_PREV_LINK(te, le);
2379
2380 if (listp->running) {
2381 listp->pref_mode |= mode;
2382 if (listp->pref_offset == 0 ||
2383 offset < listp->pref_offset) {
2384 listp->pref_offset = offset;
2385 }
2386 } else {
2387 /*
2388 * The list could have got rescheduled while
2389 * this thread was waiting for the lock
2390 */
2391 if (listp->scheduled) {
2392 int32_t diff;
2393 diff = timer_diff(listp->runtime, 0,
2394 tcp_now, offset);
2395 if (diff <= 0) {
2396 goto done;
2397 } else {
2398 goto schedule;
2399 }
2400 } else {
2401 goto schedule;
2402 }
2403 }
2404 }
2405 goto done;
2406
2407 schedule:
2408 /*
2409 * Since a connection with timers is getting scheduled, the timer
2410 * list moves from idle to active state and that is why idlegen is
2411 * reset
2412 */
2413 if (mode & TCP_TIMERLIST_10MS_MODE) {
2414 listp->mode = TCP_TIMERLIST_10MS_MODE;
2415 listp->idleruns = 0;
2416 offset = min(offset, TCP_TIMER_10MS_QUANTUM);
2417 } else if (mode & TCP_TIMERLIST_100MS_MODE) {
2418 if (listp->mode > TCP_TIMERLIST_100MS_MODE) {
2419 listp->mode = TCP_TIMERLIST_100MS_MODE;
2420 }
2421 listp->idleruns = 0;
2422 offset = min(offset, TCP_TIMER_100MS_QUANTUM);
2423 }
2424 tcp_sched_timerlist(offset);
2425
2426 done:
2427 if (list_locked) {
2428 lck_mtx_unlock(&listp->mtx);
2429 }
2430
2431 return;
2432 }
2433
2434 static inline void
tcp_set_lotimer_index(struct tcpcb * tp)2435 tcp_set_lotimer_index(struct tcpcb *tp)
2436 {
2437 uint16_t i, lo_index = TCPT_NONE, mode = 0;
2438 uint32_t lo_timer = 0;
2439 for (i = 0; i < TCPT_NTIMERS; ++i) {
2440 if (tp->t_timer[i] != 0) {
2441 TCP_SET_TIMER_MODE(mode, i);
2442 if (lo_timer == 0 || tp->t_timer[i] < lo_timer) {
2443 lo_timer = tp->t_timer[i];
2444 lo_index = i;
2445 }
2446 }
2447 }
2448 tp->tentry.index = lo_index;
2449 tp->tentry.mode = mode;
2450 VERIFY(tp->tentry.index == TCPT_NONE || tp->tentry.mode > 0);
2451
2452 if (tp->tentry.index != TCPT_NONE) {
2453 tp->tentry.runtime = tp->tentry.timer_start
2454 + tp->t_timer[tp->tentry.index];
2455 if (tp->tentry.runtime == 0) {
2456 tp->tentry.runtime++;
2457 }
2458 }
2459 }
2460
2461 void
tcp_check_timer_state(struct tcpcb * tp)2462 tcp_check_timer_state(struct tcpcb *tp)
2463 {
2464 socket_lock_assert_owned(tp->t_inpcb->inp_socket);
2465
2466 if (tp->t_inpcb->inp_flags2 & INP2_TIMEWAIT) {
2467 return;
2468 }
2469
2470 tcp_set_lotimer_index(tp);
2471
2472 tcp_sched_timers(tp);
2473 return;
2474 }
2475
2476 static inline void
tcp_cumulative_stat(u_int32_t cur,u_int32_t * prev,u_int32_t * dest)2477 tcp_cumulative_stat(u_int32_t cur, u_int32_t *prev, u_int32_t *dest)
2478 {
2479 /* handle wrap around */
2480 int32_t diff = (int32_t) (cur - *prev);
2481 if (diff > 0) {
2482 *dest = diff;
2483 } else {
2484 *dest = 0;
2485 }
2486 *prev = cur;
2487 return;
2488 }
2489
2490 static inline void
tcp_cumulative_stat64(u_int64_t cur,u_int64_t * prev,u_int64_t * dest)2491 tcp_cumulative_stat64(u_int64_t cur, u_int64_t *prev, u_int64_t *dest)
2492 {
2493 /* handle wrap around */
2494 int64_t diff = (int64_t) (cur - *prev);
2495 if (diff > 0) {
2496 *dest = diff;
2497 } else {
2498 *dest = 0;
2499 }
2500 *prev = cur;
2501 return;
2502 }
2503
2504 __private_extern__ void
tcp_report_stats(void)2505 tcp_report_stats(void)
2506 {
2507 struct nstat_sysinfo_data data;
2508 struct sockaddr_in dst;
2509 struct sockaddr_in6 dst6;
2510 struct rtentry *rt = NULL;
2511 static struct tcp_last_report_stats prev;
2512 u_int64_t var, uptime;
2513
2514 #define stat data.u.tcp_stats
2515 if (((uptime = net_uptime()) - tcp_last_report_time) <
2516 tcp_report_stats_interval) {
2517 return;
2518 }
2519
2520 tcp_last_report_time = uptime;
2521
2522 bzero(&data, sizeof(data));
2523 data.flags = NSTAT_SYSINFO_TCP_STATS;
2524
2525 SOCKADDR_ZERO(&dst, sizeof(dst));
2526 dst.sin_len = sizeof(dst);
2527 dst.sin_family = AF_INET;
2528
2529 /* ipv4 avg rtt */
2530 lck_mtx_lock(rnh_lock);
2531 rt = rt_lookup(TRUE, SA(&dst), NULL,
2532 rt_tables[AF_INET], IFSCOPE_NONE);
2533 lck_mtx_unlock(rnh_lock);
2534 if (rt != NULL) {
2535 RT_LOCK(rt);
2536 if (rt_primary_default(rt, rt_key(rt)) &&
2537 rt->rt_stats != NULL) {
2538 stat.ipv4_avgrtt = rt->rt_stats->nstat_avg_rtt;
2539 }
2540 RT_UNLOCK(rt);
2541 rtfree(rt);
2542 rt = NULL;
2543 }
2544
2545 /* ipv6 avg rtt */
2546 SOCKADDR_ZERO(&dst6, sizeof(dst6));
2547 dst6.sin6_len = sizeof(dst6);
2548 dst6.sin6_family = AF_INET6;
2549
2550 lck_mtx_lock(rnh_lock);
2551 rt = rt_lookup(TRUE, SA(&dst6), NULL,
2552 rt_tables[AF_INET6], IFSCOPE_NONE);
2553 lck_mtx_unlock(rnh_lock);
2554 if (rt != NULL) {
2555 RT_LOCK(rt);
2556 if (rt_primary_default(rt, rt_key(rt)) &&
2557 rt->rt_stats != NULL) {
2558 stat.ipv6_avgrtt = rt->rt_stats->nstat_avg_rtt;
2559 }
2560 RT_UNLOCK(rt);
2561 rtfree(rt);
2562 rt = NULL;
2563 }
2564
2565 /* send packet loss rate, shift by 10 for precision */
2566 if (tcpstat.tcps_sndpack > 0 && tcpstat.tcps_sndrexmitpack > 0) {
2567 var = tcpstat.tcps_sndrexmitpack << 10;
2568 stat.send_plr = (uint32_t)((var * 100) / tcpstat.tcps_sndpack);
2569 }
2570
2571 /* recv packet loss rate, shift by 10 for precision */
2572 if (tcpstat.tcps_rcvpack > 0 && tcpstat.tcps_recovered_pkts > 0) {
2573 var = tcpstat.tcps_recovered_pkts << 10;
2574 stat.recv_plr = (uint32_t)((var * 100) / tcpstat.tcps_rcvpack);
2575 }
2576
2577 /* RTO after tail loss, shift by 10 for precision */
2578 if (tcpstat.tcps_sndrexmitpack > 0
2579 && tcpstat.tcps_tailloss_rto > 0) {
2580 var = tcpstat.tcps_tailloss_rto << 10;
2581 stat.send_tlrto_rate =
2582 (uint32_t)((var * 100) / tcpstat.tcps_sndrexmitpack);
2583 }
2584
2585 /* packet reordering */
2586 if (tcpstat.tcps_sndpack > 0 && tcpstat.tcps_reordered_pkts > 0) {
2587 var = tcpstat.tcps_reordered_pkts << 10;
2588 stat.send_reorder_rate =
2589 (uint32_t)((var * 100) / tcpstat.tcps_sndpack);
2590 }
2591
2592 if (tcp_ecn_outbound == 1) {
2593 stat.ecn_client_enabled = 1;
2594 }
2595 if (tcp_ecn_inbound == 1) {
2596 stat.ecn_server_enabled = 1;
2597 }
2598 tcp_cumulative_stat(tcpstat.tcps_connattempt,
2599 &prev.tcps_connattempt, &stat.connection_attempts);
2600 tcp_cumulative_stat(tcpstat.tcps_accepts,
2601 &prev.tcps_accepts, &stat.connection_accepts);
2602 tcp_cumulative_stat(tcpstat.tcps_ecn_client_setup,
2603 &prev.tcps_ecn_client_setup, &stat.ecn_client_setup);
2604 tcp_cumulative_stat(tcpstat.tcps_ecn_server_setup,
2605 &prev.tcps_ecn_server_setup, &stat.ecn_server_setup);
2606 tcp_cumulative_stat(tcpstat.tcps_ecn_client_success,
2607 &prev.tcps_ecn_client_success, &stat.ecn_client_success);
2608 tcp_cumulative_stat(tcpstat.tcps_ecn_server_success,
2609 &prev.tcps_ecn_server_success, &stat.ecn_server_success);
2610 tcp_cumulative_stat(tcpstat.tcps_ecn_not_supported,
2611 &prev.tcps_ecn_not_supported, &stat.ecn_not_supported);
2612 tcp_cumulative_stat(tcpstat.tcps_ecn_lost_syn,
2613 &prev.tcps_ecn_lost_syn, &stat.ecn_lost_syn);
2614 tcp_cumulative_stat(tcpstat.tcps_ecn_lost_synack,
2615 &prev.tcps_ecn_lost_synack, &stat.ecn_lost_synack);
2616 tcp_cumulative_stat(tcpstat.tcps_ecn_recv_ce,
2617 &prev.tcps_ecn_recv_ce, &stat.ecn_recv_ce);
2618 tcp_cumulative_stat(tcpstat.tcps_ecn_recv_ece,
2619 &prev.tcps_ecn_recv_ece, &stat.ecn_recv_ece);
2620 tcp_cumulative_stat(tcpstat.tcps_ecn_recv_ece,
2621 &prev.tcps_ecn_recv_ece, &stat.ecn_recv_ece);
2622 tcp_cumulative_stat(tcpstat.tcps_ecn_sent_ece,
2623 &prev.tcps_ecn_sent_ece, &stat.ecn_sent_ece);
2624 tcp_cumulative_stat(tcpstat.tcps_ecn_sent_ece,
2625 &prev.tcps_ecn_sent_ece, &stat.ecn_sent_ece);
2626 tcp_cumulative_stat(tcpstat.tcps_ecn_conn_recv_ce,
2627 &prev.tcps_ecn_conn_recv_ce, &stat.ecn_conn_recv_ce);
2628 tcp_cumulative_stat(tcpstat.tcps_ecn_conn_recv_ece,
2629 &prev.tcps_ecn_conn_recv_ece, &stat.ecn_conn_recv_ece);
2630 tcp_cumulative_stat(tcpstat.tcps_ecn_conn_plnoce,
2631 &prev.tcps_ecn_conn_plnoce, &stat.ecn_conn_plnoce);
2632 tcp_cumulative_stat(tcpstat.tcps_ecn_conn_pl_ce,
2633 &prev.tcps_ecn_conn_pl_ce, &stat.ecn_conn_pl_ce);
2634 tcp_cumulative_stat(tcpstat.tcps_ecn_conn_nopl_ce,
2635 &prev.tcps_ecn_conn_nopl_ce, &stat.ecn_conn_nopl_ce);
2636 tcp_cumulative_stat(tcpstat.tcps_ecn_fallback_synloss,
2637 &prev.tcps_ecn_fallback_synloss, &stat.ecn_fallback_synloss);
2638 tcp_cumulative_stat(tcpstat.tcps_ecn_fallback_reorder,
2639 &prev.tcps_ecn_fallback_reorder, &stat.ecn_fallback_reorder);
2640 tcp_cumulative_stat(tcpstat.tcps_ecn_fallback_ce,
2641 &prev.tcps_ecn_fallback_ce, &stat.ecn_fallback_ce);
2642 tcp_cumulative_stat(tcpstat.tcps_tfo_syn_data_rcv,
2643 &prev.tcps_tfo_syn_data_rcv, &stat.tfo_syn_data_rcv);
2644 tcp_cumulative_stat(tcpstat.tcps_tfo_cookie_req_rcv,
2645 &prev.tcps_tfo_cookie_req_rcv, &stat.tfo_cookie_req_rcv);
2646 tcp_cumulative_stat(tcpstat.tcps_tfo_cookie_sent,
2647 &prev.tcps_tfo_cookie_sent, &stat.tfo_cookie_sent);
2648 tcp_cumulative_stat(tcpstat.tcps_tfo_cookie_invalid,
2649 &prev.tcps_tfo_cookie_invalid, &stat.tfo_cookie_invalid);
2650 tcp_cumulative_stat(tcpstat.tcps_tfo_cookie_req,
2651 &prev.tcps_tfo_cookie_req, &stat.tfo_cookie_req);
2652 tcp_cumulative_stat(tcpstat.tcps_tfo_cookie_rcv,
2653 &prev.tcps_tfo_cookie_rcv, &stat.tfo_cookie_rcv);
2654 tcp_cumulative_stat(tcpstat.tcps_tfo_syn_data_sent,
2655 &prev.tcps_tfo_syn_data_sent, &stat.tfo_syn_data_sent);
2656 tcp_cumulative_stat(tcpstat.tcps_tfo_syn_data_acked,
2657 &prev.tcps_tfo_syn_data_acked, &stat.tfo_syn_data_acked);
2658 tcp_cumulative_stat(tcpstat.tcps_tfo_syn_loss,
2659 &prev.tcps_tfo_syn_loss, &stat.tfo_syn_loss);
2660 tcp_cumulative_stat(tcpstat.tcps_tfo_blackhole,
2661 &prev.tcps_tfo_blackhole, &stat.tfo_blackhole);
2662 tcp_cumulative_stat(tcpstat.tcps_tfo_cookie_wrong,
2663 &prev.tcps_tfo_cookie_wrong, &stat.tfo_cookie_wrong);
2664 tcp_cumulative_stat(tcpstat.tcps_tfo_no_cookie_rcv,
2665 &prev.tcps_tfo_no_cookie_rcv, &stat.tfo_no_cookie_rcv);
2666 tcp_cumulative_stat(tcpstat.tcps_tfo_heuristics_disable,
2667 &prev.tcps_tfo_heuristics_disable, &stat.tfo_heuristics_disable);
2668 tcp_cumulative_stat(tcpstat.tcps_tfo_sndblackhole,
2669 &prev.tcps_tfo_sndblackhole, &stat.tfo_sndblackhole);
2670
2671
2672 tcp_cumulative_stat(tcpstat.tcps_mptcp_handover_attempt,
2673 &prev.tcps_mptcp_handover_attempt, &stat.mptcp_handover_attempt);
2674 tcp_cumulative_stat(tcpstat.tcps_mptcp_interactive_attempt,
2675 &prev.tcps_mptcp_interactive_attempt, &stat.mptcp_interactive_attempt);
2676 tcp_cumulative_stat(tcpstat.tcps_mptcp_aggregate_attempt,
2677 &prev.tcps_mptcp_aggregate_attempt, &stat.mptcp_aggregate_attempt);
2678 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_handover_attempt,
2679 &prev.tcps_mptcp_fp_handover_attempt, &stat.mptcp_fp_handover_attempt);
2680 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_interactive_attempt,
2681 &prev.tcps_mptcp_fp_interactive_attempt, &stat.mptcp_fp_interactive_attempt);
2682 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_aggregate_attempt,
2683 &prev.tcps_mptcp_fp_aggregate_attempt, &stat.mptcp_fp_aggregate_attempt);
2684 tcp_cumulative_stat(tcpstat.tcps_mptcp_heuristic_fallback,
2685 &prev.tcps_mptcp_heuristic_fallback, &stat.mptcp_heuristic_fallback);
2686 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_heuristic_fallback,
2687 &prev.tcps_mptcp_fp_heuristic_fallback, &stat.mptcp_fp_heuristic_fallback);
2688 tcp_cumulative_stat(tcpstat.tcps_mptcp_handover_success_wifi,
2689 &prev.tcps_mptcp_handover_success_wifi, &stat.mptcp_handover_success_wifi);
2690 tcp_cumulative_stat(tcpstat.tcps_mptcp_handover_success_cell,
2691 &prev.tcps_mptcp_handover_success_cell, &stat.mptcp_handover_success_cell);
2692 tcp_cumulative_stat(tcpstat.tcps_mptcp_interactive_success,
2693 &prev.tcps_mptcp_interactive_success, &stat.mptcp_interactive_success);
2694 tcp_cumulative_stat(tcpstat.tcps_mptcp_aggregate_success,
2695 &prev.tcps_mptcp_aggregate_success, &stat.mptcp_aggregate_success);
2696 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_handover_success_wifi,
2697 &prev.tcps_mptcp_fp_handover_success_wifi, &stat.mptcp_fp_handover_success_wifi);
2698 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_handover_success_cell,
2699 &prev.tcps_mptcp_fp_handover_success_cell, &stat.mptcp_fp_handover_success_cell);
2700 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_interactive_success,
2701 &prev.tcps_mptcp_fp_interactive_success, &stat.mptcp_fp_interactive_success);
2702 tcp_cumulative_stat(tcpstat.tcps_mptcp_fp_aggregate_success,
2703 &prev.tcps_mptcp_fp_aggregate_success, &stat.mptcp_fp_aggregate_success);
2704 tcp_cumulative_stat(tcpstat.tcps_mptcp_handover_cell_from_wifi,
2705 &prev.tcps_mptcp_handover_cell_from_wifi, &stat.mptcp_handover_cell_from_wifi);
2706 tcp_cumulative_stat(tcpstat.tcps_mptcp_handover_wifi_from_cell,
2707 &prev.tcps_mptcp_handover_wifi_from_cell, &stat.mptcp_handover_wifi_from_cell);
2708 tcp_cumulative_stat(tcpstat.tcps_mptcp_interactive_cell_from_wifi,
2709 &prev.tcps_mptcp_interactive_cell_from_wifi, &stat.mptcp_interactive_cell_from_wifi);
2710 tcp_cumulative_stat64(tcpstat.tcps_mptcp_handover_cell_bytes,
2711 &prev.tcps_mptcp_handover_cell_bytes, &stat.mptcp_handover_cell_bytes);
2712 tcp_cumulative_stat64(tcpstat.tcps_mptcp_interactive_cell_bytes,
2713 &prev.tcps_mptcp_interactive_cell_bytes, &stat.mptcp_interactive_cell_bytes);
2714 tcp_cumulative_stat64(tcpstat.tcps_mptcp_aggregate_cell_bytes,
2715 &prev.tcps_mptcp_aggregate_cell_bytes, &stat.mptcp_aggregate_cell_bytes);
2716 tcp_cumulative_stat64(tcpstat.tcps_mptcp_handover_all_bytes,
2717 &prev.tcps_mptcp_handover_all_bytes, &stat.mptcp_handover_all_bytes);
2718 tcp_cumulative_stat64(tcpstat.tcps_mptcp_interactive_all_bytes,
2719 &prev.tcps_mptcp_interactive_all_bytes, &stat.mptcp_interactive_all_bytes);
2720 tcp_cumulative_stat64(tcpstat.tcps_mptcp_aggregate_all_bytes,
2721 &prev.tcps_mptcp_aggregate_all_bytes, &stat.mptcp_aggregate_all_bytes);
2722 tcp_cumulative_stat(tcpstat.tcps_mptcp_back_to_wifi,
2723 &prev.tcps_mptcp_back_to_wifi, &stat.mptcp_back_to_wifi);
2724 tcp_cumulative_stat(tcpstat.tcps_mptcp_wifi_proxy,
2725 &prev.tcps_mptcp_wifi_proxy, &stat.mptcp_wifi_proxy);
2726 tcp_cumulative_stat(tcpstat.tcps_mptcp_cell_proxy,
2727 &prev.tcps_mptcp_cell_proxy, &stat.mptcp_cell_proxy);
2728 tcp_cumulative_stat(tcpstat.tcps_mptcp_triggered_cell,
2729 &prev.tcps_mptcp_triggered_cell, &stat.mptcp_triggered_cell);
2730
2731 nstat_sysinfo_send_data(&data);
2732
2733 #undef stat
2734 }
2735
2736 void
tcp_interface_send_probe(u_int16_t probe_if_index)2737 tcp_interface_send_probe(u_int16_t probe_if_index)
2738 {
2739 int32_t offset = 0;
2740 struct tcptimerlist *listp = &tcp_timer_list;
2741
2742 /* Make sure TCP clock is up to date */
2743 calculate_tcp_clock();
2744
2745 lck_mtx_lock(&listp->mtx);
2746 if (listp->probe_if_index > 0 && listp->probe_if_index != probe_if_index) {
2747 tcpstat.tcps_probe_if_conflict++;
2748 os_log(OS_LOG_DEFAULT,
2749 "%s: probe_if_index %u conflicts with %u, tcps_probe_if_conflict %u\n",
2750 __func__, probe_if_index, listp->probe_if_index,
2751 tcpstat.tcps_probe_if_conflict);
2752 goto done;
2753 }
2754
2755 listp->probe_if_index = probe_if_index;
2756 if (listp->running) {
2757 os_log(OS_LOG_DEFAULT, "%s: timer list already running for if_index %u\n",
2758 __func__, probe_if_index);
2759 goto done;
2760 }
2761
2762 /*
2763 * Reschedule the timerlist to run within the next 10ms, which is
2764 * the fastest that we can do.
2765 */
2766 offset = TCP_TIMER_10MS_QUANTUM;
2767 if (listp->scheduled) {
2768 int32_t diff;
2769 diff = timer_diff(listp->runtime, 0, tcp_now, offset);
2770 if (diff <= 0) {
2771 /* The timer will fire sooner than what's needed */
2772 os_log(OS_LOG_DEFAULT,
2773 "%s: timer will fire sooner than needed for if_index %u\n",
2774 __func__, probe_if_index);
2775 goto done;
2776 }
2777 }
2778 listp->mode = TCP_TIMERLIST_10MS_MODE;
2779 listp->idleruns = 0;
2780
2781 tcp_sched_timerlist(offset);
2782
2783 done:
2784 lck_mtx_unlock(&listp->mtx);
2785 return;
2786 }
2787
2788 /*
2789 * Enable read probes on this connection, if:
2790 * - it is in established state
2791 * - doesn't have any data outstanding
2792 * - the outgoing ifp matches
2793 * - we have not already sent any read probes
2794 */
2795 static void
tcp_enable_read_probe(struct tcpcb * tp,struct ifnet * ifp)2796 tcp_enable_read_probe(struct tcpcb *tp, struct ifnet *ifp)
2797 {
2798 if (tp->t_state == TCPS_ESTABLISHED &&
2799 tp->snd_max == tp->snd_una &&
2800 tp->t_inpcb->inp_last_outifp == ifp &&
2801 !(tp->t_flagsext & TF_DETECT_READSTALL) &&
2802 tp->t_rtimo_probes == 0) {
2803 tp->t_flagsext |= TF_DETECT_READSTALL;
2804 tp->t_rtimo_probes = 0;
2805 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
2806 TCP_TIMER_10MS_QUANTUM);
2807 if (tp->tentry.index == TCPT_NONE) {
2808 tp->tentry.index = TCPT_KEEP;
2809 tp->tentry.runtime = tcp_now +
2810 TCP_TIMER_10MS_QUANTUM;
2811 } else {
2812 int32_t diff = 0;
2813
2814 /* Reset runtime to be in next 10ms */
2815 diff = timer_diff(tp->tentry.runtime, 0,
2816 tcp_now, TCP_TIMER_10MS_QUANTUM);
2817 if (diff > 0) {
2818 tp->tentry.index = TCPT_KEEP;
2819 tp->tentry.runtime = tcp_now +
2820 TCP_TIMER_10MS_QUANTUM;
2821 if (tp->tentry.runtime == 0) {
2822 tp->tentry.runtime++;
2823 }
2824 }
2825 }
2826 }
2827 }
2828
2829 /*
2830 * Disable read probe and reset the keep alive timer
2831 */
2832 static void
tcp_disable_read_probe(struct tcpcb * tp)2833 tcp_disable_read_probe(struct tcpcb *tp)
2834 {
2835 if (tp->t_adaptive_rtimo == 0 &&
2836 ((tp->t_flagsext & TF_DETECT_READSTALL) ||
2837 tp->t_rtimo_probes > 0)) {
2838 tcp_keepalive_reset(tp);
2839
2840 if (tp->t_mpsub) {
2841 mptcp_reset_keepalive(tp);
2842 }
2843 }
2844 }
2845
2846 /*
2847 * Reschedule the tcp timerlist in the next 10ms to re-enable read/write
2848 * probes on connections going over a particular interface.
2849 */
2850 void
tcp_probe_connectivity(struct ifnet * ifp,u_int32_t enable)2851 tcp_probe_connectivity(struct ifnet *ifp, u_int32_t enable)
2852 {
2853 int32_t offset;
2854 struct tcptimerlist *listp = &tcp_timer_list;
2855 struct inpcbinfo *pcbinfo = &tcbinfo;
2856 struct inpcb *inp, *nxt;
2857
2858 if (ifp == NULL) {
2859 return;
2860 }
2861
2862 /* update clock */
2863 calculate_tcp_clock();
2864
2865 /*
2866 * Enable keep alive timer on all connections that are
2867 * active/established on this interface.
2868 */
2869 lck_rw_lock_shared(&pcbinfo->ipi_lock);
2870
2871 LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, nxt) {
2872 struct tcpcb *tp = NULL;
2873 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) ==
2874 WNT_STOPUSING) {
2875 continue;
2876 }
2877
2878 /* Acquire lock to look at the state of the connection */
2879 socket_lock(inp->inp_socket, 1);
2880
2881 /* Release the want count */
2882 if (inp->inp_ppcb == NULL ||
2883 (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING)) {
2884 socket_unlock(inp->inp_socket, 1);
2885 continue;
2886 }
2887 tp = intotcpcb(inp);
2888 if (enable) {
2889 tcp_enable_read_probe(tp, ifp);
2890 } else {
2891 tcp_disable_read_probe(tp);
2892 }
2893
2894 socket_unlock(inp->inp_socket, 1);
2895 }
2896 lck_rw_done(&pcbinfo->ipi_lock);
2897
2898 lck_mtx_lock(&listp->mtx);
2899 if (listp->running) {
2900 listp->pref_mode |= TCP_TIMERLIST_10MS_MODE;
2901 goto done;
2902 }
2903
2904 /* Reschedule within the next 10ms */
2905 offset = TCP_TIMER_10MS_QUANTUM;
2906 if (listp->scheduled) {
2907 int32_t diff;
2908 diff = timer_diff(listp->runtime, 0, tcp_now, offset);
2909 if (diff <= 0) {
2910 /* The timer will fire sooner than what's needed */
2911 goto done;
2912 }
2913 }
2914 listp->mode = TCP_TIMERLIST_10MS_MODE;
2915 listp->idleruns = 0;
2916
2917 tcp_sched_timerlist(offset);
2918 done:
2919 lck_mtx_unlock(&listp->mtx);
2920 return;
2921 }
2922
2923 inline void
tcp_update_mss_core(struct tcpcb * tp,struct ifnet * ifp)2924 tcp_update_mss_core(struct tcpcb *tp, struct ifnet *ifp)
2925 {
2926 struct if_cellular_status_v1 *ifsr;
2927 u_int32_t optlen;
2928 ifsr = &ifp->if_link_status->ifsr_u.ifsr_cell.if_cell_u.if_status_v1;
2929 if (ifsr->valid_bitmask & IF_CELL_UL_MSS_RECOMMENDED_VALID) {
2930 optlen = tp->t_maxopd - tp->t_maxseg;
2931
2932 if (ifsr->mss_recommended ==
2933 IF_CELL_UL_MSS_RECOMMENDED_NONE &&
2934 tp->t_cached_maxopd > 0 &&
2935 tp->t_maxopd < tp->t_cached_maxopd) {
2936 tp->t_maxopd = tp->t_cached_maxopd;
2937 tcpstat.tcps_mss_to_default++;
2938 } else if (ifsr->mss_recommended ==
2939 IF_CELL_UL_MSS_RECOMMENDED_MEDIUM &&
2940 tp->t_maxopd > tcp_mss_rec_medium) {
2941 tp->t_cached_maxopd = tp->t_maxopd;
2942 tp->t_maxopd = tcp_mss_rec_medium;
2943 tcpstat.tcps_mss_to_medium++;
2944 } else if (ifsr->mss_recommended ==
2945 IF_CELL_UL_MSS_RECOMMENDED_LOW &&
2946 tp->t_maxopd > tcp_mss_rec_low) {
2947 tp->t_cached_maxopd = tp->t_maxopd;
2948 tp->t_maxopd = tcp_mss_rec_low;
2949 tcpstat.tcps_mss_to_low++;
2950 }
2951 tp->t_maxseg = tp->t_maxopd - optlen;
2952
2953 /*
2954 * clear the cached value if it is same as the current
2955 */
2956 if (tp->t_maxopd == tp->t_cached_maxopd) {
2957 tp->t_cached_maxopd = 0;
2958 }
2959 }
2960 }
2961
2962 void
tcp_update_mss_locked(struct socket * so,struct ifnet * ifp)2963 tcp_update_mss_locked(struct socket *so, struct ifnet *ifp)
2964 {
2965 struct inpcb *inp = sotoinpcb(so);
2966 struct tcpcb *tp = intotcpcb(inp);
2967
2968 if (ifp == NULL && (ifp = inp->inp_last_outifp) == NULL) {
2969 return;
2970 }
2971
2972 if (!IFNET_IS_CELLULAR(ifp)) {
2973 /*
2974 * This optimization is implemented for cellular
2975 * networks only
2976 */
2977 return;
2978 }
2979 if (tp->t_state <= TCPS_CLOSE_WAIT) {
2980 /*
2981 * If the connection is currently doing or has done PMTU
2982 * blackhole detection, do not change the MSS
2983 */
2984 if (tp->t_flags & TF_BLACKHOLE) {
2985 return;
2986 }
2987 if (ifp->if_link_status == NULL) {
2988 return;
2989 }
2990 tcp_update_mss_core(tp, ifp);
2991 }
2992 }
2993
2994 void
tcp_itimer(struct inpcbinfo * ipi)2995 tcp_itimer(struct inpcbinfo *ipi)
2996 {
2997 struct inpcb *inp, *nxt;
2998
2999 if (lck_rw_try_lock_exclusive(&ipi->ipi_lock) == FALSE) {
3000 if (tcp_itimer_done == TRUE) {
3001 tcp_itimer_done = FALSE;
3002 os_atomic_inc(&ipi->ipi_timer_req.intimer_fast, relaxed);
3003 return;
3004 }
3005 /* Upgrade failed, lost lock now take it again exclusive */
3006 lck_rw_lock_exclusive(&ipi->ipi_lock);
3007 }
3008 tcp_itimer_done = TRUE;
3009
3010 LIST_FOREACH_SAFE(inp, &tcb, inp_list, nxt) {
3011 struct socket *so;
3012 struct ifnet *ifp;
3013
3014 if (inp->inp_ppcb == NULL ||
3015 in_pcb_checkstate(inp, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
3016 continue;
3017 }
3018 so = inp->inp_socket;
3019 ifp = inp->inp_last_outifp;
3020 socket_lock(so, 1);
3021 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
3022 socket_unlock(so, 1);
3023 continue;
3024 }
3025 so_check_extended_bk_idle_time(so);
3026 if (ipi->ipi_flags & INPCBINFO_UPDATE_MSS) {
3027 tcp_update_mss_locked(so, NULL);
3028 }
3029 socket_unlock(so, 1);
3030
3031 /*
3032 * Defunct all system-initiated background sockets if the
3033 * socket is using the cellular interface and the interface
3034 * has its LQM set to abort.
3035 */
3036 if ((ipi->ipi_flags & INPCBINFO_HANDLE_LQM_ABORT) &&
3037 IS_SO_TC_BACKGROUNDSYSTEM(so->so_traffic_class) &&
3038 ifp != NULL && IFNET_IS_CELLULAR(ifp) &&
3039 (ifp->if_interface_state.valid_bitmask &
3040 IF_INTERFACE_STATE_LQM_STATE_VALID) &&
3041 ifp->if_interface_state.lqm_state ==
3042 IFNET_LQM_THRESH_ABORT) {
3043 socket_defunct(current_proc(), so,
3044 SHUTDOWN_SOCKET_LEVEL_DISCONNECT_ALL);
3045 }
3046 }
3047
3048 ipi->ipi_flags &= ~(INPCBINFO_UPDATE_MSS | INPCBINFO_HANDLE_LQM_ABORT);
3049 lck_rw_done(&ipi->ipi_lock);
3050 }
3051