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