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