xref: /linux/net/ipv4/tcp_metrics.c (revision f16d85cd3de9d0c761b74155b4cbe2f20d3dcf80)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <linux/rcupdate.h>
3 #include <linux/spinlock.h>
4 #include <linux/jiffies.h>
5 #include <linux/module.h>
6 #include <linux/cache.h>
7 #include <linux/slab.h>
8 #include <linux/init.h>
9 #include <linux/tcp.h>
10 #include <linux/hash.h>
11 #include <linux/tcp_metrics.h>
12 #include <linux/vmalloc.h>
13 
14 #include <net/inet_connection_sock.h>
15 #include <net/net_namespace.h>
16 #include <net/request_sock.h>
17 #include <net/inetpeer.h>
18 #include <net/sock.h>
19 #include <net/ipv6.h>
20 #include <net/dst.h>
21 #include <net/tcp.h>
22 #include <net/genetlink.h>
23 
24 static struct tcp_metrics_block *__tcp_get_metrics(const struct inetpeer_addr *saddr,
25 						   const struct inetpeer_addr *daddr,
26 						   struct net *net, unsigned int hash);
27 
28 struct tcp_fastopen_metrics {
29 	u16	mss;
30 	u16	syn_loss:10,		/* Recurring Fast Open SYN losses */
31 		try_exp:2;		/* Request w/ exp. option (once) */
32 	unsigned long	last_syn_loss;	/* Last Fast Open SYN loss */
33 	struct	tcp_fastopen_cookie	cookie;
34 };
35 
36 /* TCP_METRIC_MAX includes 2 extra fields for userspace compatibility
37  * Kernel only stores RTT and RTTVAR in usec resolution
38  */
39 #define TCP_METRIC_MAX_KERNEL (TCP_METRIC_MAX - 2)
40 
41 struct tcp_metrics_block {
42 	struct tcp_metrics_block __rcu	*tcpm_next;
43 	struct net			*tcpm_net;
44 	struct inetpeer_addr		tcpm_saddr;
45 	struct inetpeer_addr		tcpm_daddr;
46 	unsigned long			tcpm_stamp;
47 	u32				tcpm_lock;
48 	u32				tcpm_vals[TCP_METRIC_MAX_KERNEL + 1];
49 	struct tcp_fastopen_metrics	tcpm_fastopen;
50 
51 	struct rcu_head			rcu_head;
52 };
53 
54 static inline struct net *tm_net(const struct tcp_metrics_block *tm)
55 {
56 	/* Paired with the WRITE_ONCE() in tcpm_new() */
57 	return READ_ONCE(tm->tcpm_net);
58 }
59 
60 static bool tcp_metric_locked(struct tcp_metrics_block *tm,
61 			      enum tcp_metric_index idx)
62 {
63 	/* Paired with WRITE_ONCE() in tcpm_suck_dst() */
64 	return READ_ONCE(tm->tcpm_lock) & (1 << idx);
65 }
66 
67 static u32 tcp_metric_get(const struct tcp_metrics_block *tm,
68 			  enum tcp_metric_index idx)
69 {
70 	/* Paired with WRITE_ONCE() in tcp_metric_set() */
71 	return READ_ONCE(tm->tcpm_vals[idx]);
72 }
73 
74 static void tcp_metric_set(struct tcp_metrics_block *tm,
75 			   enum tcp_metric_index idx,
76 			   u32 val)
77 {
78 	/* Paired with READ_ONCE() in tcp_metric_get() */
79 	WRITE_ONCE(tm->tcpm_vals[idx], val);
80 }
81 
82 static bool addr_same(const struct inetpeer_addr *a,
83 		      const struct inetpeer_addr *b)
84 {
85 	return (a->family == b->family) && !inetpeer_addr_cmp(a, b);
86 }
87 
88 struct tcpm_hash_bucket {
89 	struct tcp_metrics_block __rcu	*chain;
90 };
91 
92 static struct tcpm_hash_bucket	*tcp_metrics_hash __read_mostly;
93 static unsigned int		tcp_metrics_hash_log __read_mostly;
94 
95 static DEFINE_SPINLOCK(tcp_metrics_lock);
96 static DEFINE_SEQLOCK(fastopen_seqlock);
97 
98 static void tcpm_suck_dst(struct tcp_metrics_block *tm,
99 			  const struct dst_entry *dst,
100 			  bool fastopen_clear)
101 {
102 	u32 msval;
103 	u32 val;
104 
105 	WRITE_ONCE(tm->tcpm_stamp, jiffies);
106 
107 	val = 0;
108 	if (dst_metric_locked(dst, RTAX_RTT))
109 		val |= 1 << TCP_METRIC_RTT;
110 	if (dst_metric_locked(dst, RTAX_RTTVAR))
111 		val |= 1 << TCP_METRIC_RTTVAR;
112 	if (dst_metric_locked(dst, RTAX_SSTHRESH))
113 		val |= 1 << TCP_METRIC_SSTHRESH;
114 	if (dst_metric_locked(dst, RTAX_CWND))
115 		val |= 1 << TCP_METRIC_CWND;
116 	if (dst_metric_locked(dst, RTAX_REORDERING))
117 		val |= 1 << TCP_METRIC_REORDERING;
118 	/* Paired with READ_ONCE() in tcp_metric_locked() */
119 	WRITE_ONCE(tm->tcpm_lock, val);
120 
121 	msval = dst_metric_raw(dst, RTAX_RTT);
122 	tcp_metric_set(tm, TCP_METRIC_RTT, msval * USEC_PER_MSEC);
123 
124 	msval = dst_metric_raw(dst, RTAX_RTTVAR);
125 	tcp_metric_set(tm, TCP_METRIC_RTTVAR, msval * USEC_PER_MSEC);
126 	tcp_metric_set(tm, TCP_METRIC_SSTHRESH,
127 		       dst_metric_raw(dst, RTAX_SSTHRESH));
128 	tcp_metric_set(tm, TCP_METRIC_CWND,
129 		       dst_metric_raw(dst, RTAX_CWND));
130 	tcp_metric_set(tm, TCP_METRIC_REORDERING,
131 		       dst_metric_raw(dst, RTAX_REORDERING));
132 	if (fastopen_clear) {
133 		write_seqlock(&fastopen_seqlock);
134 		tm->tcpm_fastopen.mss = 0;
135 		tm->tcpm_fastopen.syn_loss = 0;
136 		tm->tcpm_fastopen.try_exp = 0;
137 		tm->tcpm_fastopen.cookie.exp = false;
138 		tm->tcpm_fastopen.cookie.len = 0;
139 		write_sequnlock(&fastopen_seqlock);
140 	}
141 }
142 
143 #define TCP_METRICS_TIMEOUT		(60 * 60 * HZ)
144 
145 static void tcpm_check_stamp(struct tcp_metrics_block *tm,
146 			     const struct dst_entry *dst)
147 {
148 	unsigned long limit;
149 
150 	if (!tm)
151 		return;
152 	limit = READ_ONCE(tm->tcpm_stamp) + TCP_METRICS_TIMEOUT;
153 	if (unlikely(time_after(jiffies, limit)))
154 		tcpm_suck_dst(tm, dst, false);
155 }
156 
157 #define TCP_METRICS_RECLAIM_DEPTH	5
158 #define TCP_METRICS_RECLAIM_PTR		(struct tcp_metrics_block *) 0x1UL
159 
160 #define deref_locked(p)	\
161 	rcu_dereference_protected(p, lockdep_is_held(&tcp_metrics_lock))
162 
163 static struct tcp_metrics_block *tcpm_new(struct dst_entry *dst,
164 					  struct net *net,
165 					  struct inetpeer_addr *saddr,
166 					  struct inetpeer_addr *daddr,
167 					  unsigned int hash)
168 {
169 	struct tcp_metrics_block *tm;
170 	bool reclaim = false;
171 
172 	spin_lock_bh(&tcp_metrics_lock);
173 
174 	/* Do not add entries to a dismantling netns: they would not be
175 	 * flushed again. Callers are in an RCU read-side section, and
176 	 * cleanup_net() waits for a grace period after the netns refcount
177 	 * reached zero and before tcp_metrics_flush_all(NULL) runs, so an
178 	 * entry added after a successful check_net() is seen by the flush.
179 	 */
180 	if (unlikely(!check_net(net))) {
181 		tm = NULL;
182 		goto out_unlock;
183 	}
184 
185 	/* While waiting for the spin-lock the cache might have been populated
186 	 * with this entry and so we have to check again.
187 	 */
188 	tm = __tcp_get_metrics(saddr, daddr, net, hash);
189 	if (tm == TCP_METRICS_RECLAIM_PTR) {
190 		reclaim = true;
191 		tm = NULL;
192 	}
193 	if (tm) {
194 		tcpm_check_stamp(tm, dst);
195 		goto out_unlock;
196 	}
197 
198 	if (unlikely(reclaim)) {
199 		struct tcp_metrics_block *oldest;
200 
201 		oldest = deref_locked(tcp_metrics_hash[hash].chain);
202 		for (tm = deref_locked(oldest->tcpm_next); tm;
203 		     tm = deref_locked(tm->tcpm_next)) {
204 			if (time_before(READ_ONCE(tm->tcpm_stamp),
205 					READ_ONCE(oldest->tcpm_stamp)))
206 				oldest = tm;
207 		}
208 		tm = oldest;
209 	} else {
210 		tm = kzalloc_obj(*tm, GFP_ATOMIC);
211 		if (!tm)
212 			goto out_unlock;
213 	}
214 	/* Paired with the READ_ONCE() in tm_net() */
215 	WRITE_ONCE(tm->tcpm_net, net);
216 
217 	tm->tcpm_saddr = *saddr;
218 	tm->tcpm_daddr = *daddr;
219 
220 	tcpm_suck_dst(tm, dst, reclaim);
221 
222 	if (likely(!reclaim)) {
223 		tm->tcpm_next = tcp_metrics_hash[hash].chain;
224 		rcu_assign_pointer(tcp_metrics_hash[hash].chain, tm);
225 	}
226 
227 out_unlock:
228 	spin_unlock_bh(&tcp_metrics_lock);
229 	return tm;
230 }
231 
232 static struct tcp_metrics_block *tcp_get_encode(struct tcp_metrics_block *tm, int depth)
233 {
234 	if (tm)
235 		return tm;
236 	if (depth > TCP_METRICS_RECLAIM_DEPTH)
237 		return TCP_METRICS_RECLAIM_PTR;
238 	return NULL;
239 }
240 
241 static struct tcp_metrics_block *__tcp_get_metrics(const struct inetpeer_addr *saddr,
242 						   const struct inetpeer_addr *daddr,
243 						   struct net *net, unsigned int hash)
244 {
245 	struct tcp_metrics_block *tm;
246 	int depth = 0;
247 
248 	for (tm = rcu_dereference(tcp_metrics_hash[hash].chain); tm;
249 	     tm = rcu_dereference(tm->tcpm_next)) {
250 		if (addr_same(&tm->tcpm_saddr, saddr) &&
251 		    addr_same(&tm->tcpm_daddr, daddr) &&
252 		    net_eq(tm_net(tm), net))
253 			break;
254 		depth++;
255 	}
256 	return tcp_get_encode(tm, depth);
257 }
258 
259 static struct tcp_metrics_block *__tcp_get_metrics_req(struct request_sock *req,
260 						       struct dst_entry *dst)
261 {
262 	struct tcp_metrics_block *tm;
263 	struct inetpeer_addr saddr, daddr;
264 	unsigned int hash;
265 	struct net *net;
266 
267 	saddr.family = req->rsk_ops->family;
268 	daddr.family = req->rsk_ops->family;
269 	switch (daddr.family) {
270 	case AF_INET:
271 		inetpeer_set_addr_v4(&saddr, inet_rsk(req)->ir_loc_addr);
272 		inetpeer_set_addr_v4(&daddr, inet_rsk(req)->ir_rmt_addr);
273 		hash = ipv4_addr_hash(inet_rsk(req)->ir_rmt_addr);
274 		break;
275 #if IS_ENABLED(CONFIG_IPV6)
276 	case AF_INET6:
277 		inetpeer_set_addr_v6(&saddr, &inet_rsk(req)->ir_v6_loc_addr);
278 		inetpeer_set_addr_v6(&daddr, &inet_rsk(req)->ir_v6_rmt_addr);
279 		hash = ipv6_addr_hash(&inet_rsk(req)->ir_v6_rmt_addr);
280 		break;
281 #endif
282 	default:
283 		return NULL;
284 	}
285 
286 	net = sock_net(req_to_sk(req));
287 	hash ^= net_hash_mix(net);
288 	hash = hash_32(hash, tcp_metrics_hash_log);
289 
290 	for (tm = rcu_dereference(tcp_metrics_hash[hash].chain); tm;
291 	     tm = rcu_dereference(tm->tcpm_next)) {
292 		if (addr_same(&tm->tcpm_saddr, &saddr) &&
293 		    addr_same(&tm->tcpm_daddr, &daddr) &&
294 		    net_eq(tm_net(tm), net))
295 			break;
296 	}
297 	tcpm_check_stamp(tm, dst);
298 	return tm;
299 }
300 
301 static struct tcp_metrics_block *tcp_get_metrics(struct sock *sk,
302 						 struct dst_entry *dst,
303 						 bool create)
304 {
305 	struct tcp_metrics_block *tm;
306 	struct inetpeer_addr saddr, daddr;
307 	unsigned int hash;
308 	struct net *net;
309 
310 	if (sk->sk_family == AF_INET) {
311 		inetpeer_set_addr_v4(&saddr, inet_sk(sk)->inet_saddr);
312 		inetpeer_set_addr_v4(&daddr, inet_sk(sk)->inet_daddr);
313 		hash = ipv4_addr_hash(inet_sk(sk)->inet_daddr);
314 	}
315 #if IS_ENABLED(CONFIG_IPV6)
316 	else if (sk->sk_family == AF_INET6) {
317 		if (ipv6_addr_v4mapped(&sk->sk_v6_daddr)) {
318 			inetpeer_set_addr_v4(&saddr, inet_sk(sk)->inet_saddr);
319 			inetpeer_set_addr_v4(&daddr, inet_sk(sk)->inet_daddr);
320 			hash = ipv4_addr_hash(inet_sk(sk)->inet_daddr);
321 		} else {
322 			inetpeer_set_addr_v6(&saddr, &sk->sk_v6_rcv_saddr);
323 			inetpeer_set_addr_v6(&daddr, &sk->sk_v6_daddr);
324 			hash = ipv6_addr_hash(&sk->sk_v6_daddr);
325 		}
326 	}
327 #endif
328 	else
329 		return NULL;
330 
331 	net = sock_net(sk);
332 	hash ^= net_hash_mix(net);
333 	hash = hash_32(hash, tcp_metrics_hash_log);
334 
335 	tm = __tcp_get_metrics(&saddr, &daddr, net, hash);
336 	if (tm == TCP_METRICS_RECLAIM_PTR)
337 		tm = NULL;
338 	if (!tm && create)
339 		tm = tcpm_new(dst, net, &saddr, &daddr, hash);
340 	else
341 		tcpm_check_stamp(tm, dst);
342 
343 	return tm;
344 }
345 
346 /* Save metrics learned by this TCP session.  This function is called
347  * only, when TCP finishes successfully i.e. when it enters TIME-WAIT
348  * or goes from LAST-ACK to CLOSE.
349  */
350 void tcp_update_metrics(struct sock *sk)
351 {
352 	const struct inet_connection_sock *icsk = inet_csk(sk);
353 	struct dst_entry *dst = __sk_dst_get(sk);
354 	struct tcp_sock *tp = tcp_sk(sk);
355 	struct net *net = sock_net(sk);
356 	struct tcp_metrics_block *tm;
357 	unsigned long rtt;
358 	u32 val;
359 	int m;
360 
361 	sk_dst_confirm(sk);
362 	if (READ_ONCE(net->ipv4.sysctl_tcp_nometrics_save) || !dst)
363 		return;
364 
365 	rcu_read_lock();
366 	if (icsk->icsk_backoff || !tp->srtt_us) {
367 		/* This session failed to estimate rtt. Why?
368 		 * Probably, no packets returned in time.  Reset our
369 		 * results.
370 		 */
371 		tm = tcp_get_metrics(sk, dst, false);
372 		if (tm && !tcp_metric_locked(tm, TCP_METRIC_RTT))
373 			tcp_metric_set(tm, TCP_METRIC_RTT, 0);
374 		goto out_unlock;
375 	} else
376 		tm = tcp_get_metrics(sk, dst, true);
377 
378 	if (!tm)
379 		goto out_unlock;
380 
381 	rtt = tcp_metric_get(tm, TCP_METRIC_RTT);
382 	m = rtt - tp->srtt_us;
383 
384 	/* If newly calculated rtt larger than stored one, store new
385 	 * one. Otherwise, use EWMA. Remember, rtt overestimation is
386 	 * always better than underestimation.
387 	 */
388 	if (!tcp_metric_locked(tm, TCP_METRIC_RTT)) {
389 		if (m <= 0)
390 			rtt = tp->srtt_us;
391 		else
392 			rtt -= (m >> 3);
393 		tcp_metric_set(tm, TCP_METRIC_RTT, rtt);
394 	}
395 
396 	if (!tcp_metric_locked(tm, TCP_METRIC_RTTVAR)) {
397 		unsigned long var;
398 
399 		if (m < 0)
400 			m = -m;
401 
402 		/* Scale deviation to rttvar fixed point */
403 		m >>= 1;
404 		if (m < tp->mdev_us)
405 			m = tp->mdev_us;
406 
407 		var = tcp_metric_get(tm, TCP_METRIC_RTTVAR);
408 		if (m >= var)
409 			var = m;
410 		else
411 			var -= (var - m) >> 2;
412 
413 		tcp_metric_set(tm, TCP_METRIC_RTTVAR, var);
414 	}
415 
416 	if (tcp_in_initial_slowstart(tp)) {
417 		/* Slow start still did not finish. */
418 		if (!READ_ONCE(net->ipv4.sysctl_tcp_no_ssthresh_metrics_save) &&
419 		    !tcp_metric_locked(tm, TCP_METRIC_SSTHRESH)) {
420 			val = tcp_metric_get(tm, TCP_METRIC_SSTHRESH);
421 			if (val && (tcp_snd_cwnd(tp) >> 1) > val)
422 				tcp_metric_set(tm, TCP_METRIC_SSTHRESH,
423 					       tcp_snd_cwnd(tp) >> 1);
424 		}
425 		if (!tcp_metric_locked(tm, TCP_METRIC_CWND)) {
426 			val = tcp_metric_get(tm, TCP_METRIC_CWND);
427 			if (tcp_snd_cwnd(tp) > val)
428 				tcp_metric_set(tm, TCP_METRIC_CWND,
429 					       tcp_snd_cwnd(tp));
430 		}
431 	} else if (!tcp_in_slow_start(tp) &&
432 		   icsk->icsk_ca_state == TCP_CA_Open) {
433 		/* Cong. avoidance phase, cwnd is reliable. */
434 		if (!READ_ONCE(net->ipv4.sysctl_tcp_no_ssthresh_metrics_save) &&
435 		    !tcp_metric_locked(tm, TCP_METRIC_SSTHRESH))
436 			tcp_metric_set(tm, TCP_METRIC_SSTHRESH,
437 				       max(tcp_snd_cwnd(tp) >> 1, tp->snd_ssthresh));
438 		if (!tcp_metric_locked(tm, TCP_METRIC_CWND)) {
439 			val = tcp_metric_get(tm, TCP_METRIC_CWND);
440 			tcp_metric_set(tm, TCP_METRIC_CWND, (val + tcp_snd_cwnd(tp)) >> 1);
441 		}
442 	} else {
443 		/* Else slow start did not finish, cwnd is non-sense,
444 		 * ssthresh may be also invalid.
445 		 */
446 		if (!tcp_metric_locked(tm, TCP_METRIC_CWND)) {
447 			val = tcp_metric_get(tm, TCP_METRIC_CWND);
448 			tcp_metric_set(tm, TCP_METRIC_CWND,
449 				       (val + tp->snd_ssthresh) >> 1);
450 		}
451 		if (!READ_ONCE(net->ipv4.sysctl_tcp_no_ssthresh_metrics_save) &&
452 		    !tcp_metric_locked(tm, TCP_METRIC_SSTHRESH)) {
453 			val = tcp_metric_get(tm, TCP_METRIC_SSTHRESH);
454 			if (val && tp->snd_ssthresh > val)
455 				tcp_metric_set(tm, TCP_METRIC_SSTHRESH,
456 					       tp->snd_ssthresh);
457 		}
458 		if (!tcp_metric_locked(tm, TCP_METRIC_REORDERING)) {
459 			val = tcp_metric_get(tm, TCP_METRIC_REORDERING);
460 			if (val < tp->reordering &&
461 			    tp->reordering !=
462 			    READ_ONCE(net->ipv4.sysctl_tcp_reordering))
463 				tcp_metric_set(tm, TCP_METRIC_REORDERING,
464 					       tp->reordering);
465 		}
466 	}
467 	WRITE_ONCE(tm->tcpm_stamp, jiffies);
468 out_unlock:
469 	rcu_read_unlock();
470 }
471 
472 /* Initialize metrics on socket. */
473 
474 void tcp_init_metrics(struct sock *sk)
475 {
476 	struct dst_entry *dst = __sk_dst_get(sk);
477 	struct tcp_sock *tp = tcp_sk(sk);
478 	struct net *net = sock_net(sk);
479 	struct tcp_metrics_block *tm;
480 	u32 val, crtt = 0; /* cached RTT scaled by 8 */
481 
482 	sk_dst_confirm(sk);
483 	/* ssthresh may have been reduced unnecessarily during.
484 	 * 3WHS. Restore it back to its initial default.
485 	 */
486 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
487 	if (!dst)
488 		goto reset;
489 
490 	rcu_read_lock();
491 	tm = tcp_get_metrics(sk, dst, false);
492 	if (!tm) {
493 		rcu_read_unlock();
494 		goto reset;
495 	}
496 
497 	if (tcp_metric_locked(tm, TCP_METRIC_CWND))
498 		tp->snd_cwnd_clamp = min(tcp_metric_get(tm, TCP_METRIC_CWND),
499 					 TCP_MAX_SND_CWND);
500 
501 	val = READ_ONCE(net->ipv4.sysctl_tcp_no_ssthresh_metrics_save) ?
502 	      0 : tcp_metric_get(tm, TCP_METRIC_SSTHRESH);
503 	if (val) {
504 		WRITE_ONCE(tp->snd_ssthresh, val);
505 		if (tp->snd_ssthresh > tp->snd_cwnd_clamp)
506 			WRITE_ONCE(tp->snd_ssthresh, tp->snd_cwnd_clamp);
507 	}
508 	val = tcp_metric_get(tm, TCP_METRIC_REORDERING);
509 	if (val && tp->reordering != val)
510 		WRITE_ONCE(tp->reordering, val);
511 
512 	crtt = tcp_metric_get(tm, TCP_METRIC_RTT);
513 	rcu_read_unlock();
514 reset:
515 	/* The initial RTT measurement from the SYN/SYN-ACK is not ideal
516 	 * to seed the RTO for later data packets because SYN packets are
517 	 * small. Use the per-dst cached values to seed the RTO but keep
518 	 * the RTT estimator variables intact (e.g., srtt, mdev, rttvar).
519 	 * Later the RTO will be updated immediately upon obtaining the first
520 	 * data RTT sample (tcp_rtt_estimator()). Hence the cached RTT only
521 	 * influences the first RTO but not later RTT estimation.
522 	 *
523 	 * But if RTT is not available from the SYN (due to retransmits or
524 	 * syn cookies) or the cache, force a conservative 3secs timeout.
525 	 *
526 	 * A bit of theory. RTT is time passed after "normal" sized packet
527 	 * is sent until it is ACKed. In normal circumstances sending small
528 	 * packets force peer to delay ACKs and calculation is correct too.
529 	 * The algorithm is adaptive and, provided we follow specs, it
530 	 * NEVER underestimate RTT. BUT! If peer tries to make some clever
531 	 * tricks sort of "quick acks" for time long enough to decrease RTT
532 	 * to low value, and then abruptly stops to do it and starts to delay
533 	 * ACKs, wait for troubles.
534 	 */
535 	if (crtt > tp->srtt_us) {
536 		/* Set RTO like tcp_rtt_estimator(), but from cached RTT. */
537 		crtt /= 8 * USEC_PER_SEC / HZ;
538 		inet_csk(sk)->icsk_rto = crtt + max(2 * crtt, tcp_rto_min(sk));
539 	} else if (tp->srtt_us == 0) {
540 		/* RFC6298: 5.7 We've failed to get a valid RTT sample from
541 		 * 3WHS. This is most likely due to retransmission,
542 		 * including spurious one. Reset the RTO back to 3secs
543 		 * from the more aggressive 1sec to avoid more spurious
544 		 * retransmission.
545 		 */
546 		tp->rttvar_us = jiffies_to_usecs(TCP_TIMEOUT_FALLBACK);
547 		tp->mdev_us = tp->mdev_max_us = tp->rttvar_us;
548 
549 		inet_csk(sk)->icsk_rto = TCP_TIMEOUT_FALLBACK;
550 	}
551 }
552 
553 bool tcp_peer_is_proven(struct request_sock *req, struct dst_entry *dst)
554 {
555 	struct tcp_metrics_block *tm;
556 	bool ret;
557 
558 	if (!dst)
559 		return false;
560 
561 	rcu_read_lock();
562 	tm = __tcp_get_metrics_req(req, dst);
563 	if (tm && tcp_metric_get(tm, TCP_METRIC_RTT))
564 		ret = true;
565 	else
566 		ret = false;
567 	rcu_read_unlock();
568 
569 	return ret;
570 }
571 
572 void tcp_fastopen_cache_get(struct sock *sk, u16 *mss,
573 			    struct tcp_fastopen_cookie *cookie)
574 {
575 	struct tcp_metrics_block *tm;
576 
577 	rcu_read_lock();
578 	tm = tcp_get_metrics(sk, __sk_dst_get(sk), false);
579 	if (tm) {
580 		struct tcp_fastopen_metrics *tfom = &tm->tcpm_fastopen;
581 		unsigned int seq;
582 
583 		do {
584 			seq = read_seqbegin(&fastopen_seqlock);
585 			if (tfom->mss)
586 				*mss = tfom->mss;
587 			*cookie = tfom->cookie;
588 			if (cookie->len <= 0 && tfom->try_exp == 1)
589 				cookie->exp = true;
590 		} while (read_seqretry(&fastopen_seqlock, seq));
591 	}
592 	rcu_read_unlock();
593 }
594 
595 void tcp_fastopen_cache_set(struct sock *sk, u16 mss,
596 			    struct tcp_fastopen_cookie *cookie, bool syn_lost,
597 			    u16 try_exp)
598 {
599 	struct dst_entry *dst = __sk_dst_get(sk);
600 	struct tcp_metrics_block *tm;
601 
602 	if (!dst)
603 		return;
604 	rcu_read_lock();
605 	tm = tcp_get_metrics(sk, dst, true);
606 	if (tm) {
607 		struct tcp_fastopen_metrics *tfom = &tm->tcpm_fastopen;
608 
609 		write_seqlock_bh(&fastopen_seqlock);
610 		if (mss)
611 			tfom->mss = mss;
612 		if (cookie && cookie->len > 0)
613 			tfom->cookie = *cookie;
614 		else if (try_exp > tfom->try_exp &&
615 			 tfom->cookie.len <= 0 && !tfom->cookie.exp)
616 			tfom->try_exp = try_exp;
617 		if (syn_lost) {
618 			++tfom->syn_loss;
619 			tfom->last_syn_loss = jiffies;
620 		} else
621 			tfom->syn_loss = 0;
622 		write_sequnlock_bh(&fastopen_seqlock);
623 	}
624 	rcu_read_unlock();
625 }
626 
627 static struct genl_family tcp_metrics_nl_family;
628 
629 static const struct nla_policy tcp_metrics_nl_policy[TCP_METRICS_ATTR_MAX + 1] = {
630 	[TCP_METRICS_ATTR_ADDR_IPV4]	= { .type = NLA_U32, },
631 	[TCP_METRICS_ATTR_ADDR_IPV6]	=
632 		NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
633 
634 	[TCP_METRICS_ATTR_SADDR_IPV4]	= { .type = NLA_U32, },
635 	[TCP_METRICS_ATTR_SADDR_IPV6]	=
636 		NLA_POLICY_EXACT_LEN(sizeof(struct in6_addr)),
637 
638 	/* Following attributes are not received for GET/DEL,
639 	 * we keep them for reference
640 	 */
641 #if 0
642 	[TCP_METRICS_ATTR_AGE]		= { .type = NLA_MSECS, },
643 	[TCP_METRICS_ATTR_TW_TSVAL]	= { .type = NLA_U32, },
644 	[TCP_METRICS_ATTR_TW_TS_STAMP]	= { .type = NLA_S32, },
645 	[TCP_METRICS_ATTR_VALS]		= { .type = NLA_NESTED, },
646 	[TCP_METRICS_ATTR_FOPEN_MSS]	= { .type = NLA_U16, },
647 	[TCP_METRICS_ATTR_FOPEN_SYN_DROPS]	= { .type = NLA_U16, },
648 	[TCP_METRICS_ATTR_FOPEN_SYN_DROP_TS]	= { .type = NLA_MSECS, },
649 	[TCP_METRICS_ATTR_FOPEN_COOKIE]	= { .type = NLA_BINARY,
650 					    .len = TCP_FASTOPEN_COOKIE_MAX, },
651 #endif
652 };
653 
654 /* Add attributes, caller cancels its header on failure */
655 static int tcp_metrics_fill_info(struct sk_buff *msg,
656 				 struct tcp_metrics_block *tm)
657 {
658 	struct nlattr *nest;
659 	int i;
660 
661 	switch (tm->tcpm_daddr.family) {
662 	case AF_INET:
663 		if (nla_put_in_addr(msg, TCP_METRICS_ATTR_ADDR_IPV4,
664 				    inetpeer_get_addr_v4(&tm->tcpm_daddr)) < 0)
665 			goto nla_put_failure;
666 		if (nla_put_in_addr(msg, TCP_METRICS_ATTR_SADDR_IPV4,
667 				    inetpeer_get_addr_v4(&tm->tcpm_saddr)) < 0)
668 			goto nla_put_failure;
669 		break;
670 	case AF_INET6:
671 		if (nla_put_in6_addr(msg, TCP_METRICS_ATTR_ADDR_IPV6,
672 				     inetpeer_get_addr_v6(&tm->tcpm_daddr)) < 0)
673 			goto nla_put_failure;
674 		if (nla_put_in6_addr(msg, TCP_METRICS_ATTR_SADDR_IPV6,
675 				     inetpeer_get_addr_v6(&tm->tcpm_saddr)) < 0)
676 			goto nla_put_failure;
677 		break;
678 	default:
679 		return -EAFNOSUPPORT;
680 	}
681 
682 	if (nla_put_msecs(msg, TCP_METRICS_ATTR_AGE,
683 			  jiffies - READ_ONCE(tm->tcpm_stamp),
684 			  TCP_METRICS_ATTR_PAD) < 0)
685 		goto nla_put_failure;
686 
687 	{
688 		int n = 0;
689 
690 		nest = nla_nest_start_noflag(msg, TCP_METRICS_ATTR_VALS);
691 		if (!nest)
692 			goto nla_put_failure;
693 		for (i = 0; i < TCP_METRIC_MAX_KERNEL + 1; i++) {
694 			u32 val = tcp_metric_get(tm, i);
695 
696 			if (!val)
697 				continue;
698 			if (i == TCP_METRIC_RTT) {
699 				if (nla_put_u32(msg, TCP_METRIC_RTT_US + 1,
700 						val) < 0)
701 					goto nla_put_failure;
702 				n++;
703 				val = max(val / 1000, 1U);
704 			}
705 			if (i == TCP_METRIC_RTTVAR) {
706 				if (nla_put_u32(msg, TCP_METRIC_RTTVAR_US + 1,
707 						val) < 0)
708 					goto nla_put_failure;
709 				n++;
710 				val = max(val / 1000, 1U);
711 			}
712 			if (nla_put_u32(msg, i + 1, val) < 0)
713 				goto nla_put_failure;
714 			n++;
715 		}
716 		if (n)
717 			nla_nest_end(msg, nest);
718 		else
719 			nla_nest_cancel(msg, nest);
720 	}
721 
722 	{
723 		struct tcp_fastopen_metrics tfom_copy[1], *tfom;
724 		unsigned int seq;
725 
726 		do {
727 			seq = read_seqbegin(&fastopen_seqlock);
728 			tfom_copy[0] = tm->tcpm_fastopen;
729 		} while (read_seqretry(&fastopen_seqlock, seq));
730 
731 		tfom = tfom_copy;
732 		if (tfom->mss &&
733 		    nla_put_u16(msg, TCP_METRICS_ATTR_FOPEN_MSS,
734 				tfom->mss) < 0)
735 			goto nla_put_failure;
736 		if (tfom->syn_loss &&
737 		    (nla_put_u16(msg, TCP_METRICS_ATTR_FOPEN_SYN_DROPS,
738 				tfom->syn_loss) < 0 ||
739 		     nla_put_msecs(msg, TCP_METRICS_ATTR_FOPEN_SYN_DROP_TS,
740 				jiffies - tfom->last_syn_loss,
741 				TCP_METRICS_ATTR_PAD) < 0))
742 			goto nla_put_failure;
743 		if (tfom->cookie.len > 0 &&
744 		    nla_put(msg, TCP_METRICS_ATTR_FOPEN_COOKIE,
745 			    tfom->cookie.len, tfom->cookie.val) < 0)
746 			goto nla_put_failure;
747 	}
748 
749 	return 0;
750 
751 nla_put_failure:
752 	return -EMSGSIZE;
753 }
754 
755 static int tcp_metrics_dump_info(struct sk_buff *skb,
756 				 struct netlink_callback *cb,
757 				 struct tcp_metrics_block *tm)
758 {
759 	void *hdr;
760 
761 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
762 			  &tcp_metrics_nl_family, NLM_F_MULTI,
763 			  TCP_METRICS_CMD_GET);
764 	if (!hdr)
765 		return -EMSGSIZE;
766 
767 	if (tcp_metrics_fill_info(skb, tm) < 0)
768 		goto nla_put_failure;
769 
770 	genlmsg_end(skb, hdr);
771 	return 0;
772 
773 nla_put_failure:
774 	genlmsg_cancel(skb, hdr);
775 	return -EMSGSIZE;
776 }
777 
778 static int tcp_metrics_nl_dump(struct sk_buff *skb,
779 			       struct netlink_callback *cb)
780 {
781 	struct net *net = sock_net(skb->sk);
782 	unsigned int max_rows = 1U << tcp_metrics_hash_log;
783 	unsigned int row, s_row = cb->args[0];
784 	int s_col = cb->args[1], col = s_col;
785 	int res = 0;
786 
787 	for (row = s_row; row < max_rows; row++, s_col = 0) {
788 		struct tcp_metrics_block *tm;
789 		struct tcpm_hash_bucket *hb = tcp_metrics_hash + row;
790 
791 		rcu_read_lock();
792 		for (col = 0, tm = rcu_dereference(hb->chain); tm;
793 		     tm = rcu_dereference(tm->tcpm_next), col++) {
794 			if (!net_eq(tm_net(tm), net))
795 				continue;
796 			if (col < s_col)
797 				continue;
798 			res = tcp_metrics_dump_info(skb, cb, tm);
799 			if (res < 0) {
800 				rcu_read_unlock();
801 				goto done;
802 			}
803 		}
804 		rcu_read_unlock();
805 	}
806 
807 done:
808 	cb->args[0] = row;
809 	cb->args[1] = col;
810 	return res;
811 }
812 
813 static int __parse_nl_addr(struct genl_info *info, struct inetpeer_addr *addr,
814 			   unsigned int *hash, int optional, int v4, int v6)
815 {
816 	struct nlattr *a;
817 
818 	a = info->attrs[v4];
819 	if (a) {
820 		inetpeer_set_addr_v4(addr, nla_get_in_addr(a));
821 		if (hash)
822 			*hash = ipv4_addr_hash(inetpeer_get_addr_v4(addr));
823 		return 0;
824 	}
825 	a = info->attrs[v6];
826 	if (a) {
827 		struct in6_addr in6;
828 
829 		in6 = nla_get_in6_addr(a);
830 		inetpeer_set_addr_v6(addr, &in6);
831 		if (hash)
832 			*hash = ipv6_addr_hash(inetpeer_get_addr_v6(addr));
833 		return 0;
834 	}
835 	return optional ? 1 : -EAFNOSUPPORT;
836 }
837 
838 static int parse_nl_addr(struct genl_info *info, struct inetpeer_addr *addr,
839 			 unsigned int *hash, int optional)
840 {
841 	return __parse_nl_addr(info, addr, hash, optional,
842 			       TCP_METRICS_ATTR_ADDR_IPV4,
843 			       TCP_METRICS_ATTR_ADDR_IPV6);
844 }
845 
846 static int parse_nl_saddr(struct genl_info *info, struct inetpeer_addr *addr)
847 {
848 	return __parse_nl_addr(info, addr, NULL, 0,
849 			       TCP_METRICS_ATTR_SADDR_IPV4,
850 			       TCP_METRICS_ATTR_SADDR_IPV6);
851 }
852 
853 static int tcp_metrics_nl_cmd_get(struct sk_buff *skb, struct genl_info *info)
854 {
855 	struct tcp_metrics_block *tm;
856 	struct inetpeer_addr saddr, daddr;
857 	unsigned int hash;
858 	struct sk_buff *msg;
859 	struct net *net = genl_info_net(info);
860 	void *reply;
861 	int ret;
862 	bool src = true;
863 
864 	ret = parse_nl_addr(info, &daddr, &hash, 0);
865 	if (ret < 0)
866 		return ret;
867 
868 	ret = parse_nl_saddr(info, &saddr);
869 	if (ret < 0)
870 		src = false;
871 
872 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
873 	if (!msg)
874 		return -ENOMEM;
875 
876 	reply = genlmsg_put_reply(msg, info, &tcp_metrics_nl_family, 0,
877 				  info->genlhdr->cmd);
878 	if (!reply)
879 		goto nla_put_failure;
880 
881 	hash ^= net_hash_mix(net);
882 	hash = hash_32(hash, tcp_metrics_hash_log);
883 	ret = -ESRCH;
884 	rcu_read_lock();
885 	for (tm = rcu_dereference(tcp_metrics_hash[hash].chain); tm;
886 	     tm = rcu_dereference(tm->tcpm_next)) {
887 		if (addr_same(&tm->tcpm_daddr, &daddr) &&
888 		    (!src || addr_same(&tm->tcpm_saddr, &saddr)) &&
889 		    net_eq(tm_net(tm), net)) {
890 			ret = tcp_metrics_fill_info(msg, tm);
891 			break;
892 		}
893 	}
894 	rcu_read_unlock();
895 	if (ret < 0)
896 		goto out_free;
897 
898 	genlmsg_end(msg, reply);
899 	return genlmsg_reply(msg, info);
900 
901 nla_put_failure:
902 	ret = -EMSGSIZE;
903 
904 out_free:
905 	nlmsg_free(msg);
906 	return ret;
907 }
908 
909 static void tcp_metrics_flush_all(struct net *net)
910 {
911 	unsigned int max_rows = 1U << tcp_metrics_hash_log;
912 	struct tcpm_hash_bucket *hb = tcp_metrics_hash;
913 	struct tcp_metrics_block *tm;
914 	unsigned int row;
915 
916 	for (row = 0; row < max_rows; row++, hb++) {
917 		struct tcp_metrics_block __rcu **pp = &hb->chain;
918 		bool match;
919 
920 		if (!rcu_access_pointer(*pp))
921 			continue;
922 
923 		spin_lock_bh(&tcp_metrics_lock);
924 		for (tm = deref_locked(*pp); tm; tm = deref_locked(*pp)) {
925 			match = net ? net_eq(tm_net(tm), net) :
926 				!check_net(tm_net(tm));
927 			if (match) {
928 				rcu_assign_pointer(*pp, tm->tcpm_next);
929 				kfree_rcu(tm, rcu_head);
930 			} else {
931 				pp = &tm->tcpm_next;
932 			}
933 		}
934 		spin_unlock_bh(&tcp_metrics_lock);
935 		cond_resched();
936 	}
937 }
938 
939 static int tcp_metrics_nl_cmd_del(struct sk_buff *skb, struct genl_info *info)
940 {
941 	struct tcpm_hash_bucket *hb;
942 	struct tcp_metrics_block *tm;
943 	struct tcp_metrics_block __rcu **pp;
944 	struct inetpeer_addr saddr, daddr;
945 	unsigned int hash;
946 	struct net *net = genl_info_net(info);
947 	int ret;
948 	bool src = true, found = false;
949 
950 	ret = parse_nl_addr(info, &daddr, &hash, 1);
951 	if (ret < 0)
952 		return ret;
953 	if (ret > 0) {
954 		tcp_metrics_flush_all(net);
955 		return 0;
956 	}
957 	ret = parse_nl_saddr(info, &saddr);
958 	if (ret < 0)
959 		src = false;
960 
961 	hash ^= net_hash_mix(net);
962 	hash = hash_32(hash, tcp_metrics_hash_log);
963 	hb = tcp_metrics_hash + hash;
964 	pp = &hb->chain;
965 	spin_lock_bh(&tcp_metrics_lock);
966 	for (tm = deref_locked(*pp); tm; tm = deref_locked(*pp)) {
967 		if (addr_same(&tm->tcpm_daddr, &daddr) &&
968 		    (!src || addr_same(&tm->tcpm_saddr, &saddr)) &&
969 		    net_eq(tm_net(tm), net)) {
970 			rcu_assign_pointer(*pp, tm->tcpm_next);
971 			kfree_rcu(tm, rcu_head);
972 			found = true;
973 		} else {
974 			pp = &tm->tcpm_next;
975 		}
976 	}
977 	spin_unlock_bh(&tcp_metrics_lock);
978 	if (!found)
979 		return -ESRCH;
980 	return 0;
981 }
982 
983 static const struct genl_small_ops tcp_metrics_nl_ops[] = {
984 	{
985 		.cmd = TCP_METRICS_CMD_GET,
986 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
987 		.doit = tcp_metrics_nl_cmd_get,
988 		.dumpit = tcp_metrics_nl_dump,
989 	},
990 	{
991 		.cmd = TCP_METRICS_CMD_DEL,
992 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
993 		.doit = tcp_metrics_nl_cmd_del,
994 		.flags = GENL_ADMIN_PERM,
995 	},
996 };
997 
998 static struct genl_family tcp_metrics_nl_family __ro_after_init = {
999 	.hdrsize	= 0,
1000 	.name		= TCP_METRICS_GENL_NAME,
1001 	.version	= TCP_METRICS_GENL_VERSION,
1002 	.maxattr	= TCP_METRICS_ATTR_MAX,
1003 	.policy = tcp_metrics_nl_policy,
1004 	.netnsok	= true,
1005 	.parallel_ops	= true,
1006 	.module		= THIS_MODULE,
1007 	.small_ops	= tcp_metrics_nl_ops,
1008 	.n_small_ops	= ARRAY_SIZE(tcp_metrics_nl_ops),
1009 	.resv_start_op	= TCP_METRICS_CMD_DEL + 1,
1010 };
1011 
1012 static unsigned int tcpmhash_entries __initdata;
1013 static int __init set_tcpmhash_entries(char *str)
1014 {
1015 	ssize_t ret;
1016 
1017 	if (!str)
1018 		return 0;
1019 
1020 	ret = kstrtouint(str, 0, &tcpmhash_entries);
1021 	if (ret)
1022 		return 0;
1023 
1024 	return 1;
1025 }
1026 __setup("tcpmhash_entries=", set_tcpmhash_entries);
1027 
1028 static void __init tcp_metrics_hash_alloc(void)
1029 {
1030 	unsigned int slots = tcpmhash_entries;
1031 	size_t size;
1032 
1033 	if (!slots) {
1034 		if (totalram_pages() >= 128 * 1024)
1035 			slots = 16 * 1024;
1036 		else
1037 			slots = 8 * 1024;
1038 	}
1039 
1040 	tcp_metrics_hash_log = order_base_2(slots);
1041 	size = sizeof(struct tcpm_hash_bucket) << tcp_metrics_hash_log;
1042 
1043 	tcp_metrics_hash = kvzalloc(size, GFP_KERNEL);
1044 	if (!tcp_metrics_hash)
1045 		panic("Could not allocate the tcp_metrics hash table\n");
1046 }
1047 
1048 static void __net_exit tcp_net_metrics_exit_batch(struct list_head *net_exit_list)
1049 {
1050 	tcp_metrics_flush_all(NULL);
1051 }
1052 
1053 static __net_initdata struct pernet_operations tcp_net_metrics_ops = {
1054 	.exit_batch	=	tcp_net_metrics_exit_batch,
1055 };
1056 
1057 void __init tcp_metrics_init(void)
1058 {
1059 	int ret;
1060 
1061 	tcp_metrics_hash_alloc();
1062 
1063 	ret = register_pernet_subsys(&tcp_net_metrics_ops);
1064 	if (ret < 0)
1065 		panic("Could not register tcp_net_metrics_ops\n");
1066 
1067 	ret = genl_register_family(&tcp_metrics_nl_family);
1068 	if (ret < 0)
1069 		panic("Could not register tcp_metrics generic netlink\n");
1070 }
1071