xref: /openbsd-src/sys/netinet/tcp_timer.c (revision d4c5fc9dc00f5a9cadd8c2de4e52d85d3c1c6003)
1 /*	$OpenBSD: tcp_timer.c,v 1.66 2018/05/10 13:30:25 bluhm Exp $	*/
2 /*	$NetBSD: tcp_timer.c,v 1.14 1996/02/13 23:44:09 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)tcp_timer.c	8.1 (Berkeley) 6/10/93
33  */
34 
35 #include <sys/param.h>
36 #include <sys/systm.h>
37 #include <sys/mbuf.h>
38 #include <sys/socket.h>
39 #include <sys/socketvar.h>
40 #include <sys/protosw.h>
41 #include <sys/kernel.h>
42 #include <sys/pool.h>
43 
44 #include <net/route.h>
45 
46 #include <netinet/in.h>
47 #include <netinet/ip.h>
48 #include <netinet/in_pcb.h>
49 #include <netinet/ip_var.h>
50 #include <netinet/tcp.h>
51 #include <netinet/tcp_fsm.h>
52 #include <netinet/tcp_timer.h>
53 #include <netinet/tcp_var.h>
54 #include <netinet/tcp_debug.h>
55 #include <netinet/ip_icmp.h>
56 #include <netinet/tcp_seq.h>
57 
58 int	tcp_always_keepalive;
59 int	tcp_keepidle;
60 int	tcp_keepintvl;
61 int	tcp_maxpersistidle;	/* max idle time in persist */
62 int	tcp_maxidle;
63 
64 /*
65  * Time to delay the ACK.  This is initialized in tcp_init(), unless
66  * its patched.
67  */
68 int	tcp_delack_msecs;
69 
70 void	tcp_timer_rexmt(void *);
71 void	tcp_timer_persist(void *);
72 void	tcp_timer_keep(void *);
73 void	tcp_timer_2msl(void *);
74 void	tcp_timer_reaper(void *);
75 void	tcp_timer_delack(void *);
76 
77 const tcp_timer_func_t tcp_timer_funcs[TCPT_NTIMERS] = {
78 	tcp_timer_rexmt,
79 	tcp_timer_persist,
80 	tcp_timer_keep,
81 	tcp_timer_2msl,
82 	tcp_timer_reaper,
83 	tcp_timer_delack,
84 };
85 
86 /*
87  * Timer state initialization, called from tcp_init().
88  */
89 void
90 tcp_timer_init(void)
91 {
92 
93 	if (tcp_keepidle == 0)
94 		tcp_keepidle = TCPTV_KEEP_IDLE;
95 
96 	if (tcp_keepintvl == 0)
97 		tcp_keepintvl = TCPTV_KEEPINTVL;
98 
99 	if (tcp_maxpersistidle == 0)
100 		tcp_maxpersistidle = TCPTV_KEEP_IDLE;
101 
102 	if (tcp_delack_msecs == 0)
103 		tcp_delack_msecs = TCP_DELACK_MSECS;
104 }
105 
106 /*
107  * Callout to process delayed ACKs for a TCPCB.
108  */
109 void
110 tcp_timer_delack(void *arg)
111 {
112 	struct tcpcb *tp = arg;
113 	short ostate;
114 
115 	/*
116 	 * If tcp_output() wasn't able to transmit the ACK
117 	 * for whatever reason, it will restart the delayed
118 	 * ACK callout.
119 	 */
120 	NET_LOCK();
121 	/* Ignore canceled timeouts or timeouts that have been rescheduled. */
122 	if (!ISSET((tp)->t_flags, TF_TMR_DELACK) ||
123 	    timeout_pending(&tp->t_timer[TCPT_DELACK]))
124 		goto out;
125 	CLR((tp)->t_flags, TF_TMR_DELACK);
126 
127 	ostate = tp->t_state;
128 	tp->t_flags |= TF_ACKNOW;
129 	(void) tcp_output(tp);
130 	if (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)
131 		tcp_trace(TA_TIMER, ostate, tp, (caddr_t)0, TCPT_DELACK, 0);
132  out:
133 	NET_UNLOCK();
134 }
135 
136 /*
137  * Tcp protocol timeout routine called every 500 ms.
138  * Updates the timers in all active tcb's and
139  * causes finite state machine actions if timers expire.
140  */
141 void
142 tcp_slowtimo(void)
143 {
144 	NET_LOCK();
145 
146 	tcp_maxidle = TCPTV_KEEPCNT * tcp_keepintvl;
147 	tcp_iss += TCP_ISSINCR2/PR_SLOWHZ;		/* increment iss */
148 	tcp_now++;					/* for timestamps */
149 
150 	NET_UNLOCK();
151 }
152 
153 /*
154  * Cancel all timers for TCP tp.
155  */
156 void
157 tcp_canceltimers(struct tcpcb *tp)
158 {
159 	int i;
160 
161 	for (i = 0; i < TCPT_NTIMERS; i++)
162 		TCP_TIMER_DISARM(tp, i);
163 }
164 
165 int	tcp_backoff[TCP_MAXRXTSHIFT + 1] =
166     { 1, 2, 4, 8, 16, 32, 64, 64, 64, 64, 64, 64, 64 };
167 
168 int tcp_totbackoff = 511;	/* sum of tcp_backoff[] */
169 
170 /*
171  * TCP timer processing.
172  */
173 
174 void	tcp_timer_freesack(struct tcpcb *);
175 
176 void
177 tcp_timer_freesack(struct tcpcb *tp)
178 {
179 	struct sackhole *p, *q;
180 	/*
181 	 * Free SACK holes for 2MSL and REXMT timers.
182 	 */
183 	q = tp->snd_holes;
184 	while (q != NULL) {
185 		p = q;
186 		q = q->next;
187 		pool_put(&sackhl_pool, p);
188 	}
189 	tp->snd_holes = 0;
190 }
191 
192 void
193 tcp_timer_rexmt(void *arg)
194 {
195 	struct tcpcb *tp = arg;
196 	uint32_t rto;
197 	short ostate;
198 
199 	NET_LOCK();
200 	/* Ignore canceled timeouts or timeouts that have been rescheduled. */
201 	if (!ISSET((tp)->t_flags, TF_TMR_REXMT) ||
202 	    timeout_pending(&tp->t_timer[TCPT_REXMT]))
203 		goto out;
204 	CLR((tp)->t_flags, TF_TMR_REXMT);
205 
206 	if ((tp->t_flags & TF_PMTUD_PEND) && tp->t_inpcb &&
207 	    SEQ_GEQ(tp->t_pmtud_th_seq, tp->snd_una) &&
208 	    SEQ_LT(tp->t_pmtud_th_seq, (int)(tp->snd_una + tp->t_maxseg))) {
209 		struct sockaddr_in sin;
210 		struct icmp icmp;
211 
212 		tp->t_flags &= ~TF_PMTUD_PEND;
213 
214 		/* XXX create fake icmp message with relevant entries */
215 		icmp.icmp_nextmtu = tp->t_pmtud_nextmtu;
216 		icmp.icmp_ip.ip_len = tp->t_pmtud_ip_len;
217 		icmp.icmp_ip.ip_hl = tp->t_pmtud_ip_hl;
218 		icmp.icmp_ip.ip_dst = tp->t_inpcb->inp_faddr;
219 		icmp_mtudisc(&icmp, tp->t_inpcb->inp_rtableid);
220 
221 		/*
222 		 * Notify all connections to the same peer about
223 		 * new mss and trigger retransmit.
224 		 */
225 		bzero(&sin, sizeof(sin));
226 		sin.sin_len = sizeof(sin);
227 		sin.sin_family = AF_INET;
228 		sin.sin_addr = tp->t_inpcb->inp_faddr;
229 		in_pcbnotifyall(&tcbtable, sintosa(&sin),
230 		    tp->t_inpcb->inp_rtableid, EMSGSIZE, tcp_mtudisc);
231 		goto out;
232 	}
233 
234 	tcp_timer_freesack(tp);
235 	if (++tp->t_rxtshift > TCP_MAXRXTSHIFT) {
236 		tp->t_rxtshift = TCP_MAXRXTSHIFT;
237 		tcpstat_inc(tcps_timeoutdrop);
238 		tp = tcp_drop(tp, tp->t_softerror ?
239 		    tp->t_softerror : ETIMEDOUT);
240 		goto out;
241 	}
242 	ostate = tp->t_state;
243 	tcpstat_inc(tcps_rexmttimeo);
244 	rto = TCP_REXMTVAL(tp);
245 	if (rto < tp->t_rttmin)
246 		rto = tp->t_rttmin;
247 	TCPT_RANGESET(tp->t_rxtcur,
248 	    rto * tcp_backoff[tp->t_rxtshift],
249 	    tp->t_rttmin, TCPTV_REXMTMAX);
250 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
251 
252 	/*
253 	 * If we are losing and we are trying path MTU discovery,
254 	 * try turning it off.  This will avoid black holes in
255 	 * the network which suppress or fail to send "packet
256 	 * too big" ICMP messages.  We should ideally do
257 	 * lots more sophisticated searching to find the right
258 	 * value here...
259 	 */
260 	if (ip_mtudisc && tp->t_inpcb &&
261 	    TCPS_HAVEESTABLISHED(tp->t_state) &&
262 	    tp->t_rxtshift > TCP_MAXRXTSHIFT / 6) {
263 		struct inpcb *inp = tp->t_inpcb;
264 		struct rtentry *rt = NULL;
265 
266 		/* No data to send means path mtu is not a problem */
267 		if (!inp->inp_socket->so_snd.sb_cc)
268 			goto leave;
269 
270 		rt = in_pcbrtentry(inp);
271 		/* Check if path MTU discovery is disabled already */
272 		if (rt && (rt->rt_flags & RTF_HOST) &&
273 		    (rt->rt_locks & RTV_MTU))
274 			goto leave;
275 
276 		rt = NULL;
277 		switch(tp->pf) {
278 #ifdef INET6
279 		case PF_INET6:
280 			/*
281 			 * We can not turn off path MTU for IPv6.
282 			 * Do nothing for now, maybe lower to
283 			 * minimum MTU.
284 			 */
285 			break;
286 #endif
287 		case PF_INET:
288 			rt = icmp_mtudisc_clone(inp->inp_faddr,
289 			    inp->inp_rtableid);
290 			break;
291 		}
292 		if (rt != NULL) {
293 			/* Disable path MTU discovery */
294 			if ((rt->rt_locks & RTV_MTU) == 0) {
295 				rt->rt_locks |= RTV_MTU;
296 				in_rtchange(inp, 0);
297 			}
298 
299 			rtfree(rt);
300 		}
301 	leave:
302 		;
303 	}
304 
305 	/*
306 	 * If losing, let the lower level know and try for
307 	 * a better route.  Also, if we backed off this far,
308 	 * our srtt estimate is probably bogus.  Clobber it
309 	 * so we'll take the next rtt measurement as our srtt;
310 	 * move the current srtt into rttvar to keep the current
311 	 * retransmit times until then.
312 	 */
313 	if (tp->t_rxtshift > TCP_MAXRXTSHIFT / 4) {
314 		in_losing(tp->t_inpcb);
315 		tp->t_rttvar += (tp->t_srtt >> TCP_RTT_SHIFT);
316 		tp->t_srtt = 0;
317 	}
318 	tp->snd_nxt = tp->snd_una;
319 	/*
320 	 * Note:  We overload snd_last to function also as the
321 	 * snd_last variable described in RFC 2582
322 	 */
323 	tp->snd_last = tp->snd_max;
324 	/*
325 	 * If timing a segment in this window, stop the timer.
326 	 */
327 	tp->t_rtttime = 0;
328 #ifdef TCP_ECN
329 	/*
330 	 * if ECN is enabled, there might be a broken firewall which
331 	 * blocks ecn packets.  fall back to non-ecn.
332 	 */
333 	if ((tp->t_state == TCPS_SYN_SENT || tp->t_state == TCPS_SYN_RECEIVED)
334 	    && tcp_do_ecn && !(tp->t_flags & TF_DISABLE_ECN))
335 		tp->t_flags |= TF_DISABLE_ECN;
336 #endif
337 	/*
338 	 * Close the congestion window down to one segment
339 	 * (we'll open it by one segment for each ack we get).
340 	 * Since we probably have a window's worth of unacked
341 	 * data accumulated, this "slow start" keeps us from
342 	 * dumping all that data as back-to-back packets (which
343 	 * might overwhelm an intermediate gateway).
344 	 *
345 	 * There are two phases to the opening: Initially we
346 	 * open by one mss on each ack.  This makes the window
347 	 * size increase exponentially with time.  If the
348 	 * window is larger than the path can handle, this
349 	 * exponential growth results in dropped packet(s)
350 	 * almost immediately.  To get more time between
351 	 * drops but still "push" the network to take advantage
352 	 * of improving conditions, we switch from exponential
353 	 * to linear window opening at some threshold size.
354 	 * For a threshold, we use half the current window
355 	 * size, truncated to a multiple of the mss.
356 	 *
357 	 * (the minimum cwnd that will give us exponential
358 	 * growth is 2 mss.  We don't allow the threshold
359 	 * to go below this.)
360 	 */
361 	{
362 		u_long win = ulmin(tp->snd_wnd, tp->snd_cwnd) / 2 / tp->t_maxseg;
363 		if (win < 2)
364 			win = 2;
365 		tp->snd_cwnd = tp->t_maxseg;
366 		tp->snd_ssthresh = win * tp->t_maxseg;
367 		tp->t_dupacks = 0;
368 #ifdef TCP_ECN
369 		tp->snd_last = tp->snd_max;
370 		tp->t_flags |= TF_SEND_CWR;
371 #endif
372 #if 1 /* TCP_ECN */
373 		tcpstat_inc(tcps_cwr_timeout);
374 #endif
375 	}
376 	(void) tcp_output(tp);
377 	if (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)
378 		tcp_trace(TA_TIMER, ostate, tp, (caddr_t)0, TCPT_REXMT, 0);
379  out:
380 	NET_UNLOCK();
381 }
382 
383 void
384 tcp_timer_persist(void *arg)
385 {
386 	struct tcpcb *tp = arg;
387 	uint32_t rto;
388 	short ostate;
389 
390 	NET_LOCK();
391 	/* Ignore canceled timeouts or timeouts that have been rescheduled. */
392 	if (!ISSET((tp)->t_flags, TF_TMR_PERSIST) ||
393 	    timeout_pending(&tp->t_timer[TCPT_PERSIST]))
394 		goto out;
395 	CLR((tp)->t_flags, TF_TMR_PERSIST);
396 
397 	if (TCP_TIMER_ISARMED(tp, TCPT_REXMT))
398 		goto out;
399 
400 	ostate = tp->t_state;
401 	tcpstat_inc(tcps_persisttimeo);
402 	/*
403 	 * Hack: if the peer is dead/unreachable, we do not
404 	 * time out if the window is closed.  After a full
405 	 * backoff, drop the connection if the idle time
406 	 * (no responses to probes) reaches the maximum
407 	 * backoff that we would use if retransmitting.
408 	 */
409 	rto = TCP_REXMTVAL(tp);
410 	if (rto < tp->t_rttmin)
411 		rto = tp->t_rttmin;
412 	if (tp->t_rxtshift == TCP_MAXRXTSHIFT &&
413 	    ((tcp_now - tp->t_rcvtime) >= tcp_maxpersistidle ||
414 	    (tcp_now - tp->t_rcvtime) >= rto * tcp_totbackoff)) {
415 		tcpstat_inc(tcps_persistdrop);
416 		tp = tcp_drop(tp, ETIMEDOUT);
417 		goto out;
418 	}
419 	tcp_setpersist(tp);
420 	tp->t_force = 1;
421 	(void) tcp_output(tp);
422 	tp->t_force = 0;
423 	if (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)
424 		tcp_trace(TA_TIMER, ostate, tp, (caddr_t)0, TCPT_PERSIST, 0);
425  out:
426 	NET_UNLOCK();
427 }
428 
429 void
430 tcp_timer_keep(void *arg)
431 {
432 	struct tcpcb *tp = arg;
433 	short ostate;
434 
435 	NET_LOCK();
436 	/* Ignore canceled timeouts or timeouts that have been rescheduled. */
437 	if (!ISSET((tp)->t_flags, TF_TMR_KEEP) ||
438 	    timeout_pending(&tp->t_timer[TCPT_KEEP]))
439 		goto out;
440 	CLR((tp)->t_flags, TF_TMR_KEEP);
441 
442 	ostate = tp->t_state;
443 	tcpstat_inc(tcps_keeptimeo);
444 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
445 		goto dropit;
446 	if ((tcp_always_keepalive ||
447 	    tp->t_inpcb->inp_socket->so_options & SO_KEEPALIVE) &&
448 	    tp->t_state <= TCPS_CLOSING) {
449 		if ((tcp_maxidle > 0) &&
450 		    ((tcp_now - tp->t_rcvtime) >= tcp_keepidle + tcp_maxidle))
451 			goto dropit;
452 		/*
453 		 * Send a packet designed to force a response
454 		 * if the peer is up and reachable:
455 		 * either an ACK if the connection is still alive,
456 		 * or an RST if the peer has closed the connection
457 		 * due to timeout or reboot.
458 		 * Using sequence number tp->snd_una-1
459 		 * causes the transmitted zero-length segment
460 		 * to lie outside the receive window;
461 		 * by the protocol spec, this requires the
462 		 * correspondent TCP to respond.
463 		 */
464 		tcpstat_inc(tcps_keepprobe);
465 		tcp_respond(tp, mtod(tp->t_template, caddr_t),
466 		    NULL, tp->rcv_nxt, tp->snd_una - 1, 0, 0);
467 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepintvl);
468 	} else
469 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
470 	if (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)
471 		tcp_trace(TA_TIMER, ostate, tp, (caddr_t)0, TCPT_KEEP, 0);
472  out:
473 	NET_UNLOCK();
474 	return;
475 
476  dropit:
477 	tcpstat_inc(tcps_keepdrops);
478 	tp = tcp_drop(tp, ETIMEDOUT);
479 	NET_UNLOCK();
480 }
481 
482 void
483 tcp_timer_2msl(void *arg)
484 {
485 	struct tcpcb *tp = arg;
486 	short ostate;
487 
488 	NET_LOCK();
489 	/* Ignore canceled timeouts or timeouts that have been rescheduled. */
490 	if (!ISSET((tp)->t_flags, TF_TMR_2MSL) ||
491 	    timeout_pending(&tp->t_timer[TCPT_2MSL]))
492 		goto out;
493 	CLR((tp)->t_flags, TF_TMR_2MSL);
494 
495 	ostate = tp->t_state;
496 	tcp_timer_freesack(tp);
497 
498 	if (tp->t_state != TCPS_TIME_WAIT &&
499 	    ((tcp_maxidle == 0) || ((tcp_now - tp->t_rcvtime) <= tcp_maxidle)))
500 		TCP_TIMER_ARM(tp, TCPT_2MSL, tcp_keepintvl);
501 	else
502 		tp = tcp_close(tp);
503 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
504 		tcp_trace(TA_TIMER, ostate, tp, (caddr_t)0, TCPT_2MSL, 0);
505  out:
506 	NET_UNLOCK();
507 }
508 
509 void
510 tcp_timer_reaper(void *arg)
511 {
512 	struct tcpcb *tp = arg;
513 
514 	/*
515 	 * This timer is necessary to delay the pool_put() after all timers
516 	 * have finished, even if they were sleeping to grab the net lock.
517 	 * Putting the pool_put() in a timer is sufficinet as all timers run
518 	 * from the same timeout thread.  Note that neither softnet thread nor
519 	 * user process may access the tcpcb after arming the reaper timer.
520 	 * Freeing may run in parallel as it does not grab the net lock.
521 	 */
522 	pool_put(&tcpcb_pool, tp);
523 	tcpstat_inc(tcps_closed);
524 }
525