xref: /linux/net/ipv4/tcp_cong.c (revision ca220141fa8ebae09765a242076b2b77338106b0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Pluggable TCP congestion control support and newReno
4  * congestion control.
5  * Based on ideas from I/O scheduler support and Web100.
6  *
7  * Copyright (C) 2005 Stephen Hemminger <shemminger@osdl.org>
8  */
9 
10 #define pr_fmt(fmt) "TCP: " fmt
11 
12 #include <linux/module.h>
13 #include <linux/mm.h>
14 #include <linux/types.h>
15 #include <linux/list.h>
16 #include <linux/gfp.h>
17 #include <linux/jhash.h>
18 #include <net/tcp.h>
19 #include <net/tcp_ecn.h>
20 #include <trace/events/tcp.h>
21 
22 static DEFINE_SPINLOCK(tcp_cong_list_lock);
23 static LIST_HEAD(tcp_cong_list);
24 
25 /* Simple linear search, don't expect many entries! */
26 struct tcp_congestion_ops *tcp_ca_find(const char *name)
27 {
28 	struct tcp_congestion_ops *e;
29 
30 	list_for_each_entry_rcu(e, &tcp_cong_list, list) {
31 		if (strcmp(e->name, name) == 0)
32 			return e;
33 	}
34 
35 	return NULL;
36 }
37 
38 void tcp_set_ca_state(struct sock *sk, const u8 ca_state)
39 {
40 	struct inet_connection_sock *icsk = inet_csk(sk);
41 
42 	trace_tcp_cong_state_set(sk, ca_state);
43 
44 	if (icsk->icsk_ca_ops->set_state)
45 		icsk->icsk_ca_ops->set_state(sk, ca_state);
46 	icsk->icsk_ca_state = ca_state;
47 }
48 
49 /* Must be called with rcu lock held */
50 static struct tcp_congestion_ops *tcp_ca_find_autoload(const char *name)
51 {
52 	struct tcp_congestion_ops *ca = tcp_ca_find(name);
53 
54 #ifdef CONFIG_MODULES
55 	if (!ca && capable(CAP_NET_ADMIN)) {
56 		rcu_read_unlock();
57 		request_module("tcp_%s", name);
58 		rcu_read_lock();
59 		ca = tcp_ca_find(name);
60 	}
61 #endif
62 	return ca;
63 }
64 
65 /* Simple linear search, not much in here. */
66 struct tcp_congestion_ops *tcp_ca_find_key(u32 key)
67 {
68 	struct tcp_congestion_ops *e;
69 
70 	list_for_each_entry_rcu(e, &tcp_cong_list, list) {
71 		if (e->key == key)
72 			return e;
73 	}
74 
75 	return NULL;
76 }
77 
78 int tcp_validate_congestion_control(struct tcp_congestion_ops *ca)
79 {
80 	/* all algorithms must implement these */
81 	if (!ca->ssthresh || !ca->undo_cwnd ||
82 	    !(ca->cong_avoid || ca->cong_control)) {
83 		pr_err("%s does not implement required ops\n", ca->name);
84 		return -EINVAL;
85 	}
86 
87 	return 0;
88 }
89 
90 /* Attach new congestion control algorithm to the list
91  * of available options.
92  */
93 int tcp_register_congestion_control(struct tcp_congestion_ops *ca)
94 {
95 	int ret;
96 
97 	ret = tcp_validate_congestion_control(ca);
98 	if (ret)
99 		return ret;
100 
101 	ca->key = jhash(ca->name, sizeof(ca->name), strlen(ca->name));
102 
103 	spin_lock(&tcp_cong_list_lock);
104 	if (ca->key == TCP_CA_UNSPEC || tcp_ca_find_key(ca->key)) {
105 		pr_notice("%s already registered or non-unique key\n",
106 			  ca->name);
107 		ret = -EEXIST;
108 	} else {
109 		list_add_tail_rcu(&ca->list, &tcp_cong_list);
110 		pr_debug("%s registered\n", ca->name);
111 	}
112 	spin_unlock(&tcp_cong_list_lock);
113 
114 	return ret;
115 }
116 EXPORT_SYMBOL_GPL(tcp_register_congestion_control);
117 
118 /*
119  * Remove congestion control algorithm, called from
120  * the module's remove function.  Module ref counts are used
121  * to ensure that this can't be done till all sockets using
122  * that method are closed.
123  */
124 void tcp_unregister_congestion_control(struct tcp_congestion_ops *ca)
125 {
126 	spin_lock(&tcp_cong_list_lock);
127 	list_del_rcu(&ca->list);
128 	spin_unlock(&tcp_cong_list_lock);
129 
130 	/* Wait for outstanding readers to complete before the
131 	 * module gets removed entirely.
132 	 *
133 	 * A try_module_get() should fail by now as our module is
134 	 * in "going" state since no refs are held anymore and
135 	 * module_exit() handler being called.
136 	 */
137 	synchronize_rcu();
138 }
139 EXPORT_SYMBOL_GPL(tcp_unregister_congestion_control);
140 
141 /* Replace a registered old ca with a new one.
142  *
143  * The new ca must have the same name as the old one, that has been
144  * registered.
145  */
146 int tcp_update_congestion_control(struct tcp_congestion_ops *ca, struct tcp_congestion_ops *old_ca)
147 {
148 	struct tcp_congestion_ops *existing;
149 	int ret = 0;
150 
151 	ca->key = jhash(ca->name, sizeof(ca->name), strlen(ca->name));
152 
153 	spin_lock(&tcp_cong_list_lock);
154 	existing = tcp_ca_find_key(old_ca->key);
155 	if (ca->key == TCP_CA_UNSPEC || !existing || strcmp(existing->name, ca->name)) {
156 		pr_notice("%s not registered or non-unique key\n",
157 			  ca->name);
158 		ret = -EINVAL;
159 	} else if (existing != old_ca) {
160 		pr_notice("invalid old congestion control algorithm to replace\n");
161 		ret = -EINVAL;
162 	} else {
163 		/* Add the new one before removing the old one to keep
164 		 * one implementation available all the time.
165 		 */
166 		list_add_tail_rcu(&ca->list, &tcp_cong_list);
167 		list_del_rcu(&existing->list);
168 		pr_debug("%s updated\n", ca->name);
169 	}
170 	spin_unlock(&tcp_cong_list_lock);
171 
172 	/* Wait for outstanding readers to complete before the
173 	 * module or struct_ops gets removed entirely.
174 	 */
175 	if (!ret)
176 		synchronize_rcu();
177 
178 	return ret;
179 }
180 
181 u32 tcp_ca_get_key_by_name(const char *name, bool *ecn_ca)
182 {
183 	const struct tcp_congestion_ops *ca;
184 	u32 key = TCP_CA_UNSPEC;
185 
186 	might_sleep();
187 
188 	rcu_read_lock();
189 	ca = tcp_ca_find_autoload(name);
190 	if (ca) {
191 		key = ca->key;
192 		*ecn_ca = ca->flags & TCP_CONG_NEEDS_ECN;
193 	}
194 	rcu_read_unlock();
195 
196 	return key;
197 }
198 
199 char *tcp_ca_get_name_by_key(u32 key, char *buffer)
200 {
201 	const struct tcp_congestion_ops *ca;
202 	char *ret = NULL;
203 
204 	rcu_read_lock();
205 	ca = tcp_ca_find_key(key);
206 	if (ca) {
207 		strscpy(buffer, ca->name, TCP_CA_NAME_MAX);
208 		ret = buffer;
209 	}
210 	rcu_read_unlock();
211 
212 	return ret;
213 }
214 
215 /* Assign choice of congestion control. */
216 void tcp_assign_congestion_control(struct sock *sk)
217 {
218 	struct net *net = sock_net(sk);
219 	struct inet_connection_sock *icsk = inet_csk(sk);
220 	const struct tcp_congestion_ops *ca;
221 
222 	rcu_read_lock();
223 	ca = rcu_dereference(net->ipv4.tcp_congestion_control);
224 	if (unlikely(!bpf_try_module_get(ca, ca->owner)))
225 		ca = &tcp_reno;
226 	icsk->icsk_ca_ops = ca;
227 	rcu_read_unlock();
228 
229 	memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv));
230 	if (ca->flags & TCP_CONG_NEEDS_ECN)
231 		INET_ECN_xmit_ect_1_negotiation(sk);
232 	else
233 		INET_ECN_dontxmit(sk);
234 }
235 
236 void tcp_init_congestion_control(struct sock *sk)
237 {
238 	struct inet_connection_sock *icsk = inet_csk(sk);
239 
240 	tcp_sk(sk)->prior_ssthresh = 0;
241 	if (icsk->icsk_ca_ops->init)
242 		icsk->icsk_ca_ops->init(sk);
243 	if (tcp_ca_needs_ecn(sk))
244 		INET_ECN_xmit(sk);
245 	else
246 		INET_ECN_dontxmit(sk);
247 	icsk->icsk_ca_initialized = 1;
248 }
249 
250 static void tcp_reinit_congestion_control(struct sock *sk,
251 					  const struct tcp_congestion_ops *ca)
252 {
253 	struct inet_connection_sock *icsk = inet_csk(sk);
254 
255 	tcp_cleanup_congestion_control(sk);
256 	icsk->icsk_ca_ops = ca;
257 	icsk->icsk_ca_setsockopt = 1;
258 	memset(icsk->icsk_ca_priv, 0, sizeof(icsk->icsk_ca_priv));
259 
260 	if (ca->flags & TCP_CONG_NEEDS_ECN)
261 		INET_ECN_xmit_ect_1_negotiation(sk);
262 	else
263 		INET_ECN_dontxmit(sk);
264 
265 	if (!((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_LISTEN)))
266 		tcp_init_congestion_control(sk);
267 }
268 
269 /* Manage refcounts on socket close. */
270 void tcp_cleanup_congestion_control(struct sock *sk)
271 {
272 	struct inet_connection_sock *icsk = inet_csk(sk);
273 
274 	if (icsk->icsk_ca_initialized && icsk->icsk_ca_ops->release)
275 		icsk->icsk_ca_ops->release(sk);
276 	icsk->icsk_ca_initialized = 0;
277 	bpf_module_put(icsk->icsk_ca_ops, icsk->icsk_ca_ops->owner);
278 }
279 
280 /* Used by sysctl to change default congestion control */
281 int tcp_set_default_congestion_control(struct net *net, const char *name)
282 {
283 	struct tcp_congestion_ops *ca;
284 	const struct tcp_congestion_ops *prev;
285 	int ret;
286 
287 	rcu_read_lock();
288 	ca = tcp_ca_find_autoload(name);
289 	if (!ca) {
290 		ret = -ENOENT;
291 	} else if (!bpf_try_module_get(ca, ca->owner)) {
292 		ret = -EBUSY;
293 	} else if (!net_eq(net, &init_net) &&
294 			!(ca->flags & TCP_CONG_NON_RESTRICTED)) {
295 		/* Only init netns can set default to a restricted algorithm */
296 		ret = -EPERM;
297 	} else {
298 		prev = xchg(&net->ipv4.tcp_congestion_control, ca);
299 		if (prev)
300 			bpf_module_put(prev, prev->owner);
301 
302 		ca->flags |= TCP_CONG_NON_RESTRICTED;
303 		ret = 0;
304 	}
305 	rcu_read_unlock();
306 
307 	return ret;
308 }
309 
310 /* Set default value from kernel configuration at bootup */
311 static int __init tcp_congestion_default(void)
312 {
313 	return tcp_set_default_congestion_control(&init_net,
314 						  CONFIG_DEFAULT_TCP_CONG);
315 }
316 late_initcall(tcp_congestion_default);
317 
318 /* Build string with list of available congestion control values */
319 void tcp_get_available_congestion_control(char *buf, size_t maxlen)
320 {
321 	struct tcp_congestion_ops *ca;
322 	size_t offs = 0;
323 
324 	rcu_read_lock();
325 	list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
326 		offs += snprintf(buf + offs, maxlen - offs,
327 				 "%s%s",
328 				 offs == 0 ? "" : " ", ca->name);
329 
330 		if (WARN_ON_ONCE(offs >= maxlen))
331 			break;
332 	}
333 	rcu_read_unlock();
334 }
335 
336 /* Get current default congestion control */
337 void tcp_get_default_congestion_control(struct net *net, char *name)
338 {
339 	const struct tcp_congestion_ops *ca;
340 
341 	rcu_read_lock();
342 	ca = rcu_dereference(net->ipv4.tcp_congestion_control);
343 	strscpy(name, ca->name, TCP_CA_NAME_MAX);
344 	rcu_read_unlock();
345 }
346 
347 /* Built list of non-restricted congestion control values */
348 void tcp_get_allowed_congestion_control(char *buf, size_t maxlen)
349 {
350 	struct tcp_congestion_ops *ca;
351 	size_t offs = 0;
352 
353 	*buf = '\0';
354 	rcu_read_lock();
355 	list_for_each_entry_rcu(ca, &tcp_cong_list, list) {
356 		if (!(ca->flags & TCP_CONG_NON_RESTRICTED))
357 			continue;
358 		offs += snprintf(buf + offs, maxlen - offs,
359 				 "%s%s",
360 				 offs == 0 ? "" : " ", ca->name);
361 
362 		if (WARN_ON_ONCE(offs >= maxlen))
363 			break;
364 	}
365 	rcu_read_unlock();
366 }
367 
368 /* Change list of non-restricted congestion control */
369 int tcp_set_allowed_congestion_control(char *val)
370 {
371 	struct tcp_congestion_ops *ca;
372 	char *saved_clone, *clone, *name;
373 	int ret = 0;
374 
375 	saved_clone = clone = kstrdup(val, GFP_USER);
376 	if (!clone)
377 		return -ENOMEM;
378 
379 	spin_lock(&tcp_cong_list_lock);
380 	/* pass 1 check for bad entries */
381 	while ((name = strsep(&clone, " ")) && *name) {
382 		ca = tcp_ca_find(name);
383 		if (!ca) {
384 			ret = -ENOENT;
385 			goto out;
386 		}
387 	}
388 
389 	/* pass 2 clear old values */
390 	list_for_each_entry_rcu(ca, &tcp_cong_list, list)
391 		ca->flags &= ~TCP_CONG_NON_RESTRICTED;
392 
393 	/* pass 3 mark as allowed */
394 	while ((name = strsep(&val, " ")) && *name) {
395 		ca = tcp_ca_find(name);
396 		WARN_ON(!ca);
397 		if (ca)
398 			ca->flags |= TCP_CONG_NON_RESTRICTED;
399 	}
400 out:
401 	spin_unlock(&tcp_cong_list_lock);
402 	kfree(saved_clone);
403 
404 	return ret;
405 }
406 
407 /* Change congestion control for socket. If load is false, then it is the
408  * responsibility of the caller to call tcp_init_congestion_control or
409  * tcp_reinit_congestion_control (if the current congestion control was
410  * already initialized.
411  */
412 int tcp_set_congestion_control(struct sock *sk, const char *name, bool load,
413 			       bool cap_net_admin)
414 {
415 	struct inet_connection_sock *icsk = inet_csk(sk);
416 	const struct tcp_congestion_ops *ca;
417 	int err = 0;
418 
419 	if (icsk->icsk_ca_dst_locked)
420 		return -EPERM;
421 
422 	rcu_read_lock();
423 	if (!load)
424 		ca = tcp_ca_find(name);
425 	else
426 		ca = tcp_ca_find_autoload(name);
427 
428 	/* No change asking for existing value */
429 	if (ca == icsk->icsk_ca_ops) {
430 		icsk->icsk_ca_setsockopt = 1;
431 		goto out;
432 	}
433 
434 	if (!ca)
435 		err = -ENOENT;
436 	else if (!((ca->flags & TCP_CONG_NON_RESTRICTED) || cap_net_admin))
437 		err = -EPERM;
438 	else if (!bpf_try_module_get(ca, ca->owner))
439 		err = -EBUSY;
440 	else
441 		tcp_reinit_congestion_control(sk, ca);
442  out:
443 	rcu_read_unlock();
444 	return err;
445 }
446 
447 /* Slow start is used when congestion window is no greater than the slow start
448  * threshold. We base on RFC2581 and also handle stretch ACKs properly.
449  * We do not implement RFC3465 Appropriate Byte Counting (ABC) per se but
450  * something better;) a packet is only considered (s)acked in its entirety to
451  * defend the ACK attacks described in the RFC. Slow start processes a stretch
452  * ACK of degree N as if N acks of degree 1 are received back to back except
453  * ABC caps N to 2. Slow start exits when cwnd grows over ssthresh and
454  * returns the leftover acks to adjust cwnd in congestion avoidance mode.
455  */
456 __bpf_kfunc u32 tcp_slow_start(struct tcp_sock *tp, u32 acked)
457 {
458 	u32 cwnd = min(tcp_snd_cwnd(tp) + acked, tp->snd_ssthresh);
459 
460 	acked -= cwnd - tcp_snd_cwnd(tp);
461 	tcp_snd_cwnd_set(tp, min(cwnd, tp->snd_cwnd_clamp));
462 
463 	return acked;
464 }
465 EXPORT_SYMBOL_GPL(tcp_slow_start);
466 
467 /* In theory this is tp->snd_cwnd += 1 / tp->snd_cwnd (or alternative w),
468  * for every packet that was ACKed.
469  */
470 __bpf_kfunc void tcp_cong_avoid_ai(struct tcp_sock *tp, u32 w, u32 acked)
471 {
472 	/* If credits accumulated at a higher w, apply them gently now. */
473 	if (tp->snd_cwnd_cnt >= w) {
474 		tp->snd_cwnd_cnt = 0;
475 		tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) + 1);
476 	}
477 
478 	tp->snd_cwnd_cnt += acked;
479 	if (tp->snd_cwnd_cnt >= w) {
480 		u32 delta = tp->snd_cwnd_cnt / w;
481 
482 		tp->snd_cwnd_cnt -= delta * w;
483 		tcp_snd_cwnd_set(tp, tcp_snd_cwnd(tp) + delta);
484 	}
485 	tcp_snd_cwnd_set(tp, min(tcp_snd_cwnd(tp), tp->snd_cwnd_clamp));
486 }
487 EXPORT_SYMBOL_GPL(tcp_cong_avoid_ai);
488 
489 /*
490  * TCP Reno congestion control
491  * This is special case used for fallback as well.
492  */
493 /* This is Jacobson's slow start and congestion avoidance.
494  * SIGCOMM '88, p. 328.
495  */
496 __bpf_kfunc void tcp_reno_cong_avoid(struct sock *sk, u32 ack, u32 acked)
497 {
498 	struct tcp_sock *tp = tcp_sk(sk);
499 
500 	if (!tcp_is_cwnd_limited(sk))
501 		return;
502 
503 	/* In "safe" area, increase. */
504 	if (tcp_in_slow_start(tp)) {
505 		acked = tcp_slow_start(tp, acked);
506 		if (!acked)
507 			return;
508 	}
509 	/* In dangerous area, increase slowly. */
510 	tcp_cong_avoid_ai(tp, tcp_snd_cwnd(tp), acked);
511 }
512 EXPORT_SYMBOL_GPL(tcp_reno_cong_avoid);
513 
514 /* Slow start threshold is half the congestion window (min 2) */
515 __bpf_kfunc u32 tcp_reno_ssthresh(struct sock *sk)
516 {
517 	const struct tcp_sock *tp = tcp_sk(sk);
518 
519 	return max(tcp_snd_cwnd(tp) >> 1U, 2U);
520 }
521 EXPORT_SYMBOL_GPL(tcp_reno_ssthresh);
522 
523 __bpf_kfunc u32 tcp_reno_undo_cwnd(struct sock *sk)
524 {
525 	const struct tcp_sock *tp = tcp_sk(sk);
526 
527 	return max(tcp_snd_cwnd(tp), tp->prior_cwnd);
528 }
529 EXPORT_SYMBOL_GPL(tcp_reno_undo_cwnd);
530 
531 struct tcp_congestion_ops tcp_reno = {
532 	.flags		= TCP_CONG_NON_RESTRICTED,
533 	.name		= "reno",
534 	.owner		= THIS_MODULE,
535 	.ssthresh	= tcp_reno_ssthresh,
536 	.cong_avoid	= tcp_reno_cong_avoid,
537 	.undo_cwnd	= tcp_reno_undo_cwnd,
538 };
539