• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 int sysctl_tcp_syn_retries __read_mostly = TCP_SYN_RETRIES;
26 int sysctl_tcp_synack_retries __read_mostly = TCP_SYNACK_RETRIES;
27 int sysctl_tcp_keepalive_time __read_mostly = TCP_KEEPALIVE_TIME;
28 int sysctl_tcp_keepalive_probes __read_mostly = TCP_KEEPALIVE_PROBES;
29 int sysctl_tcp_keepalive_intvl __read_mostly = TCP_KEEPALIVE_INTVL;
30 int sysctl_tcp_retries1 __read_mostly = TCP_RETR1;
31 int sysctl_tcp_retries2 __read_mostly = TCP_RETR2;
32 int sysctl_tcp_orphan_retries __read_mostly;
33 int sysctl_tcp_thin_linear_timeouts __read_mostly;
34 
tcp_write_err(struct sock * sk)35 static void tcp_write_err(struct sock *sk)
36 {
37 	sk->sk_err = sk->sk_err_soft ? : ETIMEDOUT;
38 	sk->sk_error_report(sk);
39 
40 	tcp_done(sk);
41 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONTIMEOUT);
42 }
43 
44 /* Do not allow orphaned sockets to eat all our resources.
45  * This is direct violation of TCP specs, but it is required
46  * to prevent DoS attacks. It is called when a retransmission timeout
47  * or zero probe timeout occurs on orphaned socket.
48  *
49  * Also close if our net namespace is exiting; in that case there is no
50  * hope of ever communicating again since all netns interfaces are already
51  * down (or about to be down), and we need to release our dst references,
52  * which have been moved to the netns loopback interface, so the namespace
53  * can finish exiting.  This condition is only possible if we are a kernel
54  * socket, as those do not hold references to the namespace.
55  *
56  * Criteria is still not confirmed experimentally and may change.
57  * We kill the socket, if:
58  * 1. If number of orphaned sockets exceeds an administratively configured
59  *    limit.
60  * 2. If we have strong memory pressure.
61  * 3. If our net namespace is exiting.
62  */
tcp_out_of_resources(struct sock * sk,bool do_reset)63 static int tcp_out_of_resources(struct sock *sk, bool do_reset)
64 {
65 	struct tcp_sock *tp = tcp_sk(sk);
66 	int shift = 0;
67 
68 	/* If peer does not open window for long time, or did not transmit
69 	 * anything for long time, penalize it. */
70 	if ((s32)(tcp_time_stamp - tp->lsndtime) > 2*TCP_RTO_MAX || !do_reset)
71 		shift++;
72 
73 	/* If some dubious ICMP arrived, penalize even more. */
74 	if (sk->sk_err_soft)
75 		shift++;
76 
77 	if (tcp_check_oom(sk, shift)) {
78 		/* Catch exceptional cases, when connection requires reset.
79 		 *      1. Last segment was sent recently. */
80 		if ((s32)(tcp_time_stamp - tp->lsndtime) <= TCP_TIMEWAIT_LEN ||
81 		    /*  2. Window is closed. */
82 		    (!tp->snd_wnd && !tp->packets_out))
83 			do_reset = true;
84 		if (do_reset)
85 			tcp_send_active_reset(sk, GFP_ATOMIC);
86 		tcp_done(sk);
87 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPABORTONMEMORY);
88 		return 1;
89 	}
90 
91 	if (!check_net(sock_net(sk))) {
92 		/* Not possible to send reset; just close */
93 		tcp_done(sk);
94 		return 1;
95 	}
96 
97 	return 0;
98 }
99 
100 /* Calculate maximal number or retries on an orphaned socket. */
tcp_orphan_retries(struct sock * sk,int alive)101 static int tcp_orphan_retries(struct sock *sk, int alive)
102 {
103 	int retries = sysctl_tcp_orphan_retries; /* May be zero. */
104 
105 	/* We know from an ICMP that something is wrong. */
106 	if (sk->sk_err_soft && !alive)
107 		retries = 0;
108 
109 	/* However, if socket sent something recently, select some safe
110 	 * number of retries. 8 corresponds to >100 seconds with minimal
111 	 * RTO of 200msec. */
112 	if (retries == 0 && alive)
113 		retries = 8;
114 	return retries;
115 }
116 
tcp_mtu_probing(struct inet_connection_sock * icsk,struct sock * sk)117 static void tcp_mtu_probing(struct inet_connection_sock *icsk, struct sock *sk)
118 {
119 	/* Black hole detection */
120 	if (sysctl_tcp_mtu_probing) {
121 		if (!icsk->icsk_mtup.enabled) {
122 			icsk->icsk_mtup.enabled = 1;
123 			tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
124 		} else {
125 			struct tcp_sock *tp = tcp_sk(sk);
126 			int mss;
127 
128 			mss = tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low) >> 1;
129 			mss = min(sysctl_tcp_base_mss, mss);
130 			mss = max(mss, 68 - tp->tcp_header_len);
131 			icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, mss);
132 			tcp_sync_mss(sk, icsk->icsk_pmtu_cookie);
133 		}
134 	}
135 }
136 
137 /* This function calculates a "timeout" which is equivalent to the timeout of a
138  * TCP connection after "boundary" unsuccessful, exponentially backed-off
139  * retransmissions with an initial RTO of TCP_RTO_MIN or TCP_TIMEOUT_INIT if
140  * syn_set flag is set.
141  */
retransmits_timed_out(struct sock * sk,unsigned int boundary,unsigned int timeout,bool syn_set)142 static bool retransmits_timed_out(struct sock *sk,
143 				  unsigned int boundary,
144 				  unsigned int timeout,
145 				  bool syn_set)
146 {
147 	unsigned int linear_backoff_thresh, start_ts;
148 	unsigned int rto_base = syn_set ? TCP_TIMEOUT_INIT : TCP_RTO_MIN;
149 
150 	if (!inet_csk(sk)->icsk_retransmits)
151 		return false;
152 
153 	start_ts = tcp_sk(sk)->retrans_stamp;
154 	if (unlikely(!start_ts))
155 		start_ts = tcp_skb_timestamp(tcp_write_queue_head(sk));
156 
157 	if (likely(timeout == 0)) {
158 		linear_backoff_thresh = ilog2(TCP_RTO_MAX/rto_base);
159 
160 		if (boundary <= linear_backoff_thresh)
161 			timeout = ((2 << boundary) - 1) * rto_base;
162 		else
163 			timeout = ((2 << linear_backoff_thresh) - 1) * rto_base +
164 				(boundary - linear_backoff_thresh) * TCP_RTO_MAX;
165 	}
166 	return (tcp_time_stamp - start_ts) >= timeout;
167 }
168 
169 /* A write timeout has occurred. Process the after effects. */
tcp_write_timeout(struct sock * sk)170 static int tcp_write_timeout(struct sock *sk)
171 {
172 	struct inet_connection_sock *icsk = inet_csk(sk);
173 	struct tcp_sock *tp = tcp_sk(sk);
174 	int retry_until;
175 	bool do_reset, syn_set = false;
176 
177 	if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
178 		if (icsk->icsk_retransmits) {
179 			dst_negative_advice(sk);
180 			if (tp->syn_fastopen || tp->syn_data)
181 				tcp_fastopen_cache_set(sk, 0, NULL, true);
182 			if (tp->syn_data)
183 				NET_INC_STATS_BH(sock_net(sk),
184 						 LINUX_MIB_TCPFASTOPENACTIVEFAIL);
185 		}
186 		retry_until = icsk->icsk_syn_retries ? : sysctl_tcp_syn_retries;
187 		syn_set = true;
188 	} else {
189 		if (retransmits_timed_out(sk, sysctl_tcp_retries1, 0, 0)) {
190 			/* Black hole detection */
191 			tcp_mtu_probing(icsk, sk);
192 
193 			dst_negative_advice(sk);
194 		}
195 
196 		retry_until = sysctl_tcp_retries2;
197 		if (sock_flag(sk, SOCK_DEAD)) {
198 			const int alive = icsk->icsk_rto < TCP_RTO_MAX;
199 
200 			retry_until = tcp_orphan_retries(sk, alive);
201 			do_reset = alive ||
202 				!retransmits_timed_out(sk, retry_until, 0, 0);
203 
204 			if (tcp_out_of_resources(sk, do_reset))
205 				return 1;
206 		}
207 	}
208 
209 	if (retransmits_timed_out(sk, retry_until,
210 				  syn_set ? 0 : icsk->icsk_user_timeout, syn_set)) {
211 		/* Has it gone just too far? */
212 		tcp_write_err(sk);
213 		return 1;
214 	}
215 	return 0;
216 }
217 
tcp_delack_timer_handler(struct sock * sk)218 void tcp_delack_timer_handler(struct sock *sk)
219 {
220 	struct tcp_sock *tp = tcp_sk(sk);
221 	struct inet_connection_sock *icsk = inet_csk(sk);
222 
223 	sk_mem_reclaim_partial(sk);
224 
225 	if (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) ||
226 	    !(icsk->icsk_ack.pending & ICSK_ACK_TIMER))
227 		goto out;
228 
229 	if (time_after(icsk->icsk_ack.timeout, jiffies)) {
230 		sk_reset_timer(sk, &icsk->icsk_delack_timer, icsk->icsk_ack.timeout);
231 		goto out;
232 	}
233 	icsk->icsk_ack.pending &= ~ICSK_ACK_TIMER;
234 
235 	if (!skb_queue_empty(&tp->ucopy.prequeue)) {
236 		struct sk_buff *skb;
237 
238 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSCHEDULERFAILED);
239 
240 		while ((skb = __skb_dequeue(&tp->ucopy.prequeue)) != NULL)
241 			sk_backlog_rcv(sk, skb);
242 
243 		tp->ucopy.memory = 0;
244 	}
245 
246 	if (inet_csk_ack_scheduled(sk)) {
247 		if (!icsk->icsk_ack.pingpong) {
248 			/* Delayed ACK missed: inflate ATO. */
249 			icsk->icsk_ack.ato = min(icsk->icsk_ack.ato << 1, icsk->icsk_rto);
250 		} else {
251 			/* Delayed ACK missed: leave pingpong mode and
252 			 * deflate ATO.
253 			 */
254 			icsk->icsk_ack.pingpong = 0;
255 			icsk->icsk_ack.ato      = TCP_ATO_MIN;
256 		}
257 		tcp_send_ack(sk);
258 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKS);
259 	}
260 
261 out:
262 	if (sk_under_memory_pressure(sk))
263 		sk_mem_reclaim(sk);
264 }
265 
tcp_delack_timer(unsigned long data)266 static void tcp_delack_timer(unsigned long data)
267 {
268 	struct sock *sk = (struct sock *)data;
269 
270 	bh_lock_sock(sk);
271 	if (!sock_owned_by_user(sk)) {
272 		tcp_delack_timer_handler(sk);
273 	} else {
274 		inet_csk(sk)->icsk_ack.blocked = 1;
275 		NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_DELAYEDACKLOCKED);
276 		/* deleguate our work to tcp_release_cb() */
277 		if (!test_and_set_bit(TCP_DELACK_TIMER_DEFERRED, &tcp_sk(sk)->tsq_flags))
278 			sock_hold(sk);
279 	}
280 	bh_unlock_sock(sk);
281 	sock_put(sk);
282 }
283 
tcp_probe_timer(struct sock * sk)284 static void tcp_probe_timer(struct sock *sk)
285 {
286 	struct inet_connection_sock *icsk = inet_csk(sk);
287 	struct tcp_sock *tp = tcp_sk(sk);
288 	int max_probes;
289 	u32 start_ts;
290 
291 	if (tp->packets_out || !tcp_send_head(sk)) {
292 		icsk->icsk_probes_out = 0;
293 		return;
294 	}
295 
296 	/* RFC 1122 4.2.2.17 requires the sender to stay open indefinitely as
297 	 * long as the receiver continues to respond probes. We support this by
298 	 * default and reset icsk_probes_out with incoming ACKs. But if the
299 	 * socket is orphaned or the user specifies TCP_USER_TIMEOUT, we
300 	 * kill the socket when the retry count and the time exceeds the
301 	 * corresponding system limit. We also implement similar policy when
302 	 * we use RTO to probe window in tcp_retransmit_timer().
303 	 */
304 	start_ts = tcp_skb_timestamp(tcp_send_head(sk));
305 	if (!start_ts)
306 		skb_mstamp_get(&tcp_send_head(sk)->skb_mstamp);
307 	else if (icsk->icsk_user_timeout &&
308 		 (s32)(tcp_time_stamp - start_ts) > icsk->icsk_user_timeout)
309 		goto abort;
310 
311 	max_probes = sysctl_tcp_retries2;
312 	if (sock_flag(sk, SOCK_DEAD)) {
313 		const int alive = inet_csk_rto_backoff(icsk, TCP_RTO_MAX) < TCP_RTO_MAX;
314 
315 		max_probes = tcp_orphan_retries(sk, alive);
316 		if (!alive && icsk->icsk_backoff >= max_probes)
317 			goto abort;
318 		if (tcp_out_of_resources(sk, true))
319 			return;
320 	}
321 
322 	if (icsk->icsk_probes_out > max_probes) {
323 abort:		tcp_write_err(sk);
324 	} else {
325 		/* Only send another probe if we didn't close things up. */
326 		tcp_send_probe0(sk);
327 	}
328 }
329 
330 /*
331  *	Timer for Fast Open socket to retransmit SYNACK. Note that the
332  *	sk here is the child socket, not the parent (listener) socket.
333  */
tcp_fastopen_synack_timer(struct sock * sk)334 static void tcp_fastopen_synack_timer(struct sock *sk)
335 {
336 	struct inet_connection_sock *icsk = inet_csk(sk);
337 	int max_retries = icsk->icsk_syn_retries ? :
338 	    sysctl_tcp_synack_retries + 1; /* add one more retry for fastopen */
339 	struct request_sock *req;
340 
341 	req = tcp_sk(sk)->fastopen_rsk;
342 	req->rsk_ops->syn_ack_timeout(sk, req);
343 
344 	if (req->num_timeout >= max_retries) {
345 		tcp_write_err(sk);
346 		return;
347 	}
348 	/* XXX (TFO) - Unlike regular SYN-ACK retransmit, we ignore error
349 	 * returned from rtx_syn_ack() to make it more persistent like
350 	 * regular retransmit because if the child socket has been accepted
351 	 * it's not good to give up too easily.
352 	 */
353 	inet_rtx_syn_ack(sk, req);
354 	req->num_timeout++;
355 	inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
356 			  TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
357 }
358 
359 /*
360  *	The TCP retransmit timer.
361  */
362 
tcp_retransmit_timer(struct sock * sk)363 void tcp_retransmit_timer(struct sock *sk)
364 {
365 	struct tcp_sock *tp = tcp_sk(sk);
366 	struct inet_connection_sock *icsk = inet_csk(sk);
367 
368 	if (tp->fastopen_rsk) {
369 		WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV &&
370 			     sk->sk_state != TCP_FIN_WAIT1);
371 		tcp_fastopen_synack_timer(sk);
372 		/* Before we receive ACK to our SYN-ACK don't retransmit
373 		 * anything else (e.g., data or FIN segments).
374 		 */
375 		return;
376 	}
377 	if (!tp->packets_out)
378 		goto out;
379 
380 	WARN_ON(tcp_write_queue_empty(sk));
381 
382 	tp->tlp_high_seq = 0;
383 
384 	if (!tp->snd_wnd && !sock_flag(sk, SOCK_DEAD) &&
385 	    !((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV))) {
386 		/* Receiver dastardly shrinks window. Our retransmits
387 		 * become zero probes, but we should not timeout this
388 		 * connection. If the socket is an orphan, time it out,
389 		 * we cannot allow such beasts to hang infinitely.
390 		 */
391 		struct inet_sock *inet = inet_sk(sk);
392 		if (sk->sk_family == AF_INET) {
393 			LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("Peer %pI4:%u/%u unexpectedly shrunk window %u:%u (repaired)\n"),
394 				       &inet->inet_daddr,
395 				       ntohs(inet->inet_dport), inet->inet_num,
396 				       tp->snd_una, tp->snd_nxt);
397 		}
398 #if IS_ENABLED(CONFIG_IPV6)
399 		else if (sk->sk_family == AF_INET6) {
400 			LIMIT_NETDEBUG(KERN_DEBUG pr_fmt("Peer %pI6:%u/%u unexpectedly shrunk window %u:%u (repaired)\n"),
401 				       &sk->sk_v6_daddr,
402 				       ntohs(inet->inet_dport), inet->inet_num,
403 				       tp->snd_una, tp->snd_nxt);
404 		}
405 #endif
406 		if (tcp_time_stamp - tp->rcv_tstamp > TCP_RTO_MAX) {
407 			tcp_write_err(sk);
408 			goto out;
409 		}
410 		tcp_enter_loss(sk);
411 		tcp_retransmit_skb(sk, tcp_write_queue_head(sk));
412 		__sk_dst_reset(sk);
413 		goto out_reset_timer;
414 	}
415 
416 	if (tcp_write_timeout(sk))
417 		goto out;
418 
419 	if (icsk->icsk_retransmits == 0) {
420 		int mib_idx;
421 
422 		if (icsk->icsk_ca_state == TCP_CA_Recovery) {
423 			if (tcp_is_sack(tp))
424 				mib_idx = LINUX_MIB_TCPSACKRECOVERYFAIL;
425 			else
426 				mib_idx = LINUX_MIB_TCPRENORECOVERYFAIL;
427 		} else if (icsk->icsk_ca_state == TCP_CA_Loss) {
428 			mib_idx = LINUX_MIB_TCPLOSSFAILURES;
429 		} else if ((icsk->icsk_ca_state == TCP_CA_Disorder) ||
430 			   tp->sacked_out) {
431 			if (tcp_is_sack(tp))
432 				mib_idx = LINUX_MIB_TCPSACKFAILURES;
433 			else
434 				mib_idx = LINUX_MIB_TCPRENOFAILURES;
435 		} else {
436 			mib_idx = LINUX_MIB_TCPTIMEOUTS;
437 		}
438 		NET_INC_STATS_BH(sock_net(sk), mib_idx);
439 	}
440 
441 	tcp_enter_loss(sk);
442 
443 	if (tcp_retransmit_skb(sk, tcp_write_queue_head(sk)) > 0) {
444 		/* Retransmission failed because of local congestion,
445 		 * do not backoff.
446 		 */
447 		if (!icsk->icsk_retransmits)
448 			icsk->icsk_retransmits = 1;
449 		inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS,
450 					  min(icsk->icsk_rto, TCP_RESOURCE_PROBE_INTERVAL),
451 					  TCP_RTO_MAX);
452 		goto out;
453 	}
454 
455 	/* Increase the timeout each time we retransmit.  Note that
456 	 * we do not increase the rtt estimate.  rto is initialized
457 	 * from rtt, but increases here.  Jacobson (SIGCOMM 88) suggests
458 	 * that doubling rto each time is the least we can get away with.
459 	 * In KA9Q, Karn uses this for the first few times, and then
460 	 * goes to quadratic.  netBSD doubles, but only goes up to *64,
461 	 * and clamps at 1 to 64 sec afterwards.  Note that 120 sec is
462 	 * defined in the protocol as the maximum possible RTT.  I guess
463 	 * we'll have to use something other than TCP to talk to the
464 	 * University of Mars.
465 	 *
466 	 * PAWS allows us longer timeouts and large windows, so once
467 	 * implemented ftp to mars will work nicely. We will have to fix
468 	 * the 120 second clamps though!
469 	 */
470 	icsk->icsk_backoff++;
471 	icsk->icsk_retransmits++;
472 
473 out_reset_timer:
474 	/* If stream is thin, use linear timeouts. Since 'icsk_backoff' is
475 	 * used to reset timer, set to 0. Recalculate 'icsk_rto' as this
476 	 * might be increased if the stream oscillates between thin and thick,
477 	 * thus the old value might already be too high compared to the value
478 	 * set by 'tcp_set_rto' in tcp_input.c which resets the rto without
479 	 * backoff. Limit to TCP_THIN_LINEAR_RETRIES before initiating
480 	 * exponential backoff behaviour to avoid continue hammering
481 	 * linear-timeout retransmissions into a black hole
482 	 */
483 	if (sk->sk_state == TCP_ESTABLISHED &&
484 	    (tp->thin_lto || sysctl_tcp_thin_linear_timeouts) &&
485 	    tcp_stream_is_thin(tp) &&
486 	    icsk->icsk_retransmits <= TCP_THIN_LINEAR_RETRIES) {
487 		icsk->icsk_backoff = 0;
488 		icsk->icsk_rto = min(__tcp_set_rto(tp), TCP_RTO_MAX);
489 	} else {
490 		/* Use normal (exponential) backoff */
491 		icsk->icsk_rto = min(icsk->icsk_rto << 1, TCP_RTO_MAX);
492 	}
493 	inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, icsk->icsk_rto, TCP_RTO_MAX);
494 	if (retransmits_timed_out(sk, sysctl_tcp_retries1 + 1, 0, 0))
495 		__sk_dst_reset(sk);
496 
497 out:;
498 }
499 
tcp_write_timer_handler(struct sock * sk)500 void tcp_write_timer_handler(struct sock *sk)
501 {
502 	struct inet_connection_sock *icsk = inet_csk(sk);
503 	int event;
504 
505 	if (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)) ||
506 	    !icsk->icsk_pending)
507 		goto out;
508 
509 	if (time_after(icsk->icsk_timeout, jiffies)) {
510 		sk_reset_timer(sk, &icsk->icsk_retransmit_timer, icsk->icsk_timeout);
511 		goto out;
512 	}
513 
514 	event = icsk->icsk_pending;
515 
516 	switch (event) {
517 	case ICSK_TIME_EARLY_RETRANS:
518 		tcp_resume_early_retransmit(sk);
519 		break;
520 	case ICSK_TIME_LOSS_PROBE:
521 		tcp_send_loss_probe(sk);
522 		break;
523 	case ICSK_TIME_RETRANS:
524 		icsk->icsk_pending = 0;
525 		tcp_retransmit_timer(sk);
526 		break;
527 	case ICSK_TIME_PROBE0:
528 		icsk->icsk_pending = 0;
529 		tcp_probe_timer(sk);
530 		break;
531 	}
532 
533 out:
534 	sk_mem_reclaim(sk);
535 }
536 
tcp_write_timer(unsigned long data)537 static void tcp_write_timer(unsigned long data)
538 {
539 	struct sock *sk = (struct sock *)data;
540 
541 	bh_lock_sock(sk);
542 	if (!sock_owned_by_user(sk)) {
543 		tcp_write_timer_handler(sk);
544 	} else {
545 		/* deleguate our work to tcp_release_cb() */
546 		if (!test_and_set_bit(TCP_WRITE_TIMER_DEFERRED, &tcp_sk(sk)->tsq_flags))
547 			sock_hold(sk);
548 	}
549 	bh_unlock_sock(sk);
550 	sock_put(sk);
551 }
552 
553 /*
554  *	Timer for listening sockets
555  */
556 
tcp_synack_timer(struct sock * sk)557 static void tcp_synack_timer(struct sock *sk)
558 {
559 	inet_csk_reqsk_queue_prune(sk, TCP_SYNQ_INTERVAL,
560 				   TCP_TIMEOUT_INIT, TCP_RTO_MAX);
561 }
562 
tcp_syn_ack_timeout(struct sock * sk,struct request_sock * req)563 void tcp_syn_ack_timeout(struct sock *sk, struct request_sock *req)
564 {
565 	NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPTIMEOUTS);
566 }
567 EXPORT_SYMBOL(tcp_syn_ack_timeout);
568 
tcp_set_keepalive(struct sock * sk,int val)569 void tcp_set_keepalive(struct sock *sk, int val)
570 {
571 	if ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN))
572 		return;
573 
574 	if (val && !sock_flag(sk, SOCK_KEEPOPEN))
575 		inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tcp_sk(sk)));
576 	else if (!val)
577 		inet_csk_delete_keepalive_timer(sk);
578 }
579 
580 
tcp_keepalive_timer(unsigned long data)581 static void tcp_keepalive_timer (unsigned long data)
582 {
583 	struct sock *sk = (struct sock *) data;
584 	struct inet_connection_sock *icsk = inet_csk(sk);
585 	struct tcp_sock *tp = tcp_sk(sk);
586 	u32 elapsed;
587 
588 	/* Only process if socket is not in use. */
589 	bh_lock_sock(sk);
590 	if (sock_owned_by_user(sk)) {
591 		/* Try again later. */
592 		inet_csk_reset_keepalive_timer (sk, HZ/20);
593 		goto out;
594 	}
595 
596 	if (sk->sk_state == TCP_LISTEN) {
597 		tcp_synack_timer(sk);
598 		goto out;
599 	}
600 
601 	if (sk->sk_state == TCP_FIN_WAIT2 && sock_flag(sk, SOCK_DEAD)) {
602 		if (tp->linger2 >= 0) {
603 			const int tmo = tcp_fin_time(sk) - TCP_TIMEWAIT_LEN;
604 
605 			if (tmo > 0) {
606 				tcp_time_wait(sk, TCP_FIN_WAIT2, tmo);
607 				goto out;
608 			}
609 		}
610 		tcp_send_active_reset(sk, GFP_ATOMIC);
611 		goto death;
612 	}
613 
614 	if (!sock_flag(sk, SOCK_KEEPOPEN) ||
615 	    ((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)))
616 		goto out;
617 
618 	elapsed = keepalive_time_when(tp);
619 
620 	/* It is alive without keepalive 8) */
621 	if (tp->packets_out || tcp_send_head(sk))
622 		goto resched;
623 
624 	elapsed = keepalive_time_elapsed(tp);
625 
626 	if (elapsed >= keepalive_time_when(tp)) {
627 		/* If the TCP_USER_TIMEOUT option is enabled, use that
628 		 * to determine when to timeout instead.
629 		 */
630 		if ((icsk->icsk_user_timeout != 0 &&
631 		    elapsed >= icsk->icsk_user_timeout &&
632 		    icsk->icsk_probes_out > 0) ||
633 		    (icsk->icsk_user_timeout == 0 &&
634 		    icsk->icsk_probes_out >= keepalive_probes(tp))) {
635 			tcp_send_active_reset(sk, GFP_ATOMIC);
636 			tcp_write_err(sk);
637 			goto out;
638 		}
639 		if (tcp_write_wakeup(sk) <= 0) {
640 			icsk->icsk_probes_out++;
641 			elapsed = keepalive_intvl_when(tp);
642 		} else {
643 			/* If keepalive was lost due to local congestion,
644 			 * try harder.
645 			 */
646 			elapsed = TCP_RESOURCE_PROBE_INTERVAL;
647 		}
648 	} else {
649 		/* It is tp->rcv_tstamp + keepalive_time_when(tp) */
650 		elapsed = keepalive_time_when(tp) - elapsed;
651 	}
652 
653 	sk_mem_reclaim(sk);
654 
655 resched:
656 	inet_csk_reset_keepalive_timer (sk, elapsed);
657 	goto out;
658 
659 death:
660 	tcp_done(sk);
661 
662 out:
663 	bh_unlock_sock(sk);
664 	sock_put(sk);
665 }
666 
tcp_init_xmit_timers(struct sock * sk)667 void tcp_init_xmit_timers(struct sock *sk)
668 {
669 	inet_csk_init_xmit_timers(sk, &tcp_write_timer, &tcp_delack_timer,
670 				  &tcp_keepalive_timer);
671 }
672 EXPORT_SYMBOL(tcp_init_xmit_timers);
673