]> git.saurik.com Git - apple/xnu.git/blame - bsd/netinet/tcp_timer.c
xnu-2422.100.13.tar.gz
[apple/xnu.git] / bsd / netinet / tcp_timer.c
CommitLineData
1c79356b 1/*
39236c6e 2 * Copyright (c) 2000-2013 Apple Inc. All rights reserved.
5d5c5d0d 3 *
2d21ac55 4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
1c79356b 5 *
2d21ac55
A
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.
8f6c56a5 14 *
2d21ac55
A
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
8f6c56a5
A
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
2d21ac55
A
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.
8f6c56a5 25 *
2d21ac55 26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
1c79356b
A
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
9bccf70c 61 * $FreeBSD: src/sys/netinet/tcp_timer.c,v 1.34.2.11 2001/08/22 00:59:12 silby Exp $
1c79356b
A
62 */
63
1c79356b
A
64
65#include <sys/param.h>
66#include <sys/systm.h>
67#include <sys/kernel.h>
9bccf70c 68#include <sys/mbuf.h>
1c79356b
A
69#include <sys/sysctl.h>
70#include <sys/socket.h>
71#include <sys/socketvar.h>
72#include <sys/protosw.h>
b0d623f7 73#include <sys/domain.h>
6d2010ae
A
74#include <sys/mcache.h>
75#include <sys/queue.h>
91447636 76#include <kern/locks.h>
1c79356b 77#include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
39236c6e 78#include <mach/boolean.h>
1c79356b
A
79
80#include <net/route.h>
316670eb 81#include <net/if_var.h>
1c79356b
A
82
83#include <netinet/in.h>
84#include <netinet/in_systm.h>
1c79356b 85#include <netinet/in_pcb.h>
9bccf70c
A
86#if INET6
87#include <netinet6/in6_pcb.h>
88#endif
1c79356b
A
89#include <netinet/ip_var.h>
90#include <netinet/tcp.h>
91#include <netinet/tcp_fsm.h>
92#include <netinet/tcp_seq.h>
93#include <netinet/tcp_timer.h>
94#include <netinet/tcp_var.h>
6d2010ae 95#include <netinet/tcp_cc.h>
b0d623f7
A
96#if INET6
97#include <netinet6/tcp6_var.h>
98#endif
1c79356b
A
99#include <netinet/tcpip.h>
100#if TCPDEBUG
101#include <netinet/tcp_debug.h>
102#endif
103#include <sys/kdebug.h>
6d2010ae 104#include <mach/sdt.h>
39236c6e 105#include <netinet/mptcp_var.h>
1c79356b 106
2d21ac55
A
107extern void postevent(struct socket *, struct sockbuf *,
108 int);
1c79356b
A
109#define DBG_FNC_TCP_FAST NETDBG_CODE(DBG_NETTCP, (5 << 8))
110#define DBG_FNC_TCP_SLOW NETDBG_CODE(DBG_NETTCP, (5 << 8) | 1)
111
6d2010ae
A
112#define TIMERENTRY_TO_TP(te) ((struct tcpcb *)((uintptr_t)te - offsetof(struct tcpcb, tentry.le.le_next)))
113
114#define VERIFY_NEXT_LINK(elm,field) do { \
115 if (LIST_NEXT((elm),field) != NULL && \
116 LIST_NEXT((elm),field)->field.le_prev != \
117 &((elm)->field.le_next)) \
118 panic("Bad link elm %p next->prev != elm", (elm)); \
119} while(0)
120
121#define VERIFY_PREV_LINK(elm,field) do { \
122 if (*(elm)->field.le_prev != (elm)) \
123 panic("Bad link elm %p prev->next != elm", (elm)); \
124} while(0)
125
39236c6e
A
126/* tcp timer list */
127struct tcptimerlist tcp_timer_list;
128
129/* List of pcbs in timewait state, protected by tcbinfo's ipi_lock */
130struct tcptailq tcp_tw_tailq;
131
2d21ac55 132static int background_io_trigger = 5;
6d2010ae 133SYSCTL_INT(_net_inet_tcp, OID_AUTO, background_io_trigger, CTLFLAG_RW | CTLFLAG_LOCKED,
2d21ac55
A
134 &background_io_trigger, 0, "Background IO Trigger Setting");
135
9bccf70c
A
136static int
137sysctl_msec_to_ticks SYSCTL_HANDLER_ARGS
138{
2d21ac55 139#pragma unused(arg1, arg2)
9bccf70c 140 int error, s, tt;
1c79356b 141
9bccf70c 142 tt = *(int *)oidp->oid_arg1;
2d21ac55 143 s = tt * 1000 / TCP_RETRANSHZ;;
1c79356b 144
9bccf70c
A
145 error = sysctl_handle_int(oidp, &s, 0, req);
146 if (error || !req->newptr)
147 return (error);
148
2d21ac55 149 tt = s * TCP_RETRANSHZ / 1000;
9bccf70c
A
150 if (tt < 1)
151 return (EINVAL);
152
153 *(int *)oidp->oid_arg1 = tt;
154 return (0);
155}
1c79356b 156
9bccf70c 157int tcp_keepinit;
6d2010ae 158SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPINIT, keepinit, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
9bccf70c
A
159 &tcp_keepinit, 0, sysctl_msec_to_ticks, "I", "");
160
161int tcp_keepidle;
6d2010ae 162SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPIDLE, keepidle, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
9bccf70c
A
163 &tcp_keepidle, 0, sysctl_msec_to_ticks, "I", "");
164
165int tcp_keepintvl;
6d2010ae 166SYSCTL_PROC(_net_inet_tcp, TCPCTL_KEEPINTVL, keepintvl, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
9bccf70c
A
167 &tcp_keepintvl, 0, sysctl_msec_to_ticks, "I", "");
168
39236c6e
A
169int tcp_keepcnt;
170SYSCTL_INT(_net_inet_tcp, OID_AUTO, keepcnt, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
171 &tcp_keepcnt, 0, "number of times to repeat keepalive");
172
9bccf70c 173int tcp_msl;
6d2010ae 174SYSCTL_PROC(_net_inet_tcp, OID_AUTO, msl, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
9bccf70c 175 &tcp_msl, 0, sysctl_msec_to_ticks, "I", "Maximum segment lifetime");
1c79356b 176
6d2010ae
A
177/*
178 * Avoid DoS via TCP Robustness in Persist Condition (see http://www.ietf.org/id/draft-ananth-tcpm-persist-02.txt)
179 * by allowing a system wide maximum persistence timeout value when in Zero Window Probe mode.
180 * Expressed in milliseconds to be consistent without timeout related values, the TCP socket option is in seconds.
181 */
182u_int32_t tcp_max_persist_timeout = 0;
183SYSCTL_PROC(_net_inet_tcp, OID_AUTO, max_persist_timeout, CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
184 &tcp_max_persist_timeout, 0, sysctl_msec_to_ticks, "I", "Maximum persistence timout for ZWP");
185
1c79356b 186static int always_keepalive = 0;
6d2010ae 187SYSCTL_INT(_net_inet_tcp, OID_AUTO, always_keepalive, CTLFLAG_RW | CTLFLAG_LOCKED,
9bccf70c 188 &always_keepalive , 0, "Assume SO_KEEPALIVE on all TCP connections");
1c79356b 189
6d2010ae
A
190/* This parameter determines how long the timer list will stay in fast mode even
191 * though all connections are idle. In fast mode, the timer will fire more frequently
192 * anticipating new data.
193 */
194int timer_fastmode_idlemax = TCP_FASTMODE_IDLEGEN_MAX;
195SYSCTL_INT(_net_inet_tcp, OID_AUTO, timer_fastmode_idlemax, CTLFLAG_RW | CTLFLAG_LOCKED,
196 &timer_fastmode_idlemax, 0, "Maximum idle generations in fast mode");
197
b0d623f7
A
198/*
199 * See tcp_syn_backoff[] for interval values between SYN retransmits;
200 * the value set below defines the number of retransmits, before we
201 * disable the timestamp and window scaling options during subsequent
202 * SYN retransmits. Setting it to 0 disables the dropping off of those
203 * two options.
204 */
205static int tcp_broken_peer_syn_rxmit_thres = 7;
6d2010ae 206SYSCTL_INT(_net_inet_tcp, OID_AUTO, broken_peer_syn_rxmit_thres, CTLFLAG_RW | CTLFLAG_LOCKED,
b0d623f7
A
207 &tcp_broken_peer_syn_rxmit_thres, 0, "Number of retransmitted SYNs before "
208 "TCP disables rfc1323 and rfc1644 during the rest of attempts");
209
39236c6e
A
210/* A higher threshold on local connections for disabling RFC 1323 options */
211static int tcp_broken_peer_syn_rxmit_thres_local = 10;
212SYSCTL_INT(_net_inet_tcp, OID_AUTO, broken_peer_syn_rexmit_thres_local,
213 CTLFLAG_RW | CTLFLAG_LOCKED, &tcp_broken_peer_syn_rxmit_thres_local, 0,
214 "Number of retransmitted SYNs before disabling RFC 1323 options on local connections");
215
6d2010ae
A
216static int tcp_timer_advanced = 0;
217SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_timer_advanced, CTLFLAG_RD | CTLFLAG_LOCKED,
218 &tcp_timer_advanced, 0, "Number of times one of the timers was advanced");
219
220static int tcp_resched_timerlist = 0;
221SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_resched_timerlist, CTLFLAG_RD | CTLFLAG_LOCKED,
222 &tcp_resched_timerlist, 0,
223 "Number of times timer list was rescheduled as part of processing a packet");
224
b0d623f7 225int tcp_pmtud_black_hole_detect = 1 ;
6d2010ae 226SYSCTL_INT(_net_inet_tcp, OID_AUTO, pmtud_blackhole_detection, CTLFLAG_RW | CTLFLAG_LOCKED,
b0d623f7
A
227 &tcp_pmtud_black_hole_detect, 0, "Path MTU Discovery Black Hole Detection");
228
229int tcp_pmtud_black_hole_mss = 1200 ;
6d2010ae 230SYSCTL_INT(_net_inet_tcp, OID_AUTO, pmtud_blackhole_mss, CTLFLAG_RW | CTLFLAG_LOCKED,
b0d623f7
A
231 &tcp_pmtud_black_hole_mss, 0, "Path MTU Discovery Black Hole Detection lowered MSS");
232
39236c6e
A
233/* performed garbage collection of "used" sockets */
234static boolean_t tcp_gc_done = FALSE;
235
1c79356b 236 /* max idle probes */
9bccf70c 237int tcp_maxpersistidle;
1c79356b 238
6d2010ae
A
239/* TCP delack timer is set to 100 ms. Since the processing of timer list in fast
240 * mode will happen no faster than 100 ms, the delayed ack timer will fire some where
241 * between 100 and 200 ms.
242 */
243int tcp_delack = TCP_RETRANSHZ / 10;
244
39236c6e
A
245#if MPTCP
246/*
247 * MP_JOIN retransmission of 3rd ACK will be every 500 msecs without backoff
248 */
249int tcp_jack_rxmt = TCP_RETRANSHZ / 2;
250#endif /* MPTCP */
1c79356b 251
6d2010ae
A
252/* The frequency of running through the TCP timer list in
253 * fast and slow mode can be configured.
254 */
255SYSCTL_UINT(_net_inet_tcp, OID_AUTO, timer_fastquantum, CTLFLAG_RW | CTLFLAG_LOCKED,
256 &tcp_timer_list.fast_quantum, TCP_FASTTIMER_QUANTUM,
257 "Frequency of running timer list in fast mode");
258
259SYSCTL_UINT(_net_inet_tcp, OID_AUTO, timer_slowquantum, CTLFLAG_RW | CTLFLAG_LOCKED,
260 &tcp_timer_list.slow_quantum, TCP_SLOWTIMER_QUANTUM,
261 "Frequency of running timer list in slow mode");
262
263static void tcp_remove_timer(struct tcpcb *tp);
264static void tcp_sched_timerlist(uint32_t offset);
265static uint32_t tcp_run_conn_timer(struct tcpcb *tp, uint16_t *next_index);
266static void tcp_sched_timers(struct tcpcb *tp);
267static inline void tcp_set_lotimer_index(struct tcpcb *);
39236c6e
A
268static void tcp_rexmt_save_state(struct tcpcb *tp);
269void tcp_remove_from_time_wait(struct inpcb *inp);
6d2010ae
A
270
271/* Macro to compare two timers. If there is a reset of the sign bit, it is
272 * safe to assume that the timer has wrapped around. By doing signed comparision,
273 * we take care of wrap around such that the value with the sign bit reset is
274 * actually ahead of the other.
275 */
276
277static inline int32_t
278timer_diff(uint32_t t1, uint32_t toff1, uint32_t t2, uint32_t toff2) {
279 return (int32_t)((t1 + toff1) - (t2 + toff2));
280};
281
282/* Returns true if the timer is on the timer list */
283#define TIMER_IS_ON_LIST(tp) ((tp)->t_flags & TF_TIMER_ONLIST)
284
285
39236c6e 286static void add_to_time_wait_locked(struct tcpcb *tp, uint32_t delay);
6d2010ae 287void add_to_time_wait(struct tcpcb *tp, uint32_t delay) ;
2d21ac55 288
39236c6e 289static boolean_t tcp_garbage_collect(struct inpcb *, int);
1c79356b 290
39236c6e
A
291/*
292 * Add to tcp timewait list, delay is given in milliseconds.
293 */
294static void
295add_to_time_wait_locked(struct tcpcb *tp, uint32_t delay)
1c79356b 296{
39236c6e
A
297 struct inpcbinfo *pcbinfo = &tcbinfo;
298 struct inpcb *inp = tp->t_inpcb;
6d2010ae 299 uint32_t timer;
1c79356b 300
39236c6e
A
301 /* pcb list should be locked when we get here */
302 lck_rw_assert(pcbinfo->ipi_lock, LCK_RW_ASSERT_EXCLUSIVE);
1c79356b 303
39236c6e
A
304 /* We may get here multiple times, so check */
305 if (!(inp->inp_flags2 & INP2_TIMEWAIT)) {
306 pcbinfo->ipi_twcount++;
307 inp->inp_flags2 |= INP2_TIMEWAIT;
308
309 /* Remove from global inp list */
310 LIST_REMOVE(inp, inp_list);
311 } else {
312 TAILQ_REMOVE(&tcp_tw_tailq, tp, t_twentry);
313 }
2d21ac55 314
39236c6e
A
315 /* Compute the time at which this socket can be closed */
316 timer = tcp_now + delay;
317
318 /* We will use the TCPT_2MSL timer for tracking this delay */
2d21ac55 319
39236c6e
A
320 if (TIMER_IS_ON_LIST(tp))
321 tcp_remove_timer(tp);
322 tp->t_timer[TCPT_2MSL] = timer;
1c79356b 323
39236c6e 324 TAILQ_INSERT_TAIL(&tcp_tw_tailq, tp, t_twentry);
1c79356b
A
325}
326
39236c6e
A
327void
328add_to_time_wait(struct tcpcb *tp, uint32_t delay)
91447636 329{
39236c6e
A
330 struct inpcbinfo *pcbinfo = &tcbinfo;
331
332 if (!lck_rw_try_lock_exclusive(pcbinfo->ipi_lock)) {
91447636 333 tcp_unlock(tp->t_inpcb->inp_socket, 0, 0);
39236c6e 334 lck_rw_lock_exclusive(pcbinfo->ipi_lock);
91447636
A
335 tcp_lock(tp->t_inpcb->inp_socket, 0, 0);
336 }
6d2010ae 337 add_to_time_wait_locked(tp, delay);
39236c6e
A
338 lck_rw_done(pcbinfo->ipi_lock);
339
340 inpcb_gc_sched(pcbinfo, INPCB_TIMER_LAZY);
91447636 341}
1c79356b 342
39236c6e
A
343/* If this is on time wait queue, remove it. */
344void
345tcp_remove_from_time_wait(struct inpcb *inp)
346{
347 struct tcpcb *tp = intotcpcb(inp);
348 if (inp->inp_flags2 & INP2_TIMEWAIT)
349 TAILQ_REMOVE(&tcp_tw_tailq, tp, t_twentry);
350}
351
352static boolean_t
b0d623f7 353tcp_garbage_collect(struct inpcb *inp, int istimewait)
2d21ac55 354{
39236c6e 355 boolean_t active = FALSE;
2d21ac55
A
356 struct socket *so;
357 struct tcpcb *tp;
358
b0d623f7
A
359 so = inp->inp_socket;
360 tp = intotcpcb(inp);
2d21ac55 361
b0d623f7
A
362 /*
363 * Skip if still in use or busy; it would have been more efficient
364 * if we were to test so_usecount against 0, but this isn't possible
365 * due to the current implementation of tcp_dropdropablreq() where
366 * overflow sockets that are eligible for garbage collection have
367 * their usecounts set to 1.
368 */
39236c6e
A
369 if (!lck_mtx_try_lock_spin(&inp->inpcb_mtx))
370 return (TRUE);
2d21ac55 371
b0d623f7
A
372 /* Check again under the lock */
373 if (so->so_usecount > 1) {
39236c6e
A
374 if (inp->inp_wantcnt == WNT_STOPUSING)
375 active = TRUE;
6d2010ae 376 lck_mtx_unlock(&inp->inpcb_mtx);
39236c6e
A
377 return (active);
378 }
379
380 if (istimewait &&
381 TSTMP_GEQ(tcp_now, tp->t_timer[TCPT_2MSL]) &&
382 tp->t_state != TCPS_CLOSED) {
383 /* Become a regular mutex */
384 lck_mtx_convert_spin(&inp->inpcb_mtx);
385 tcp_close(tp);
b0d623f7 386 }
2d21ac55 387
b0d623f7
A
388 /*
389 * Overflowed socket dropped from the listening queue? Do this
390 * only if we are called to clean up the time wait slots, since
391 * tcp_dropdropablreq() considers a socket to have been fully
392 * dropped after add_to_time_wait() is finished.
39236c6e
A
393 * Also handle the case of connections getting closed by the peer
394 * while in the queue as seen with rdar://6422317
395 *
b0d623f7 396 */
39236c6e 397 if (so->so_usecount == 1 &&
b0d623f7 398 ((istimewait && (so->so_flags & SOF_OVERFLOW)) ||
39236c6e
A
399 ((tp != NULL) && (tp->t_state == TCPS_CLOSED) &&
400 (so->so_head != NULL) &&
401 ((so->so_state & (SS_INCOMP|SS_CANTSENDMORE|SS_CANTRCVMORE)) ==
402 (SS_INCOMP|SS_CANTSENDMORE|SS_CANTRCVMORE))))) {
b0d623f7
A
403
404 if (inp->inp_state != INPCB_STATE_DEAD) {
405 /* Become a regular mutex */
6d2010ae 406 lck_mtx_convert_spin(&inp->inpcb_mtx);
b0d623f7 407#if INET6
39236c6e 408 if (SOCK_CHECK_DOM(so, PF_INET6))
b0d623f7
A
409 in6_pcbdetach(inp);
410 else
411#endif /* INET6 */
39236c6e 412 in_pcbdetach(inp);
2d21ac55 413 }
b0d623f7 414 so->so_usecount--;
39236c6e
A
415 if (inp->inp_wantcnt == WNT_STOPUSING)
416 active = TRUE;
6d2010ae 417 lck_mtx_unlock(&inp->inpcb_mtx);
39236c6e 418 return (active);
b0d623f7 419 } else if (inp->inp_wantcnt != WNT_STOPUSING) {
6d2010ae 420 lck_mtx_unlock(&inp->inpcb_mtx);
39236c6e 421 return (FALSE);
b0d623f7 422 }
2d21ac55 423
b0d623f7 424 /*
39236c6e
A
425 * We get here because the PCB is no longer searchable
426 * (WNT_STOPUSING); detach (if needed) and dispose if it is dead
427 * (usecount is 0). This covers all cases, including overflow
428 * sockets and those that are considered as "embryonic",
429 * i.e. created by sonewconn() in TCP input path, and have
430 * not yet been committed. For the former, we reduce the usecount
431 * to 0 as done by the code above. For the latter, the usecount
432 * would have reduced to 0 as part calling soabort() when the
b0d623f7
A
433 * socket is dropped at the end of tcp_input().
434 */
435 if (so->so_usecount == 0) {
6d2010ae
A
436 DTRACE_TCP4(state__change, void, NULL, struct inpcb *, inp,
437 struct tcpcb *, tp, int32_t, TCPS_CLOSED);
b0d623f7 438 /* Become a regular mutex */
6d2010ae 439 lck_mtx_convert_spin(&inp->inpcb_mtx);
39236c6e
A
440
441 /*
442 * If this tp still happens to be on the timer list,
ebb1b9f4
A
443 * take it out
444 */
445 if (TIMER_IS_ON_LIST(tp)) {
446 tcp_remove_timer(tp);
447 }
448
b0d623f7
A
449 if (inp->inp_state != INPCB_STATE_DEAD) {
450#if INET6
39236c6e 451 if (SOCK_CHECK_DOM(so, PF_INET6))
b0d623f7
A
452 in6_pcbdetach(inp);
453 else
454#endif /* INET6 */
39236c6e 455 in_pcbdetach(inp);
2d21ac55 456 }
b0d623f7 457 in_pcbdispose(inp);
39236c6e 458 return (FALSE);
b0d623f7 459 }
39236c6e
A
460
461 lck_mtx_unlock(&inp->inpcb_mtx);
462 return (TRUE);
2d21ac55
A
463}
464
39236c6e
A
465/*
466 * TCP garbage collector callback (inpcb_timer_func_t).
467 *
468 * Returns the number of pcbs that will need to be gc-ed soon,
469 * returnining > 0 will keep timer active.
470 */
1c79356b 471void
39236c6e 472tcp_gc(struct inpcbinfo *ipi)
1c79356b 473{
4a3eedf9 474 struct inpcb *inp, *nxt;
39236c6e 475 struct tcpcb *tw_tp, *tw_ntp;
1c79356b
A
476#if TCPDEBUG
477 int ostate;
478#endif
b0d623f7 479#if KDEBUG
2d21ac55 480 static int tws_checked = 0;
b0d623f7 481#endif
2d21ac55 482
39236c6e 483 KERNEL_DEBUG(DBG_FNC_TCP_SLOW | DBG_FUNC_START, 0, 0, 0, 0, 0);
1c79356b 484
39236c6e
A
485 /*
486 * Update tcp_now here as it may get used while
487 * processing the slow timer.
488 */
6d2010ae 489 calculate_tcp_clock();
8ad349bb 490
39236c6e
A
491 /*
492 * Garbage collect socket/tcpcb: We need to acquire the list lock
6d2010ae 493 * exclusively to do this
2d21ac55
A
494 */
495
39236c6e
A
496 if (lck_rw_try_lock_exclusive(ipi->ipi_lock) == FALSE) {
497 /* don't sweat it this time; cleanup was done last time */
498 if (tcp_gc_done == TRUE) {
2d21ac55 499 tcp_gc_done = FALSE;
39236c6e
A
500 KERNEL_DEBUG(DBG_FNC_TCP_SLOW | DBG_FUNC_END,
501 tws_checked, cur_tw_slot, 0, 0, 0);
502 /* Lock upgrade failed, give up this round */
503 atomic_add_32(&ipi->ipi_gc_req.intimer_fast, 1);
504 return;
2d21ac55 505 }
39236c6e
A
506 /* Upgrade failed, lost lock now take it again exclusive */
507 lck_rw_lock_exclusive(ipi->ipi_lock);
2d21ac55
A
508 }
509 tcp_gc_done = TRUE;
1c79356b 510
39236c6e
A
511 LIST_FOREACH_SAFE(inp, &tcb, inp_list, nxt) {
512 if (tcp_garbage_collect(inp, 0))
513 atomic_add_32(&ipi->ipi_gc_req.intimer_fast, 1);
514 }
2d21ac55 515
39236c6e
A
516 /* Now cleanup the time wait ones */
517 TAILQ_FOREACH_SAFE(tw_tp, &tcp_tw_tailq, t_twentry, tw_ntp) {
518 /*
519 * We check the timestamp here without holding the
520 * socket lock for better performance. If there are
521 * any pcbs in time-wait, the timer will get rescheduled.
522 * Hence some error in this check can be tolerated.
15129b1c
A
523 *
524 * Sometimes a socket on time-wait queue can be closed if
525 * 2MSL timer expired but the application still has a
526 * usecount on it.
39236c6e 527 */
15129b1c
A
528 if (tw_tp->t_state == TCPS_CLOSED ||
529 TSTMP_GEQ(tcp_now, tw_tp->t_timer[TCPT_2MSL])) {
39236c6e
A
530 if (tcp_garbage_collect(tw_tp->t_inpcb, 1))
531 atomic_add_32(&ipi->ipi_gc_req.intimer_lazy, 1);
2d21ac55 532 }
91447636
A
533 }
534
39236c6e
A
535 /* take into account pcbs that are still in time_wait_slots */
536 atomic_add_32(&ipi->ipi_gc_req.intimer_lazy, ipi->ipi_twcount);
91447636 537
39236c6e 538 lck_rw_done(ipi->ipi_lock);
1c79356b 539
39236c6e
A
540 /* Clean up the socache while we are here */
541 if (so_cache_timer())
542 atomic_add_32(&ipi->ipi_gc_req.intimer_lazy, 1);
91447636 543
39236c6e
A
544 KERNEL_DEBUG(DBG_FNC_TCP_SLOW | DBG_FUNC_END, tws_checked,
545 cur_tw_slot, 0, 0, 0);
546
547 return;
1c79356b
A
548}
549
550/*
551 * Cancel all timers for TCP tp.
552 */
553void
554tcp_canceltimers(tp)
555 struct tcpcb *tp;
556{
557 register int i;
558
6d2010ae 559 tcp_remove_timer(tp);
1c79356b
A
560 for (i = 0; i < TCPT_NTIMERS; i++)
561 tp->t_timer[i] = 0;
6d2010ae
A
562 tp->tentry.timer_start = tcp_now;
563 tp->tentry.index = TCPT_NONE;
1c79356b
A
564}
565
9bccf70c
A
566int tcp_syn_backoff[TCP_MAXRXTSHIFT + 1] =
567 { 1, 1, 1, 1, 1, 2, 4, 8, 16, 32, 64, 64, 64 };
568
1c79356b
A
569int tcp_backoff[TCP_MAXRXTSHIFT + 1] =
570 { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };
571
572static int tcp_totbackoff = 511; /* sum of tcp_backoff[] */
573
39236c6e
A
574static void tcp_rexmt_save_state(struct tcpcb *tp)
575{
576 u_int32_t fsize;
577 if (TSTMP_SUPPORTED(tp)) {
578 /*
579 * Since timestamps are supported on the connection,
580 * we can do recovery as described in rfc 4015.
581 */
582 fsize = tp->snd_max - tp->snd_una;
583 tp->snd_ssthresh_prev = max(fsize, tp->snd_ssthresh);
584 tp->snd_recover_prev = tp->snd_recover;
585 } else {
586 /*
587 * Timestamp option is not supported on this connection.
588 * Record ssthresh and cwnd so they can
589 * be recovered if this turns out to be a "bad" retransmit.
590 * A retransmit is considered "bad" if an ACK for this
591 * segment is received within RTT/2 interval; the assumption
592 * here is that the ACK was already in flight. See
593 * "On Estimating End-to-End Network Path Properties" by
594 * Allman and Paxson for more details.
595 */
596 tp->snd_cwnd_prev = tp->snd_cwnd;
597 tp->snd_ssthresh_prev = tp->snd_ssthresh;
598 tp->snd_recover_prev = tp->snd_recover;
599 if (IN_FASTRECOVERY(tp))
600 tp->t_flags |= TF_WASFRECOVERY;
601 else
602 tp->t_flags &= ~TF_WASFRECOVERY;
603 }
604 tp->t_srtt_prev = (tp->t_srtt >> TCP_RTT_SHIFT) + 2;
605 tp->t_rttvar_prev = (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
606 tp->t_flagsext &= ~(TF_RECOMPUTE_RTT);
607}
608
1c79356b
A
609/*
610 * TCP timer processing.
611 */
612struct tcpcb *
613tcp_timers(tp, timer)
614 register struct tcpcb *tp;
615 int timer;
616{
617 register int rexmt;
316670eb 618 struct socket *so;
9bccf70c 619 struct tcptemp *t_template;
b0d623f7 620 int optlen = 0;
6d2010ae 621 int idle_time = 0;
9bccf70c 622
55e303ae
A
623#if TCPDEBUG
624 int ostate;
625#endif
626
1c79356b
A
627#if INET6
628 int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV4) == 0;
629#endif /* INET6 */
630
316670eb 631 so = tp->t_inpcb->inp_socket;
6d2010ae 632 idle_time = tcp_now - tp->t_rcvtime;
9bccf70c 633
1c79356b
A
634 switch (timer) {
635
636 /*
637 * 2 MSL timeout in shutdown went off. If we're closed but
638 * still waiting for peer to close and connection has been idle
2d21ac55
A
639 * too long, or if 2MSL time is up from TIME_WAIT or FIN_WAIT_2,
640 * delete connection control block.
641 * Otherwise, (this case shouldn't happen) check again in a bit
642 * we keep the socket in the main list in that case.
1c79356b
A
643 */
644 case TCPT_2MSL:
8ad349bb 645 tcp_free_sackholes(tp);
1c79356b 646 if (tp->t_state != TCPS_TIME_WAIT &&
2d21ac55 647 tp->t_state != TCPS_FIN_WAIT_2 &&
39236c6e
A
648 ((idle_time > 0) && (idle_time < TCP_CONN_MAXIDLE(tp)))) {
649 tp->t_timer[TCPT_2MSL] = OFFSET_FROM_START(tp,
650 (u_int32_t)TCP_CONN_KEEPINTVL(tp));
651 } else {
1c79356b 652 tp = tcp_close(tp);
91447636
A
653 return(tp);
654 }
1c79356b
A
655 break;
656
657 /*
658 * Retransmission timer went off. Message has not
659 * been acked within retransmit interval. Back off
660 * to a longer retransmit interval and retransmit one segment.
661 */
662 case TCPT_REXMT:
6d2010ae
A
663 /* Drop a connection in the retransmit timer
664 * 1. If we have retransmitted more than TCP_MAXRXTSHIFT times
665 * 2. If the time spent in this retransmission episode is more than
666 * the time limit set with TCP_RXT_CONNDROPTIME socket option
667 * 3. If TCP_RXT_FINDROP socket option was set and we have already
668 * retransmitted the FIN 3 times without receiving an ack
669 */
670 if (++tp->t_rxtshift > TCP_MAXRXTSHIFT ||
39236c6e
A
671 (tp->t_rxt_conndroptime > 0 && tp->t_rxtstart > 0 &&
672 (tcp_now - tp->t_rxtstart) >= tp->t_rxt_conndroptime) ||
6d2010ae
A
673 ((tp->t_flagsext & TF_RXTFINDROP) != 0 &&
674 (tp->t_flags & TF_SENTFIN) != 0 &&
675 tp->t_rxtshift >= 4)) {
676
677 if ((tp->t_flagsext & TF_RXTFINDROP) != 0) {
678 tcpstat.tcps_rxtfindrop++;
679 } else {
680 tcpstat.tcps_timeoutdrop++;
681 }
1c79356b 682 tp->t_rxtshift = TCP_MAXRXTSHIFT;
316670eb
A
683 postevent(so, 0, EV_TIMEOUT);
684 soevent(so,
685 (SO_FILT_HINT_LOCKED|SO_FILT_HINT_TIMEOUT));
1c79356b
A
686 tp = tcp_drop(tp, tp->t_softerror ?
687 tp->t_softerror : ETIMEDOUT);
316670eb 688
1c79356b
A
689 break;
690 }
9bccf70c 691
39236c6e 692 tcpstat.tcps_rexmttimeo++;
6d2010ae 693
39236c6e
A
694 if (tp->t_rxtshift == 1 &&
695 tp->t_state == TCPS_ESTABLISHED) {
696 /* Set the time at which retransmission started. */
697 tp->t_rxtstart = tcp_now;
698
699 /*
700 * if this is the first retransmit timeout, save
701 * the state so that we can recover if the timeout
702 * is spurious.
703 */
704 tcp_rexmt_save_state(tp);
705 }
706#if MPTCP
707 if ((tp->t_rxtshift == mptcp_fail_thresh) &&
708 (tp->t_state == TCPS_ESTABLISHED) &&
709 (tp->t_mpflags & TMPF_MPTCP_TRUE)) {
710 mptcp_act_on_txfail(so);
711
712 }
713#endif /* MPTCP */
714
715 if (tp->t_adaptive_wtimo > 0 &&
716 tp->t_rxtshift > tp->t_adaptive_wtimo &&
717 TCPS_HAVEESTABLISHED(tp->t_state)) {
718 /* Send an event to the application */
719 soevent(so,
720 (SO_FILT_HINT_LOCKED|
721 SO_FILT_HINT_ADAPTIVE_WTIMO));
9bccf70c 722 }
316670eb 723
39236c6e 724 if (tp->t_state == TCPS_SYN_SENT) {
9bccf70c 725 rexmt = TCP_REXMTVAL(tp) * tcp_syn_backoff[tp->t_rxtshift];
39236c6e
A
726 tp->t_stat.synrxtshift = tp->t_rxtshift;
727 }
9bccf70c
A
728 else
729 rexmt = TCP_REXMTVAL(tp) * tcp_backoff[tp->t_rxtshift];
1c79356b 730 TCPT_RANGESET(tp->t_rxtcur, rexmt,
6d2010ae
A
731 tp->t_rttmin, TCPTV_REXMTMAX,
732 TCP_ADD_REXMTSLOP(tp));
733 tp->t_timer[TCPT_REXMT] = OFFSET_FROM_START(tp, tp->t_rxtcur);
9bccf70c 734
316670eb
A
735 if (INP_WAIT_FOR_IF_FEEDBACK(tp->t_inpcb))
736 goto fc_output;
737
738 tcp_free_sackholes(tp);
9bccf70c 739 /*
b0d623f7
A
740 * Check for potential Path MTU Discovery Black Hole
741 */
742
743 if (tcp_pmtud_black_hole_detect && (tp->t_state == TCPS_ESTABLISHED)) {
316670eb
A
744 if (((tp->t_flags & (TF_PMTUD|TF_MAXSEGSNT)) == (TF_PMTUD|TF_MAXSEGSNT)) &&
745 (tp->t_rxtshift == 2)) {
b0d623f7
A
746 /*
747 * Enter Path MTU Black-hole Detection mechanism:
748 * - Disable Path MTU Discovery (IP "DF" bit).
749 * - Reduce MTU to lower value than what we negociated with peer.
750 */
39236c6e
A
751 /* Disable Path MTU Discovery for now */
752 tp->t_flags &= ~TF_PMTUD;
753 /* Record that we may have found a black hole */
754 tp->t_flags |= TF_BLACKHOLE;
b0d623f7 755 optlen = tp->t_maxopd - tp->t_maxseg;
39236c6e
A
756 /* Keep track of previous MSS */
757 tp->t_pmtud_saved_maxopd = tp->t_maxopd;
758 /* Reduce the MSS to intermediary value */
759 if (tp->t_maxopd > tcp_pmtud_black_hole_mss) {
760 tp->t_maxopd = tcp_pmtud_black_hole_mss;
761 } else {
b0d623f7
A
762 tp->t_maxopd = /* use the default MSS */
763#if INET6
764 isipv6 ? tcp_v6mssdflt :
765#endif /* INET6 */
766 tcp_mssdflt;
767 }
768 tp->t_maxseg = tp->t_maxopd - optlen;
6d2010ae
A
769
770 /*
39236c6e
A
771 * Reset the slow-start flight size
772 * as it may depend on the new MSS
6d2010ae
A
773 */
774 if (CC_ALGO(tp)->cwnd_init != NULL)
775 CC_ALGO(tp)->cwnd_init(tp);
b0d623f7
A
776 }
777 /*
778 * If further retransmissions are still unsuccessful with a lowered MTU,
779 * maybe this isn't a Black Hole and we restore the previous MSS and
780 * blackhole detection flags.
781 */
782 else {
783
784 if ((tp->t_flags & TF_BLACKHOLE) && (tp->t_rxtshift > 4)) {
785 tp->t_flags |= TF_PMTUD;
786 tp->t_flags &= ~TF_BLACKHOLE;
787 optlen = tp->t_maxopd - tp->t_maxseg;
788 tp->t_maxopd = tp->t_pmtud_saved_maxopd;
789 tp->t_maxseg = tp->t_maxopd - optlen;
6d2010ae 790 /*
39236c6e
A
791 * Reset the slow-start flight size as it
792 * may depend on the new MSS
793 */
6d2010ae
A
794 if (CC_ALGO(tp)->cwnd_init != NULL)
795 CC_ALGO(tp)->cwnd_init(tp);
b0d623f7
A
796 }
797 }
798 }
799
800
801 /*
802 * Disable rfc1323 and rfc1644 if we haven't got any response to
803 * our SYN (after we reach the threshold) to work-around some
804 * broken terminal servers (most of which have hopefully been
805 * retired) that have bad VJ header compression code which
806 * trashes TCP segments containing unknown-to-them TCP options.
39236c6e 807 * Do this only on non-local connections.
9bccf70c 808 */
39236c6e
A
809 if (tp->t_state == TCPS_SYN_SENT &&
810 ((!(tp->t_flags & TF_LOCAL) &&
811 tp->t_rxtshift == tcp_broken_peer_syn_rxmit_thres) ||
812 ((tp->t_flags & TF_LOCAL) &&
813 tp->t_rxtshift == tcp_broken_peer_syn_rxmit_thres_local)))
b0d623f7 814 tp->t_flags &= ~(TF_REQ_SCALE|TF_REQ_TSTMP|TF_REQ_CC);
316670eb 815
1c79356b
A
816 /*
817 * If losing, let the lower level know and try for
818 * a better route. Also, if we backed off this far,
819 * our srtt estimate is probably bogus. Clobber it
820 * so we'll take the next rtt measurement as our srtt;
821 * move the current srtt into rttvar to keep the current
822 * retransmit times until then.
823 */
824 if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
825#if INET6
826 if (isipv6)
827 in6_losing(tp->t_inpcb);
828 else
829#endif /* INET6 */
830 in_losing(tp->t_inpcb);
831 tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
832 tp->t_srtt = 0;
833 }
834 tp->snd_nxt = tp->snd_una;
9bccf70c
A
835 /*
836 * Note: We overload snd_recover to function also as the
837 * snd_last variable described in RFC 2582
838 */
839 tp->snd_recover = tp->snd_max;
1c79356b
A
840 /*
841 * Force a segment to be sent.
842 */
843 tp->t_flags |= TF_ACKNOW;
844 /*
845 * If timing a segment in this window, stop the timer.
846 */
9bccf70c 847 tp->t_rtttime = 0;
6d2010ae 848
39236c6e
A
849 EXIT_FASTRECOVERY(tp);
850
851 /* RFC 5681 says: when a TCP sender detects segment loss
852 * using retransmit timer and the given segment has already
853 * been retransmitted by way of the retransmission timer at
854 * least once, the value of ssthresh is held constant
855 */
856 if (tp->t_rxtshift == 1 &&
857 CC_ALGO(tp)->after_timeout != NULL)
6d2010ae
A
858 CC_ALGO(tp)->after_timeout(tp);
859
6d2010ae 860
316670eb
A
861 /* CWR notifications are to be sent on new data right after
862 * RTOs, Fast Retransmits and ECE notification receipts.
863 */
864 if ((tp->ecn_flags & TE_ECN_ON) == TE_ECN_ON) {
865 tp->ecn_flags |= TE_SENDCWR;
866 }
867fc_output:
6d2010ae
A
868 DTRACE_TCP5(cc, void, NULL, struct inpcb *, tp->t_inpcb,
869 struct tcpcb *, tp, struct tcphdr *, NULL,
870 int32_t, TCP_CC_REXMT_TIMEOUT);
871
1c79356b
A
872 (void) tcp_output(tp);
873 break;
874
875 /*
876 * Persistance timer into zero window.
877 * Force a byte to be output, if possible.
878 */
879 case TCPT_PERSIST:
880 tcpstat.tcps_persisttimeo++;
881 /*
882 * Hack: if the peer is dead/unreachable, we do not
883 * time out if the window is closed. After a full
884 * backoff, drop the connection if the idle time
885 * (no responses to probes) reaches the maximum
886 * backoff that we would use if retransmitting.
6d2010ae
A
887 *
888 * Drop the connection if we reached the maximum allowed time for
889 * Zero Window Probes without a non-zero update from the peer.
890 * See rdar://5805356
1c79356b 891 */
6d2010ae
A
892 if ((tp->t_rxtshift == TCP_MAXRXTSHIFT &&
893 (idle_time >= tcp_maxpersistidle ||
894 idle_time >= TCP_REXMTVAL(tp) * tcp_totbackoff)) ||
316670eb
A
895 ((tp->t_persist_stop != 0) &&
896 TSTMP_LEQ(tp->t_persist_stop, tcp_now))) {
1c79356b 897 tcpstat.tcps_persistdrop++;
316670eb
A
898 postevent(so, 0, EV_TIMEOUT);
899 soevent(so,
900 (SO_FILT_HINT_LOCKED|SO_FILT_HINT_TIMEOUT));
1c79356b 901 tp = tcp_drop(tp, ETIMEDOUT);
1c79356b
A
902 break;
903 }
904 tcp_setpersist(tp);
905 tp->t_force = 1;
906 (void) tcp_output(tp);
907 tp->t_force = 0;
908 break;
909
910 /*
911 * Keep-alive timer went off; send something
912 * or drop connection if idle for too long.
913 */
914 case TCPT_KEEP:
915 tcpstat.tcps_keeptimeo++;
39236c6e
A
916#if MPTCP
917 /*
918 * Regular TCP connections do not send keepalives after closing
919 * MPTCP must not also, after sending Data FINs.
920 */
921 struct mptcb *mp_tp = tp->t_mptcb;
922 if ((tp->t_mpflags & TMPF_MPTCP_TRUE) &&
923 (mp_tp == NULL)) {
924 goto dropit;
925 } else if (mp_tp != NULL) {
926 if ((mptcp_ok_to_keepalive(mp_tp) == 0))
927 goto dropit;
928 }
929#endif /* MPTCP */
1c79356b
A
930 if (tp->t_state < TCPS_ESTABLISHED)
931 goto dropit;
932 if ((always_keepalive ||
39236c6e
A
933 (tp->t_inpcb->inp_socket->so_options & SO_KEEPALIVE) ||
934 (tp->t_flagsext & TF_DETECT_READSTALL)) &&
2d21ac55 935 (tp->t_state <= TCPS_CLOSING || tp->t_state == TCPS_FIN_WAIT_2)) {
39236c6e 936 if (idle_time >= TCP_CONN_KEEPIDLE(tp) + TCP_CONN_MAXIDLE(tp))
1c79356b
A
937 goto dropit;
938 /*
939 * Send a packet designed to force a response
940 * if the peer is up and reachable:
941 * either an ACK if the connection is still alive,
942 * or an RST if the peer has closed the connection
943 * due to timeout or reboot.
944 * Using sequence number tp->snd_una-1
945 * causes the transmitted zero-length segment
946 * to lie outside the receive window;
947 * by the protocol spec, this requires the
948 * correspondent TCP to respond.
949 */
950 tcpstat.tcps_keepprobe++;
9bccf70c
A
951 t_template = tcp_maketemplate(tp);
952 if (t_template) {
6d2010ae 953 unsigned int ifscope, nocell = 0;
c910b4d9
A
954
955 if (tp->t_inpcb->inp_flags & INP_BOUND_IF)
316670eb 956 ifscope = tp->t_inpcb->inp_boundifp->if_index;
c910b4d9
A
957 else
958 ifscope = IFSCOPE_NONE;
959
6d2010ae
A
960 /*
961 * If the socket isn't allowed to use the
962 * cellular interface, indicate it as such.
963 */
964 if (tp->t_inpcb->inp_flags & INP_NO_IFT_CELLULAR)
965 nocell = 1;
966
9bccf70c
A
967 tcp_respond(tp, t_template->tt_ipgen,
968 &t_template->tt_t, (struct mbuf *)NULL,
6d2010ae
A
969 tp->rcv_nxt, tp->snd_una - 1, 0, ifscope,
970 nocell);
9bccf70c 971 (void) m_free(dtom(t_template));
39236c6e
A
972 if (tp->t_flagsext & TF_DETECT_READSTALL)
973 tp->t_rtimo_probes++;
974 }
975 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
976 TCP_CONN_KEEPINTVL(tp));
977 } else {
978 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(tp,
979 TCP_CONN_KEEPIDLE(tp));
980 }
981 if (tp->t_flagsext & TF_DETECT_READSTALL) {
982 /*
983 * The keep alive packets sent to detect a read
984 * stall did not get a response from the
985 * peer. Generate more keep-alives to confirm this.
986 * If the number of probes sent reaches the limit,
987 * generate an event.
988 */
989 if (tp->t_rtimo_probes > tp->t_adaptive_rtimo) {
990 /* Generate an event */
991 soevent(so,
992 (SO_FILT_HINT_LOCKED|
993 SO_FILT_HINT_ADAPTIVE_RTIMO));
994 tcp_keepalive_reset(tp);
995 } else {
996 tp->t_timer[TCPT_KEEP] = OFFSET_FROM_START(
997 tp, TCP_REXMTVAL(tp));
9bccf70c 998 }
39236c6e 999 }
6d2010ae
A
1000 break;
1001 case TCPT_DELACK:
1002 if (tcp_delack_enabled && (tp->t_flags & TF_DELACK)) {
1003 tp->t_flags &= ~TF_DELACK;
1004 tp->t_timer[TCPT_DELACK] = 0;
1005 tp->t_flags |= TF_ACKNOW;
1006
39236c6e 1007 /* If delayed ack timer fired while stretching acks
6d2010ae
A
1008 * go back to acking every other packet
1009 */
1010 if ((tp->t_flags & TF_STRETCHACK) != 0)
1011 tcp_reset_stretch_ack(tp);
1012
316670eb
A
1013 /* If we are measuring inter packet arrival jitter for
1014 * throttling a connection, this delayed ack might be
1015 * the reason for accumulating some jitter. So let's
1016 * restart the measurement.
1017 */
1018 CLEAR_IAJ_STATE(tp);
1019
6d2010ae
A
1020 tcpstat.tcps_delack++;
1021 (void) tcp_output(tp);
1022 }
1c79356b 1023 break;
9bccf70c 1024
39236c6e
A
1025#if MPTCP
1026 case TCPT_JACK_RXMT:
1027 if ((tp->t_state == TCPS_ESTABLISHED) &&
1028 (tp->t_mpflags & TMPF_PREESTABLISHED) &&
1029 (tp->t_mpflags & TMPF_JOINED_FLOW)) {
1030 if (++tp->t_mprxtshift > TCP_MAXRXTSHIFT) {
1031 tcpstat.tcps_timeoutdrop++;
1032 postevent(so, 0, EV_TIMEOUT);
1033 soevent(so,
1034 (SO_FILT_HINT_LOCKED|
1035 SO_FILT_HINT_TIMEOUT));
1036 tp = tcp_drop(tp, tp->t_softerror ?
1037 tp->t_softerror : ETIMEDOUT);
1038 break;
1039 }
1040 tcpstat.tcps_join_rxmts++;
1041 tp->t_flags |= TF_ACKNOW;
1042
1043 /*
1044 * No backoff is implemented for simplicity for this
1045 * corner case.
1046 */
1047 (void) tcp_output(tp);
1048 }
1049 break;
1050#endif /* MPTCP */
1051
9bccf70c
A
1052#if TCPDEBUG
1053 if (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)
1054 tcp_trace(TA_USER, ostate, tp, (void *)0, (struct tcphdr *)0,
1055 PRU_SLOWTIMO);
1056#endif
1c79356b
A
1057 dropit:
1058 tcpstat.tcps_keepdrops++;
316670eb
A
1059 postevent(so, 0, EV_TIMEOUT);
1060 soevent(so,
1061 (SO_FILT_HINT_LOCKED|SO_FILT_HINT_TIMEOUT));
1c79356b 1062 tp = tcp_drop(tp, ETIMEDOUT);
1c79356b
A
1063 break;
1064 }
1065 return (tp);
1066}
6d2010ae
A
1067
1068/* Remove a timer entry from timer list */
1069void
1070tcp_remove_timer(struct tcpcb *tp)
1071{
1072 struct tcptimerlist *listp = &tcp_timer_list;
1073
1074 lck_mtx_assert(&tp->t_inpcb->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
1075 if (!(TIMER_IS_ON_LIST(tp))) {
1076 return;
1077 }
1078 lck_mtx_lock(listp->mtx);
1079
1080 /* Check if pcb is on timer list again after acquiring the lock */
1081 if (!(TIMER_IS_ON_LIST(tp))) {
1082 lck_mtx_unlock(listp->mtx);
1083 return;
1084 }
1085
1086 if (listp->next_te != NULL && listp->next_te == &tp->tentry)
1087 listp->next_te = LIST_NEXT(&tp->tentry, le);
1088
1089 LIST_REMOVE(&tp->tentry, le);
1090 tp->t_flags &= ~(TF_TIMER_ONLIST);
1091
1092 listp->entries--;
6d2010ae
A
1093
1094 tp->tentry.le.le_next = NULL;
1095 tp->tentry.le.le_prev = NULL;
ebb1b9f4 1096 lck_mtx_unlock(listp->mtx);
6d2010ae
A
1097}
1098
1099/* Function to check if the timerlist needs to be rescheduled to run
1100 * the timer entry correctly. Basically, this is to check if we can avoid
1101 * taking the list lock.
1102 */
1103
1104static boolean_t
1105need_to_resched_timerlist(uint32_t runtime, uint16_t index) {
1106 struct tcptimerlist *listp = &tcp_timer_list;
1107 int32_t diff;
1108 boolean_t is_fast;
1109
1110 if (runtime == 0 || index == TCPT_NONE)
1111 return FALSE;
1112 is_fast = !(IS_TIMER_SLOW(index));
1113
1114 /* If the list is being processed then the state of the list is in flux.
1115 * In this case always acquire the lock and set the state correctly.
1116 */
1117 if (listp->running) {
1118 return TRUE;
1119 }
1120
1121 diff = timer_diff(listp->runtime, 0, runtime, 0);
1122 if (diff <= 0) {
1123 /* The list is going to run before this timer */
1124 return FALSE;
1125 } else {
1126 if (is_fast) {
1127 if (diff <= listp->fast_quantum)
1128 return FALSE;
1129 } else {
1130 if (diff <= listp->slow_quantum)
1131 return FALSE;
1132 }
1133 }
1134 return TRUE;
1135}
1136
1137void
1138tcp_sched_timerlist(uint32_t offset)
1139{
1140
1141 uint64_t deadline = 0;
1142 struct tcptimerlist *listp = &tcp_timer_list;
1143
1144 lck_mtx_assert(listp->mtx, LCK_MTX_ASSERT_OWNED);
1145
1146 listp->runtime = tcp_now + offset;
1147
1148 clock_interval_to_deadline(offset, NSEC_PER_SEC / TCP_RETRANSHZ,
1149 &deadline);
1150
1151 thread_call_enter_delayed(listp->call, deadline);
1152}
1153
1154/* Function to run the timers for a connection.
1155 *
1156 * Returns the offset of next timer to be run for this connection which
1157 * can be used to reschedule the timerlist.
1158 */
1159uint32_t
1160tcp_run_conn_timer(struct tcpcb *tp, uint16_t *next_index) {
1161
1162 struct socket *so;
1163 uint16_t i = 0, index = TCPT_NONE, lo_index = TCPT_NONE;
1164 uint32_t timer_val, offset = 0, lo_timer = 0;
1165 int32_t diff;
1166 boolean_t needtorun[TCPT_NTIMERS];
1167 int count = 0;
1168
1169 VERIFY(tp != NULL);
1170 bzero(needtorun, sizeof(needtorun));
1171
1172 tcp_lock(tp->t_inpcb->inp_socket, 1, 0);
1173
1174 so = tp->t_inpcb->inp_socket;
1175 /* Release the want count on inp */
1176 if (in_pcb_checkstate(tp->t_inpcb, WNT_RELEASE, 1) == WNT_STOPUSING) {
1177 if (TIMER_IS_ON_LIST(tp)) {
1178 tcp_remove_timer(tp);
1179 }
1180
1181 /* Looks like the TCP connection got closed while we
1182 * were waiting for the lock.. Done
1183 */
1184 goto done;
1185 }
1186
1187 /* Since the timer thread needs to wait for tcp lock, it may race
1188 * with another thread that can cancel or reschedule the timer that is
1189 * about to run. Check if we need to run anything.
1190 */
1191 index = tp->tentry.index;
1192 timer_val = tp->t_timer[index];
1193
1194 if (index == TCPT_NONE || tp->tentry.runtime == 0)
1195 goto done;
1196
1197 diff = timer_diff(tp->tentry.runtime, 0, tcp_now, 0);
1198 if (diff > 0) {
1199 if (tp->tentry.index != TCPT_NONE) {
1200 offset = diff;
1201 *(next_index) = tp->tentry.index;
1202 }
1203 goto done;
1204 }
1205
1206 tp->t_timer[index] = 0;
1207 if (timer_val > 0) {
1208 tp = tcp_timers(tp, index);
1209 if (tp == NULL)
1210 goto done;
1211 }
1212
1213 /* Check if there are any other timers that need to be run. While doing it,
1214 * adjust the timer values wrt tcp_now.
1215 */
1216 for (i = 0; i < TCPT_NTIMERS; ++i) {
1217 if (tp->t_timer[i] != 0) {
1218 diff = timer_diff(tp->tentry.timer_start, tp->t_timer[i], tcp_now, 0);
1219 if (diff <= 0) {
1220 tp->t_timer[i] = 0;
1221 needtorun[i] = TRUE;
1222 count++;
1223 } else {
1224 tp->t_timer[i] = diff;
1225 needtorun[i] = FALSE;
1226 if (lo_timer == 0 || diff < lo_timer) {
1227 lo_timer = diff;
1228 lo_index = i;
1229 }
1230 }
1231 }
1232 }
1233
1234 tp->tentry.timer_start = tcp_now;
1235 tp->tentry.index = lo_index;
1236 if (lo_index != TCPT_NONE) {
1237 tp->tentry.runtime = tp->tentry.timer_start + tp->t_timer[lo_index];
1238 } else {
1239 tp->tentry.runtime = 0;
1240 }
1241
1242 if (count > 0) {
1243 /* run any other timers that are also outstanding at this time. */
1244 for (i = 0; i < TCPT_NTIMERS; ++i) {
1245 if (needtorun[i]) {
1246 tp->t_timer[i] = 0;
1247 tp = tcp_timers(tp, i);
1248 if (tp == NULL)
1249 goto done;
1250 }
1251 }
1252 tcp_set_lotimer_index(tp);
1253 }
1254
1255 if (tp->tentry.index < TCPT_NONE) {
1256 offset = tp->t_timer[tp->tentry.index];
1257 *(next_index) = tp->tentry.index;
1258 }
1259
1260done:
1261 if (tp != NULL && tp->tentry.index == TCPT_NONE) {
1262 tcp_remove_timer(tp);
1263 }
1264 tcp_unlock(so, 1, 0);
1265 return offset;
1266}
1267
1268void
1269tcp_run_timerlist(void * arg1, void * arg2) {
1270
1271#pragma unused(arg1, arg2)
1272
1273 struct tcptimerentry *te, *next_te;
1274 struct tcptimerlist *listp = &tcp_timer_list;
1275 struct tcpcb *tp;
1276 uint32_t next_timer = 0;
1277 uint16_t index = TCPT_NONE;
1278 boolean_t need_fast = FALSE;
1279 uint32_t active_count = 0;
1280 uint32_t mode = TCP_TIMERLIST_FASTMODE;
1281
1282 calculate_tcp_clock();
1283
1284 lck_mtx_lock(listp->mtx);
1285
1286 listp->running = TRUE;
1287
1288 LIST_FOREACH_SAFE(te, &listp->lhead, le, next_te) {
1289 uint32_t offset = 0;
1290 uint32_t runtime = te->runtime;
1291 if (TSTMP_GT(runtime, tcp_now)) {
1292 offset = timer_diff(runtime, 0, tcp_now, 0);
1293 if (next_timer == 0 || offset < next_timer) {
1294 next_timer = offset;
1295 }
1296 continue;
1297 }
1298 active_count++;
1299
1300 tp = TIMERENTRY_TO_TP(te);
1301
1302 /* Acquire an inp wantcnt on the inpcb so that the socket won't get
1303 * detached even if tcp_close is called
1304 */
1305 if (in_pcb_checkstate(tp->t_inpcb, WNT_ACQUIRE, 0) == WNT_STOPUSING) {
1306 /* Some how this pcb went into dead state while on the timer list,
1307 * just take it off the list. Since the timer list entry pointers
1308 * are protected by the timer list lock, we can do it here
1309 */
1310 if (TIMER_IS_ON_LIST(tp)) {
1311 tp->t_flags &= ~(TF_TIMER_ONLIST);
1312 LIST_REMOVE(&tp->tentry, le);
1313 listp->entries--;
1314
1315 tp->tentry.le.le_next = NULL;
1316 tp->tentry.le.le_prev = NULL;
1317 }
1318 continue;
1319 }
1320
1321 /* Store the next timerentry pointer before releasing the list lock.
1322 * If that entry has to be removed when we release the lock, this
1323 * pointer will be updated to the element after that.
1324 */
1325 listp->next_te = next_te;
1326
1327 VERIFY_NEXT_LINK(&tp->tentry, le);
1328 VERIFY_PREV_LINK(&tp->tentry, le);
1329
1330 lck_mtx_unlock(listp->mtx);
1331
1332 index = TCPT_NONE;
1333 offset = tcp_run_conn_timer(tp, &index);
1334
1335 lck_mtx_lock(listp->mtx);
1336
1337 next_te = listp->next_te;
1338 listp->next_te = NULL;
1339
1340 if (offset > 0) {
1341 if (index < TCPT_NONE) {
1342 /* Check if this is a fast_timer. */
1343 if (!need_fast && !(IS_TIMER_SLOW(index))) {
1344 need_fast = TRUE;
1345 }
1346
1347 if (next_timer == 0 || offset < next_timer) {
1348 next_timer = offset;
1349 }
1350 }
1351 }
1352 }
1353
1354 if (!LIST_EMPTY(&listp->lhead)) {
1355 if (listp->mode == TCP_TIMERLIST_FASTMODE) {
1356 if (need_fast || active_count > 0 ||
1357 listp->pref_mode == TCP_TIMERLIST_FASTMODE) {
1358 listp->idlegen = 0;
1359 } else {
1360 listp->idlegen++;
1361 if (listp->idlegen > timer_fastmode_idlemax) {
1362 mode = TCP_TIMERLIST_SLOWMODE;
1363 listp->idlegen = 0;
1364 }
1365 }
1366 } else {
1367 if (!need_fast) {
1368 mode = TCP_TIMERLIST_SLOWMODE;
1369 }
1370 }
1371
1372 if (mode == TCP_TIMERLIST_FASTMODE ||
1373 listp->pref_mode == TCP_TIMERLIST_FASTMODE) {
1374 next_timer = listp->fast_quantum;
1375 } else {
1376 if (listp->pref_offset != 0 &&
1377 listp->pref_offset < next_timer)
1378 next_timer = listp->pref_offset;
1379 if (next_timer < listp->slow_quantum)
1380 next_timer = listp->slow_quantum;
1381 }
1382
1383 listp->mode = mode;
1384
1385 tcp_sched_timerlist(next_timer);
1386 } else {
1387 /* No need to reschedule this timer */
1388 listp->runtime = 0;
1389 }
1390
1391 listp->running = FALSE;
1392 listp->pref_mode = 0;
1393 listp->pref_offset = 0;
1394
1395 lck_mtx_unlock(listp->mtx);
1396}
1397
1398/* Function to verify if a change in timer state is required for a connection */
1399void
1400tcp_sched_timers(struct tcpcb *tp)
1401{
1402 struct tcptimerentry *te = &tp->tentry;
1403 uint16_t index = te->index;
1404 struct tcptimerlist *listp = &tcp_timer_list;
1405 uint32_t offset = 0;
1406 boolean_t is_fast;
1407 int list_locked = 0;
1408
1409 if (tp->t_inpcb->inp_state == INPCB_STATE_DEAD) {
1410 /* Just return without adding the dead pcb to the list */
1411 if (TIMER_IS_ON_LIST(tp)) {
1412 tcp_remove_timer(tp);
1413 }
1414 return;
1415 }
1416
1417 if (index == TCPT_NONE) {
1418 tcp_remove_timer(tp);
1419 return;
1420 }
1421
1422 is_fast = !(IS_TIMER_SLOW(index));
1423 offset = te->runtime - tcp_now;
1424 if (offset == 0) {
1425 offset = 1;
1426 tcp_timer_advanced++;
1427 }
1428 if (is_fast)
1429 offset = listp->fast_quantum;
1430
1431 if (!TIMER_IS_ON_LIST(tp)) {
1432 if (!list_locked) {
1433 lck_mtx_lock(listp->mtx);
1434 list_locked = 1;
1435 }
1436
1437 LIST_INSERT_HEAD(&listp->lhead, te, le);
1438 tp->t_flags |= TF_TIMER_ONLIST;
1439
1440 listp->entries++;
1441 if (listp->entries > listp->maxentries)
1442 listp->maxentries = listp->entries;
1443
1444 /* if the list is not scheduled, just schedule it */
1445 if (listp->runtime == 0)
1446 goto schedule;
1447
1448 }
1449
1450
1451 /* timer entry is currently on the list */
1452 if (need_to_resched_timerlist(te->runtime, index)) {
1453 tcp_resched_timerlist++;
1454
1455 if (!list_locked) {
1456 lck_mtx_lock(listp->mtx);
1457 list_locked = 1;
1458 }
1459
1460 VERIFY_NEXT_LINK(te, le);
1461 VERIFY_PREV_LINK(te, le);
1462
1463 if (listp->running) {
1464 if (is_fast) {
1465 listp->pref_mode = TCP_TIMERLIST_FASTMODE;
1466 } else if (listp->pref_offset == 0 ||
1467 ((int)offset) < listp->pref_offset) {
1468 listp->pref_offset = offset;
1469 }
1470 } else {
1471 int32_t diff;
1472 diff = timer_diff(listp->runtime, 0, tcp_now, offset);
1473 if (diff <= 0) {
1474 /* The list is going to run before this timer */
1475 goto done;
1476 } else {
1477 goto schedule;
1478 }
1479 }
1480 }
1481 goto done;
1482
1483schedule:
1484 if (is_fast) {
1485 listp->mode = TCP_TIMERLIST_FASTMODE;
1486 listp->idlegen = 0;
1487 }
1488 tcp_sched_timerlist(offset);
1489
1490done:
1491 if (list_locked)
1492 lck_mtx_unlock(listp->mtx);
1493
1494 return;
1495}
1496
1497void
1498tcp_set_lotimer_index(struct tcpcb *tp) {
1499 uint16_t i, lo_index = TCPT_NONE;
1500 uint32_t lo_timer = 0;
1501 for (i = 0; i < TCPT_NTIMERS; ++i) {
1502 if (tp->t_timer[i] != 0 &&
1503 (lo_timer == 0 || tp->t_timer[i] < lo_timer)) {
1504 lo_timer = tp->t_timer[i];
1505 lo_index = i;
1506 }
1507 }
1508 tp->tentry.index = lo_index;
1509 if (lo_index != TCPT_NONE) {
1510 tp->tentry.runtime = tp->tentry.timer_start + tp->t_timer[lo_index];
1511 } else {
1512 tp->tentry.runtime = 0;
1513 }
1514}
1515
1516void
1517tcp_check_timer_state(struct tcpcb *tp) {
1518
1519 lck_mtx_assert(&tp->t_inpcb->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
1520
1521 tcp_set_lotimer_index(tp);
1522
1523 tcp_sched_timers(tp);
1524 return;
1525}