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