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