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