xref: /openbmc/linux/net/ipv4/tcp_timer.c (revision d0e22329)
1 /*
2  * INET		An implementation of the TCP/IP protocol suite for the LINUX
3  *		operating system.  INET is implemented using the  BSD Socket
4  *		interface as the means of communication with the user level.
5  *
6  *		Implementation of the Transmission Control Protocol(TCP).
7  *
8  * Authors:	Ross Biro
9  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10  *		Mark Evans, <evansmp@uhura.aston.ac.uk>
11  *		Corey Minyard <wf-rch!minyard@relay.EU.net>
12  *		Florian La Roche, <flla@stud.uni-sb.de>
13  *		Charles Hedrick, <hedrick@klinzhai.rutgers.edu>
14  *		Linus Torvalds, <torvalds@cs.helsinki.fi>
15  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
16  *		Matthew Dillon, <dillon@apollo.west.oic.com>
17  *		Arnt Gulbrandsen, <agulbra@nvg.unit.no>
18  *		Jorge Cwik, <jorge@laser.satlink.net>
19  */
20 
21 #include <linux/module.h>
22 #include <linux/gfp.h>
23 #include <net/tcp.h>
24 
25 static u32 tcp_retransmit_stamp(const struct sock *sk)
26 {
27 	u32 start_ts = tcp_sk(sk)->retrans_stamp;
28 
29 	if (unlikely(!start_ts)) {
30 		struct sk_buff *head = tcp_rtx_queue_head(sk);
31 
32 		if (!head)
33 			return 0;
34 		start_ts = tcp_skb_timestamp(head);
35 	}
36 	return start_ts;
37 }
38 
39 static u32 tcp_clamp_rto_to_user_timeout(const struct sock *sk)
40 {
41 	struct inet_connection_sock *icsk = inet_csk(sk);
42 	u32 elapsed, start_ts;
43 	s32 remaining;
44 
45 	start_ts = tcp_retransmit_stamp(sk);
46 	if (!icsk->icsk_user_timeout || !start_ts)
47 		return icsk->icsk_rto;
48 	elapsed = tcp_time_stamp(tcp_sk(sk)) - start_ts;
49 	remaining = icsk->icsk_user_timeout - elapsed;
50 	if (remaining <= 0)
51 		return 1; /* user timeout has passed; fire ASAP */
52 
53 	return min_t(u32, icsk->icsk_rto, msecs_to_jiffies(remaining));
54 }
55 
56 /**
57  *  tcp_write_err() - close socket and save error info
58  *  @sk:  The socket the error has appeared on.
59  *
60  *  Returns: Nothing (void)
61  */
62 
63 static void tcp_write_err(struct sock *sk)
64 {
65 	sk->sk_err = sk->sk_err_soft ? : ETIMEDOUT;
66 	sk->sk_error_report(sk);
67 
68 	tcp_write_queue_purge(sk);
69 	tcp_done(sk);
70 	__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONTIMEOUT);
71 }
72 
73 /**
74  *  tcp_out_of_resources() - Close socket if out of resources
75  *  @sk:        pointer to current socket
76  *  @do_reset:  send a last packet with reset flag
77  *
78  *  Do not allow orphaned sockets to eat all our resources.
79  *  This is direct violation of TCP specs, but it is required
80  *  to prevent DoS attacks. It is called when a retransmission timeout
81  *  or zero probe timeout occurs on orphaned socket.
82  *
83  *  Also close if our net namespace is exiting; in that case there is no
84  *  hope of ever communicating again since all netns interfaces are already
85  *  down (or about to be down), and we need to release our dst references,
86  *  which have been moved to the netns loopback interface, so the namespace
87  *  can finish exiting.  This condition is only possible if we are a kernel
88  *  socket, as those do not hold references to the namespace.
89  *
90  *  Criteria is still not confirmed experimentally and may change.
91  *  We kill the socket, if:
92  *  1. If number of orphaned sockets exceeds an administratively configured
93  *     limit.
94  *  2. If we have strong memory pressure.
95  *  3. If our net namespace is exiting.
96  */
97 static int tcp_out_of_resources(struct sock *sk, bool do_reset)
98 {
99 	struct tcp_sock *tp = tcp_sk(sk);
100 	int shift = 0;
101 
102 	/* If peer does not open window for long time, or did not transmit
103 	 * anything for long time, penalize it. */
104 	if ((s32)(tcp_jiffies32 - tp->lsndtime) > 2*TCP_RTO_MAX || !do_reset)
105 		shift++;
106 
107 	/* If some dubious ICMP arrived, penalize even more. */
108 	if (sk->sk_err_soft)
109 		shift++;
110 
111 	if (tcp_check_oom(sk, shift)) {
112 		/* Catch exceptional cases, when connection requires reset.
113 		 *      1. Last segment was sent recently. */
114 		if ((s32)(tcp_jiffies32 - tp->lsndtime) <= TCP_TIMEWAIT_LEN ||
115 		    /*  2. Window is closed. */
116 		    (!tp->snd_wnd && !tp->packets_out))
117 			do_reset = true;
118 		if (do_reset)
119 			tcp_send_active_reset(sk, GFP_ATOMIC);
120 		tcp_done(sk);
121 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONMEMORY);
122 		return 1;
123 	}
124 
125 	if (!check_net(sock_net(sk))) {
126 		/* Not possible to send reset; just close */
127 		tcp_done(sk);
128 		return 1;
129 	}
130 
131 	return 0;
132 }
133 
134 /**
135  *  tcp_orphan_retries() - Returns maximal number of retries on an orphaned socket
136  *  @sk:    Pointer to the current socket.
137  *  @alive: bool, socket alive state
138  */
139 static int tcp_orphan_retries(struct sock *sk, bool alive)
140 {
141 	int retries = sock_net(sk)->ipv4.sysctl_tcp_orphan_retries; /* May be zero. */
142 
143 	/* We know from an ICMP that something is wrong. */
144 	if (sk->sk_err_soft && !alive)
145 		retries = 0;
146 
147 	/* However, if socket sent something recently, select some safe
148 	 * number of retries. 8 corresponds to >100 seconds with minimal
149 	 * RTO of 200msec. */
150 	if (retries == 0 && alive)
151 		retries = 8;
152 	return retries;
153 }
154 
155 static void tcp_mtu_probing(struct inet_connection_sock *icsk, struct sock *sk)
156 {
157 	const struct net *net = sock_net(sk);
158 	int mss;
159 
160 	/* Black hole detection */
161 	if (!net->ipv4.sysctl_tcp_mtu_probing)
162 		return;
163 
164 	if (!icsk->icsk_mtup.enabled) {
165 		icsk->icsk_mtup.enabled = 1;
166 		icsk->icsk_mtup.probe_timestamp = tcp_jiffies32;
167 	} else {
168 		mss = tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low) >> 1;
169 		mss = min(net->ipv4.sysctl_tcp_base_mss, mss);
170 		mss = max(mss, 68 - tcp_sk(sk)->tcp_header_len);
171 		icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, mss);
172 	}
173 	tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
174 }
175 
176 
177 /**
178  *  retransmits_timed_out() - returns true if this connection has timed out
179  *  @sk:       The current socket
180  *  @boundary: max number of retransmissions
181  *  @timeout:  A custom timeout value.
182  *             If set to 0 the default timeout is calculated and used.
183  *             Using TCP_RTO_MIN and the number of unsuccessful retransmits.
184  *
185  * The default "timeout" value this function can calculate and use
186  * is equivalent to the timeout of a TCP Connection
187  * after "boundary" unsuccessful, exponentially backed-off
188  * retransmissions with an initial RTO of TCP_RTO_MIN.
189  */
190 static bool retransmits_timed_out(struct sock *sk,
191 				  unsigned int boundary,
192 				  unsigned int timeout)
193 {
194 	const unsigned int rto_base = TCP_RTO_MIN;
195 	unsigned int linear_backoff_thresh, start_ts;
196 
197 	if (!inet_csk(sk)->icsk_retransmits)
198 		return false;
199 
200 	start_ts = tcp_retransmit_stamp(sk);
201 	if (!start_ts)
202 		return false;
203 
204 	if (likely(timeout == 0)) {
205 		linear_backoff_thresh = ilog2(TCP_RTO_MAX/rto_base);
206 
207 		if (boundary <= linear_backoff_thresh)
208 			timeout = ((2 << boundary) - 1) * rto_base;
209 		else
210 			timeout = ((2 << linear_backoff_thresh) - 1) * rto_base +
211 				(boundary - linear_backoff_thresh) * TCP_RTO_MAX;
212 		timeout = jiffies_to_msecs(timeout);
213 	}
214 	return (s32)(tcp_time_stamp(tcp_sk(sk)) - start_ts - timeout) >= 0;
215 }
216 
217 /* A write timeout has occurred. Process the after effects. */
218 static int tcp_write_timeout(struct sock *sk)
219 {
220 	struct inet_connection_sock *icsk = inet_csk(sk);
221 	struct tcp_sock *tp = tcp_sk(sk);
222 	struct net *net = sock_net(sk);
223 	bool expired, do_reset;
224 	int retry_until;
225 
226 	if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
227 		if (icsk->icsk_retransmits) {
228 			dst_negative_advice(sk);
229 		} else if (!tp->syn_data && !tp->syn_fastopen) {
230 			sk_rethink_txhash(sk);
231 		}
232 		retry_until = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_syn_retries;
233 		expired = icsk->icsk_retransmits >= retry_until;
234 	} else {
235 		if (retransmits_timed_out(sk, net->ipv4.sysctl_tcp_retries1, 0)) {
236 			/* Black hole detection */
237 			tcp_mtu_probing(icsk, sk);
238 
239 			dst_negative_advice(sk);
240 		} else {
241 			sk_rethink_txhash(sk);
242 		}
243 
244 		retry_until = net->ipv4.sysctl_tcp_retries2;
245 		if (sock_flag(sk, SOCK_DEAD)) {
246 			const bool alive = icsk->icsk_rto < TCP_RTO_MAX;
247 
248 			retry_until = tcp_orphan_retries(sk, alive);
249 			do_reset = alive ||
250 				!retransmits_timed_out(sk, retry_until, 0);
251 
252 			if (tcp_out_of_resources(sk, do_reset))
253 				return 1;
254 		}
255 		expired = retransmits_timed_out(sk, retry_until,
256 						icsk->icsk_user_timeout);
257 	}
258 	tcp_fastopen_active_detect_blackhole(sk, expired);
259 
260 	if (BPF_SOCK_OPS_TEST_FLAG(tp, BPF_SOCK_OPS_RTO_CB_FLAG))
261 		tcp_call_bpf_3arg(sk, BPF_SOCK_OPS_RTO_CB,
262 				  icsk->icsk_retransmits,
263 				  icsk->icsk_rto, (int)expired);
264 
265 	if (expired) {
266 		/* Has it gone just too far? */
267 		tcp_write_err(sk);
268 		return 1;
269 	}
270 
271 	return 0;
272 }
273 
274 /* Called with BH disabled */
275 void tcp_delack_timer_handler(struct sock *sk)
276 {
277 	struct inet_connection_sock *icsk = inet_csk(sk);
278 
279 	sk_mem_reclaim_partial(sk);
280 
281 	if (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) ||
282 	    !(icsk->icsk_ack.pending & ICSK_ACK_TIMER))
283 		goto out;
284 
285 	if (time_after(icsk->icsk_ack.timeout, jiffies)) {
286 		sk_reset_timer(sk, &icsk->icsk_delack_timer, icsk->icsk_ack.timeout);
287 		goto out;
288 	}
289 	icsk->icsk_ack.pending &= ~ICSK_ACK_TIMER;
290 
291 	if (inet_csk_ack_scheduled(sk)) {
292 		if (!icsk->icsk_ack.pingpong) {
293 			/* Delayed ACK missed: inflate ATO. */
294 			icsk->icsk_ack.ato = min(icsk->icsk_ack.ato << 1, icsk->icsk_rto);
295 		} else {
296 			/* Delayed ACK missed: leave pingpong mode and
297 			 * deflate ATO.
298 			 */
299 			icsk->icsk_ack.pingpong = 0;
300 			icsk->icsk_ack.ato      = TCP_ATO_MIN;
301 		}
302 		tcp_mstamp_refresh(tcp_sk(sk));
303 		tcp_send_ack(sk);
304 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKS);
305 	}
306 
307 out:
308 	if (tcp_under_memory_pressure(sk))
309 		sk_mem_reclaim(sk);
310 }
311 
312 
313 /**
314  *  tcp_delack_timer() - The TCP delayed ACK timeout handler
315  *  @data:  Pointer to the current socket. (gets casted to struct sock *)
316  *
317  *  This function gets (indirectly) called when the kernel timer for a TCP packet
318  *  of this socket expires. Calls tcp_delack_timer_handler() to do the actual work.
319  *
320  *  Returns: Nothing (void)
321  */
322 static void tcp_delack_timer(struct timer_list *t)
323 {
324 	struct inet_connection_sock *icsk =
325 			from_timer(icsk, t, icsk_delack_timer);
326 	struct sock *sk = &icsk->icsk_inet.sk;
327 
328 	bh_lock_sock(sk);
329 	if (!sock_owned_by_user(sk)) {
330 		tcp_delack_timer_handler(sk);
331 	} else {
332 		icsk->icsk_ack.blocked = 1;
333 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOCKED);
334 		/* deleguate our work to tcp_release_cb() */
335 		if (!test_and_set_bit(TCP_DELACK_TIMER_DEFERRED, &sk->sk_tsq_flags))
336 			sock_hold(sk);
337 	}
338 	bh_unlock_sock(sk);
339 	sock_put(sk);
340 }
341 
342 static void tcp_probe_timer(struct sock *sk)
343 {
344 	struct inet_connection_sock *icsk = inet_csk(sk);
345 	struct sk_buff *skb = tcp_send_head(sk);
346 	struct tcp_sock *tp = tcp_sk(sk);
347 	int max_probes;
348 	u32 start_ts;
349 
350 	if (tp->packets_out || !skb) {
351 		icsk->icsk_probes_out = 0;
352 		return;
353 	}
354 
355 	/* RFC 1122 4.2.2.17 requires the sender to stay open indefinitely as
356 	 * long as the receiver continues to respond probes. We support this by
357 	 * default and reset icsk_probes_out with incoming ACKs. But if the
358 	 * socket is orphaned or the user specifies TCP_USER_TIMEOUT, we
359 	 * kill the socket when the retry count and the time exceeds the
360 	 * corresponding system limit. We also implement similar policy when
361 	 * we use RTO to probe window in tcp_retransmit_timer().
362 	 */
363 	start_ts = tcp_skb_timestamp(skb);
364 	if (!start_ts)
365 		skb->skb_mstamp_ns = tp->tcp_clock_cache;
366 	else if (icsk->icsk_user_timeout &&
367 		 (s32)(tcp_time_stamp(tp) - start_ts) > icsk->icsk_user_timeout)
368 		goto abort;
369 
370 	max_probes = sock_net(sk)->ipv4.sysctl_tcp_retries2;
371 	if (sock_flag(sk, SOCK_DEAD)) {
372 		const bool alive = inet_csk_rto_backoff(icsk, TCP_RTO_MAX) < TCP_RTO_MAX;
373 
374 		max_probes = tcp_orphan_retries(sk, alive);
375 		if (!alive && icsk->icsk_backoff >= max_probes)
376 			goto abort;
377 		if (tcp_out_of_resources(sk, true))
378 			return;
379 	}
380 
381 	if (icsk->icsk_probes_out >= max_probes) {
382 abort:		tcp_write_err(sk);
383 	} else {
384 		/* Only send another probe if we didn't close things up. */
385 		tcp_send_probe0(sk);
386 	}
387 }
388 
389 /*
390  *	Timer for Fast Open socket to retransmit SYNACK. Note that the
391  *	sk here is the child socket, not the parent (listener) socket.
392  */
393 static void tcp_fastopen_synack_timer(struct sock *sk)
394 {
395 	struct inet_connection_sock *icsk = inet_csk(sk);
396 	int max_retries = icsk->icsk_syn_retries ? :
397 	    sock_net(sk)->ipv4.sysctl_tcp_synack_retries + 1; /* add one more retry for fastopen */
398 	struct request_sock *req;
399 
400 	req = tcp_sk(sk)->fastopen_rsk;
401 	req->rsk_ops->syn_ack_timeout(req);
402 
403 	if (req->num_timeout >= max_retries) {
404 		tcp_write_err(sk);
405 		return;
406 	}
407 	/* XXX (TFO) - Unlike regular SYN-ACK retransmit, we ignore error
408 	 * returned from rtx_syn_ack() to make it more persistent like
409 	 * regular retransmit because if the child socket has been accepted
410 	 * it's not good to give up too easily.
411 	 */
412 	inet_rtx_syn_ack(sk, req);
413 	req->num_timeout++;
414 	icsk->icsk_retransmits++;
415 	inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
416 			  TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
417 }
418 
419 
420 /**
421  *  tcp_retransmit_timer() - The TCP retransmit timeout handler
422  *  @sk:  Pointer to the current socket.
423  *
424  *  This function gets called when the kernel timer for a TCP packet
425  *  of this socket expires.
426  *
427  *  It handles retransmission, timer adjustment and other necesarry measures.
428  *
429  *  Returns: Nothing (void)
430  */
431 void tcp_retransmit_timer(struct sock *sk)
432 {
433 	struct tcp_sock *tp = tcp_sk(sk);
434 	struct net *net = sock_net(sk);
435 	struct inet_connection_sock *icsk = inet_csk(sk);
436 
437 	if (tp->fastopen_rsk) {
438 		WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
439 			     sk->sk_state != TCP_FIN_WAIT1);
440 		tcp_fastopen_synack_timer(sk);
441 		/* Before we receive ACK to our SYN-ACK don't retransmit
442 		 * anything else (e.g., data or FIN segments).
443 		 */
444 		return;
445 	}
446 	if (!tp->packets_out)
447 		goto out;
448 
449 	WARN_ON(tcp_rtx_queue_empty(sk));
450 
451 	tp->tlp_high_seq = 0;
452 
453 	if (!tp->snd_wnd && !sock_flag(sk, SOCK_DEAD) &&
454 	    !((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))) {
455 		/* Receiver dastardly shrinks window. Our retransmits
456 		 * become zero probes, but we should not timeout this
457 		 * connection. If the socket is an orphan, time it out,
458 		 * we cannot allow such beasts to hang infinitely.
459 		 */
460 		struct inet_sock *inet = inet_sk(sk);
461 		if (sk->sk_family == AF_INET) {
462 			net_dbg_ratelimited("Peer %pI4:%u/%u unexpectedly shrunk window %u:%u (repaired)\n",
463 					    &inet->inet_daddr,
464 					    ntohs(inet->inet_dport),
465 					    inet->inet_num,
466 					    tp->snd_una, tp->snd_nxt);
467 		}
468 #if IS_ENABLED(CONFIG_IPV6)
469 		else if (sk->sk_family == AF_INET6) {
470 			net_dbg_ratelimited("Peer %pI6:%u/%u unexpectedly shrunk window %u:%u (repaired)\n",
471 					    &sk->sk_v6_daddr,
472 					    ntohs(inet->inet_dport),
473 					    inet->inet_num,
474 					    tp->snd_una, tp->snd_nxt);
475 		}
476 #endif
477 		if (tcp_jiffies32 - tp->rcv_tstamp > TCP_RTO_MAX) {
478 			tcp_write_err(sk);
479 			goto out;
480 		}
481 		tcp_enter_loss(sk);
482 		tcp_retransmit_skb(sk, tcp_rtx_queue_head(sk), 1);
483 		__sk_dst_reset(sk);
484 		goto out_reset_timer;
485 	}
486 
487 	__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPTIMEOUTS);
488 	if (tcp_write_timeout(sk))
489 		goto out;
490 
491 	if (icsk->icsk_retransmits == 0) {
492 		int mib_idx = 0;
493 
494 		if (icsk->icsk_ca_state == TCP_CA_Recovery) {
495 			if (tcp_is_sack(tp))
496 				mib_idx = LINUX_MIB_TCPSACKRECOVERYFAIL;
497 			else
498 				mib_idx = LINUX_MIB_TCPRENORECOVERYFAIL;
499 		} else if (icsk->icsk_ca_state == TCP_CA_Loss) {
500 			mib_idx = LINUX_MIB_TCPLOSSFAILURES;
501 		} else if ((icsk->icsk_ca_state == TCP_CA_Disorder) ||
502 			   tp->sacked_out) {
503 			if (tcp_is_sack(tp))
504 				mib_idx = LINUX_MIB_TCPSACKFAILURES;
505 			else
506 				mib_idx = LINUX_MIB_TCPRENOFAILURES;
507 		}
508 		if (mib_idx)
509 			__NET_INC_STATS(sock_net(sk), mib_idx);
510 	}
511 
512 	tcp_enter_loss(sk);
513 
514 	if (tcp_retransmit_skb(sk, tcp_rtx_queue_head(sk), 1) > 0) {
515 		/* Retransmission failed because of local congestion,
516 		 * do not backoff.
517 		 */
518 		if (!icsk->icsk_retransmits)
519 			icsk->icsk_retransmits = 1;
520 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
521 					  min(icsk->icsk_rto, TCP_RESOURCE_PROBE_INTERVAL),
522 					  TCP_RTO_MAX);
523 		goto out;
524 	}
525 
526 	/* Increase the timeout each time we retransmit.  Note that
527 	 * we do not increase the rtt estimate.  rto is initialized
528 	 * from rtt, but increases here.  Jacobson (SIGCOMM 88) suggests
529 	 * that doubling rto each time is the least we can get away with.
530 	 * In KA9Q, Karn uses this for the first few times, and then
531 	 * goes to quadratic.  netBSD doubles, but only goes up to *64,
532 	 * and clamps at 1 to 64 sec afterwards.  Note that 120 sec is
533 	 * defined in the protocol as the maximum possible RTT.  I guess
534 	 * we'll have to use something other than TCP to talk to the
535 	 * University of Mars.
536 	 *
537 	 * PAWS allows us longer timeouts and large windows, so once
538 	 * implemented ftp to mars will work nicely. We will have to fix
539 	 * the 120 second clamps though!
540 	 */
541 	icsk->icsk_backoff++;
542 	icsk->icsk_retransmits++;
543 
544 out_reset_timer:
545 	/* If stream is thin, use linear timeouts. Since 'icsk_backoff' is
546 	 * used to reset timer, set to 0. Recalculate 'icsk_rto' as this
547 	 * might be increased if the stream oscillates between thin and thick,
548 	 * thus the old value might already be too high compared to the value
549 	 * set by 'tcp_set_rto' in tcp_input.c which resets the rto without
550 	 * backoff. Limit to TCP_THIN_LINEAR_RETRIES before initiating
551 	 * exponential backoff behaviour to avoid continue hammering
552 	 * linear-timeout retransmissions into a black hole
553 	 */
554 	if (sk->sk_state == TCP_ESTABLISHED &&
555 	    (tp->thin_lto || net->ipv4.sysctl_tcp_thin_linear_timeouts) &&
556 	    tcp_stream_is_thin(tp) &&
557 	    icsk->icsk_retransmits <= TCP_THIN_LINEAR_RETRIES) {
558 		icsk->icsk_backoff = 0;
559 		icsk->icsk_rto = min(__tcp_set_rto(tp), TCP_RTO_MAX);
560 	} else {
561 		/* Use normal (exponential) backoff */
562 		icsk->icsk_rto = min(icsk->icsk_rto << 1, TCP_RTO_MAX);
563 	}
564 	inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
565 				  tcp_clamp_rto_to_user_timeout(sk), TCP_RTO_MAX);
566 	if (retransmits_timed_out(sk, net->ipv4.sysctl_tcp_retries1 + 1, 0))
567 		__sk_dst_reset(sk);
568 
569 out:;
570 }
571 
572 /* Called with bottom-half processing disabled.
573    Called by tcp_write_timer() */
574 void tcp_write_timer_handler(struct sock *sk)
575 {
576 	struct inet_connection_sock *icsk = inet_csk(sk);
577 	int event;
578 
579 	if (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) ||
580 	    !icsk->icsk_pending)
581 		goto out;
582 
583 	if (time_after(icsk->icsk_timeout, jiffies)) {
584 		sk_reset_timer(sk, &icsk->icsk_retransmit_timer, icsk->icsk_timeout);
585 		goto out;
586 	}
587 
588 	tcp_mstamp_refresh(tcp_sk(sk));
589 	event = icsk->icsk_pending;
590 
591 	switch (event) {
592 	case ICSK_TIME_REO_TIMEOUT:
593 		tcp_rack_reo_timeout(sk);
594 		break;
595 	case ICSK_TIME_LOSS_PROBE:
596 		tcp_send_loss_probe(sk);
597 		break;
598 	case ICSK_TIME_RETRANS:
599 		icsk->icsk_pending = 0;
600 		tcp_retransmit_timer(sk);
601 		break;
602 	case ICSK_TIME_PROBE0:
603 		icsk->icsk_pending = 0;
604 		tcp_probe_timer(sk);
605 		break;
606 	}
607 
608 out:
609 	sk_mem_reclaim(sk);
610 }
611 
612 static void tcp_write_timer(struct timer_list *t)
613 {
614 	struct inet_connection_sock *icsk =
615 			from_timer(icsk, t, icsk_retransmit_timer);
616 	struct sock *sk = &icsk->icsk_inet.sk;
617 
618 	bh_lock_sock(sk);
619 	if (!sock_owned_by_user(sk)) {
620 		tcp_write_timer_handler(sk);
621 	} else {
622 		/* delegate our work to tcp_release_cb() */
623 		if (!test_and_set_bit(TCP_WRITE_TIMER_DEFERRED, &sk->sk_tsq_flags))
624 			sock_hold(sk);
625 	}
626 	bh_unlock_sock(sk);
627 	sock_put(sk);
628 }
629 
630 void tcp_syn_ack_timeout(const struct request_sock *req)
631 {
632 	struct net *net = read_pnet(&inet_rsk(req)->ireq_net);
633 
634 	__NET_INC_STATS(net, LINUX_MIB_TCPTIMEOUTS);
635 }
636 EXPORT_SYMBOL(tcp_syn_ack_timeout);
637 
638 void tcp_set_keepalive(struct sock *sk, int val)
639 {
640 	if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))
641 		return;
642 
643 	if (val && !sock_flag(sk, SOCK_KEEPOPEN))
644 		inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tcp_sk(sk)));
645 	else if (!val)
646 		inet_csk_delete_keepalive_timer(sk);
647 }
648 EXPORT_SYMBOL_GPL(tcp_set_keepalive);
649 
650 
651 static void tcp_keepalive_timer (struct timer_list *t)
652 {
653 	struct sock *sk = from_timer(sk, t, sk_timer);
654 	struct inet_connection_sock *icsk = inet_csk(sk);
655 	struct tcp_sock *tp = tcp_sk(sk);
656 	u32 elapsed;
657 
658 	/* Only process if socket is not in use. */
659 	bh_lock_sock(sk);
660 	if (sock_owned_by_user(sk)) {
661 		/* Try again later. */
662 		inet_csk_reset_keepalive_timer (sk, HZ/20);
663 		goto out;
664 	}
665 
666 	if (sk->sk_state == TCP_LISTEN) {
667 		pr_err("Hmm... keepalive on a LISTEN ???\n");
668 		goto out;
669 	}
670 
671 	tcp_mstamp_refresh(tp);
672 	if (sk->sk_state == TCP_FIN_WAIT2 && sock_flag(sk, SOCK_DEAD)) {
673 		if (tp->linger2 >= 0) {
674 			const int tmo = tcp_fin_time(sk) - TCP_TIMEWAIT_LEN;
675 
676 			if (tmo > 0) {
677 				tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
678 				goto out;
679 			}
680 		}
681 		tcp_send_active_reset(sk, GFP_ATOMIC);
682 		goto death;
683 	}
684 
685 	if (!sock_flag(sk, SOCK_KEEPOPEN) ||
686 	    ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)))
687 		goto out;
688 
689 	elapsed = keepalive_time_when(tp);
690 
691 	/* It is alive without keepalive 8) */
692 	if (tp->packets_out || !tcp_write_queue_empty(sk))
693 		goto resched;
694 
695 	elapsed = keepalive_time_elapsed(tp);
696 
697 	if (elapsed >= keepalive_time_when(tp)) {
698 		/* If the TCP_USER_TIMEOUT option is enabled, use that
699 		 * to determine when to timeout instead.
700 		 */
701 		if ((icsk->icsk_user_timeout != 0 &&
702 		    elapsed >= msecs_to_jiffies(icsk->icsk_user_timeout) &&
703 		    icsk->icsk_probes_out > 0) ||
704 		    (icsk->icsk_user_timeout == 0 &&
705 		    icsk->icsk_probes_out >= keepalive_probes(tp))) {
706 			tcp_send_active_reset(sk, GFP_ATOMIC);
707 			tcp_write_err(sk);
708 			goto out;
709 		}
710 		if (tcp_write_wakeup(sk, LINUX_MIB_TCPKEEPALIVE) <= 0) {
711 			icsk->icsk_probes_out++;
712 			elapsed = keepalive_intvl_when(tp);
713 		} else {
714 			/* If keepalive was lost due to local congestion,
715 			 * try harder.
716 			 */
717 			elapsed = TCP_RESOURCE_PROBE_INTERVAL;
718 		}
719 	} else {
720 		/* It is tp->rcv_tstamp + keepalive_time_when(tp) */
721 		elapsed = keepalive_time_when(tp) - elapsed;
722 	}
723 
724 	sk_mem_reclaim(sk);
725 
726 resched:
727 	inet_csk_reset_keepalive_timer (sk, elapsed);
728 	goto out;
729 
730 death:
731 	tcp_done(sk);
732 
733 out:
734 	bh_unlock_sock(sk);
735 	sock_put(sk);
736 }
737 
738 static enum hrtimer_restart tcp_compressed_ack_kick(struct hrtimer *timer)
739 {
740 	struct tcp_sock *tp = container_of(timer, struct tcp_sock, compressed_ack_timer);
741 	struct sock *sk = (struct sock *)tp;
742 
743 	bh_lock_sock(sk);
744 	if (!sock_owned_by_user(sk)) {
745 		if (tp->compressed_ack > TCP_FASTRETRANS_THRESH)
746 			tcp_send_ack(sk);
747 	} else {
748 		if (!test_and_set_bit(TCP_DELACK_TIMER_DEFERRED,
749 				      &sk->sk_tsq_flags))
750 			sock_hold(sk);
751 	}
752 	bh_unlock_sock(sk);
753 
754 	sock_put(sk);
755 
756 	return HRTIMER_NORESTART;
757 }
758 
759 void tcp_init_xmit_timers(struct sock *sk)
760 {
761 	inet_csk_init_xmit_timers(sk, &tcp_write_timer, &tcp_delack_timer,
762 				  &tcp_keepalive_timer);
763 	hrtimer_init(&tcp_sk(sk)->pacing_timer, CLOCK_MONOTONIC,
764 		     HRTIMER_MODE_ABS_PINNED_SOFT);
765 	tcp_sk(sk)->pacing_timer.function = tcp_pace_kick;
766 
767 	hrtimer_init(&tcp_sk(sk)->compressed_ack_timer, CLOCK_MONOTONIC,
768 		     HRTIMER_MODE_REL_PINNED_SOFT);
769 	tcp_sk(sk)->compressed_ack_timer.function = tcp_compressed_ack_kick;
770 }
771