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