xref: /linux/tools/testing/selftests/bpf/progs/bpf_cubic.c (revision d1e59a46973719e458bec78d00dd767d7a7ba71f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 /* WARNING: This implementation is not necessarily the same
4  * as the tcp_cubic.c.  The purpose is mainly for testing
5  * the kernel BPF logic.
6  *
7  * Highlights:
8  * 1. CONFIG_HZ .kconfig map is used.
9  * 2. In bictcp_update(), calculation is changed to use usec
10  *    resolution (i.e. USEC_PER_JIFFY) instead of using jiffies.
11  *    Thus, usecs_to_jiffies() is not used in the bpf_cubic.c.
12  * 3. In bitctcp_update() [under tcp_friendliness], the original
13  *    "while (ca->ack_cnt > delta)" loop is changed to the equivalent
14  *    "ca->ack_cnt / delta" operation.
15  */
16 
17 #include "bpf_tracing_net.h"
18 #include <bpf/bpf_tracing.h>
19 
20 char _license[] SEC("license") = "GPL";
21 
22 #define clamp(val, lo, hi) min((typeof(val))max(val, lo), hi)
23 
24 extern __u32 tcp_slow_start(struct tcp_sock *tp, __u32 acked) __ksym;
25 extern void tcp_cong_avoid_ai(struct tcp_sock *tp, __u32 w, __u32 acked) __ksym;
26 
27 #define BICTCP_BETA_SCALE    1024	/* Scale factor beta calculation
28 					 * max_cwnd = snd_cwnd * beta
29 					 */
30 #define	BICTCP_HZ		10	/* BIC HZ 2^10 = 1024 */
31 
32 /* Two methods of hybrid slow start */
33 #define HYSTART_ACK_TRAIN	0x1
34 #define HYSTART_DELAY		0x2
35 
36 /* Number of delay samples for detecting the increase of delay */
37 #define HYSTART_MIN_SAMPLES	8
38 #define HYSTART_DELAY_MIN	(4000U)	/* 4ms */
39 #define HYSTART_DELAY_MAX	(16000U)	/* 16 ms */
40 #define HYSTART_DELAY_THRESH(x)	clamp(x, HYSTART_DELAY_MIN, HYSTART_DELAY_MAX)
41 
42 static int fast_convergence = 1;
43 static const int beta = 717;	/* = 717/1024 (BICTCP_BETA_SCALE) */
44 static int initial_ssthresh;
45 static const int bic_scale = 41;
46 static int tcp_friendliness = 1;
47 
48 static int hystart = 1;
49 static int hystart_detect = HYSTART_ACK_TRAIN | HYSTART_DELAY;
50 static int hystart_low_window = 16;
51 static int hystart_ack_delta_us = 2000;
52 
53 static const __u32 cube_rtt_scale = (bic_scale * 10);	/* 1024*c/rtt */
54 static const __u32 beta_scale = 8*(BICTCP_BETA_SCALE+beta) / 3
55 				/ (BICTCP_BETA_SCALE - beta);
56 /* calculate the "K" for (wmax-cwnd) = c/rtt * K^3
57  *  so K = cubic_root( (wmax-cwnd)*rtt/c )
58  * the unit of K is bictcp_HZ=2^10, not HZ
59  *
60  *  c = bic_scale >> 10
61  *  rtt = 100ms
62  *
63  * the following code has been designed and tested for
64  * cwnd < 1 million packets
65  * RTT < 100 seconds
66  * HZ < 1,000,00  (corresponding to 10 nano-second)
67  */
68 
69 /* 1/c * 2^2*bictcp_HZ * srtt, 2^40 */
70 static const __u64 cube_factor = (__u64)(1ull << (10+3*BICTCP_HZ))
71 				/ (bic_scale * 10);
72 
73 /* BIC TCP Parameters */
74 struct bpf_bictcp {
75 	__u32	cnt;		/* increase cwnd by 1 after ACKs */
76 	__u32	last_max_cwnd;	/* last maximum snd_cwnd */
77 	__u32	last_cwnd;	/* the last snd_cwnd */
78 	__u32	last_time;	/* time when updated last_cwnd */
79 	__u32	bic_origin_point;/* origin point of bic function */
80 	__u32	bic_K;		/* time to origin point
81 				   from the beginning of the current epoch */
82 	__u32	delay_min;	/* min delay (usec) */
83 	__u32	epoch_start;	/* beginning of an epoch */
84 	__u32	ack_cnt;	/* number of acks */
85 	__u32	tcp_cwnd;	/* estimated tcp cwnd */
86 	__u16	unused;
87 	__u8	sample_cnt;	/* number of samples to decide curr_rtt */
88 	__u8	found;		/* the exit point is found? */
89 	__u32	round_start;	/* beginning of each round */
90 	__u32	end_seq;	/* end_seq of the round */
91 	__u32	last_ack;	/* last time when the ACK spacing is close */
92 	__u32	curr_rtt;	/* the minimum rtt of current round */
93 };
94 
95 static void bictcp_reset(struct bpf_bictcp *ca)
96 {
97 	ca->cnt = 0;
98 	ca->last_max_cwnd = 0;
99 	ca->last_cwnd = 0;
100 	ca->last_time = 0;
101 	ca->bic_origin_point = 0;
102 	ca->bic_K = 0;
103 	ca->delay_min = 0;
104 	ca->epoch_start = 0;
105 	ca->ack_cnt = 0;
106 	ca->tcp_cwnd = 0;
107 	ca->found = 0;
108 }
109 
110 extern unsigned long CONFIG_HZ __kconfig;
111 #define HZ CONFIG_HZ
112 #define USEC_PER_MSEC	1000UL
113 #define USEC_PER_SEC	1000000UL
114 #define USEC_PER_JIFFY	(USEC_PER_SEC / HZ)
115 
116 static __u64 div64_u64(__u64 dividend, __u64 divisor)
117 {
118 	return dividend / divisor;
119 }
120 
121 #define div64_ul div64_u64
122 
123 #define BITS_PER_U64 (sizeof(__u64) * 8)
124 static int fls64(__u64 x)
125 {
126 	int num = BITS_PER_U64 - 1;
127 
128 	if (x == 0)
129 		return 0;
130 
131 	if (!(x & (~0ull << (BITS_PER_U64-32)))) {
132 		num -= 32;
133 		x <<= 32;
134 	}
135 	if (!(x & (~0ull << (BITS_PER_U64-16)))) {
136 		num -= 16;
137 		x <<= 16;
138 	}
139 	if (!(x & (~0ull << (BITS_PER_U64-8)))) {
140 		num -= 8;
141 		x <<= 8;
142 	}
143 	if (!(x & (~0ull << (BITS_PER_U64-4)))) {
144 		num -= 4;
145 		x <<= 4;
146 	}
147 	if (!(x & (~0ull << (BITS_PER_U64-2)))) {
148 		num -= 2;
149 		x <<= 2;
150 	}
151 	if (!(x & (~0ull << (BITS_PER_U64-1))))
152 		num -= 1;
153 
154 	return num + 1;
155 }
156 
157 static __u32 bictcp_clock_us(const struct sock *sk)
158 {
159 	return tcp_sk(sk)->tcp_mstamp;
160 }
161 
162 static void bictcp_hystart_reset(struct sock *sk)
163 {
164 	struct tcp_sock *tp = tcp_sk(sk);
165 	struct bpf_bictcp *ca = inet_csk_ca(sk);
166 
167 	ca->round_start = ca->last_ack = bictcp_clock_us(sk);
168 	ca->end_seq = tp->snd_nxt;
169 	ca->curr_rtt = ~0U;
170 	ca->sample_cnt = 0;
171 }
172 
173 SEC("struct_ops")
174 void BPF_PROG(bpf_cubic_init, struct sock *sk)
175 {
176 	struct bpf_bictcp *ca = inet_csk_ca(sk);
177 
178 	bictcp_reset(ca);
179 
180 	if (hystart)
181 		bictcp_hystart_reset(sk);
182 
183 	if (!hystart && initial_ssthresh)
184 		tcp_sk(sk)->snd_ssthresh = initial_ssthresh;
185 }
186 
187 SEC("struct_ops")
188 void BPF_PROG(bpf_cubic_cwnd_event_tx_start, struct sock *sk)
189 {
190 	struct bpf_bictcp *ca = inet_csk_ca(sk);
191 	__u32 now = tcp_jiffies32;
192 	__s32 delta;
193 
194 	delta = now - tcp_sk(sk)->lsndtime;
195 
196 	/* We were application limited (idle) for a while.
197 	 * Shift epoch_start to keep cwnd growth to cubic curve.
198 	 */
199 	if (ca->epoch_start && delta > 0) {
200 		ca->epoch_start += delta;
201 		if (after(ca->epoch_start, now))
202 			ca->epoch_start = now;
203 	}
204 }
205 
206 /*
207  * cbrt(x) MSB values for x MSB values in [0..63].
208  * Precomputed then refined by hand - Willy Tarreau
209  *
210  * For x in [0..63],
211  *   v = cbrt(x << 18) - 1
212  *   cbrt(x) = (v[x] + 10) >> 6
213  */
214 static const __u8 v[] = {
215 	/* 0x00 */    0,   54,   54,   54,  118,  118,  118,  118,
216 	/* 0x08 */  123,  129,  134,  138,  143,  147,  151,  156,
217 	/* 0x10 */  157,  161,  164,  168,  170,  173,  176,  179,
218 	/* 0x18 */  181,  185,  187,  190,  192,  194,  197,  199,
219 	/* 0x20 */  200,  202,  204,  206,  209,  211,  213,  215,
220 	/* 0x28 */  217,  219,  221,  222,  224,  225,  227,  229,
221 	/* 0x30 */  231,  232,  234,  236,  237,  239,  240,  242,
222 	/* 0x38 */  244,  245,  246,  248,  250,  251,  252,  254,
223 };
224 
225 /* calculate the cubic root of x using a table lookup followed by one
226  * Newton-Raphson iteration.
227  * Avg err ~= 0.195%
228  */
229 static __u32 cubic_root(__u64 a)
230 {
231 	__u32 x, b, shift;
232 
233 	if (a < 64) {
234 		/* a in [0..63] */
235 		return ((__u32)v[(__u32)a] + 35) >> 6;
236 	}
237 
238 	b = fls64(a);
239 	b = ((b * 84) >> 8) - 1;
240 	shift = (a >> (b * 3));
241 
242 	/* it is needed for verifier's bound check on v */
243 	if (shift >= 64)
244 		return 0;
245 
246 	x = ((__u32)(((__u32)v[shift] + 10) << b)) >> 6;
247 
248 	/*
249 	 * Newton-Raphson iteration
250 	 *                         2
251 	 * x    = ( 2 * x  +  a / x  ) / 3
252 	 *  k+1          k         k
253 	 */
254 	x = (2 * x + (__u32)div64_u64(a, (__u64)x * (__u64)(x - 1)));
255 	x = ((x * 341) >> 10);
256 	return x;
257 }
258 
259 /*
260  * Compute congestion window to use.
261  */
262 static void bictcp_update(struct bpf_bictcp *ca, __u32 cwnd, __u32 acked)
263 {
264 	__u32 delta, bic_target, max_cnt;
265 	__u64 offs, t;
266 
267 	ca->ack_cnt += acked;	/* count the number of ACKed packets */
268 
269 	if (ca->last_cwnd == cwnd &&
270 	    (__s32)(tcp_jiffies32 - ca->last_time) <= HZ / 32)
271 		return;
272 
273 	/* The CUBIC function can update ca->cnt at most once per jiffy.
274 	 * On all cwnd reduction events, ca->epoch_start is set to 0,
275 	 * which will force a recalculation of ca->cnt.
276 	 */
277 	if (ca->epoch_start && tcp_jiffies32 == ca->last_time)
278 		goto tcp_friendliness;
279 
280 	ca->last_cwnd = cwnd;
281 	ca->last_time = tcp_jiffies32;
282 
283 	if (ca->epoch_start == 0) {
284 		ca->epoch_start = tcp_jiffies32;	/* record beginning */
285 		ca->ack_cnt = acked;			/* start counting */
286 		ca->tcp_cwnd = cwnd;			/* syn with cubic */
287 
288 		if (ca->last_max_cwnd <= cwnd) {
289 			ca->bic_K = 0;
290 			ca->bic_origin_point = cwnd;
291 		} else {
292 			/* Compute new K based on
293 			 * (wmax-cwnd) * (srtt>>3 / HZ) / c * 2^(3*bictcp_HZ)
294 			 */
295 			ca->bic_K = cubic_root(cube_factor
296 					       * (ca->last_max_cwnd - cwnd));
297 			ca->bic_origin_point = ca->last_max_cwnd;
298 		}
299 	}
300 
301 	/* cubic function - calc*/
302 	/* calculate c * time^3 / rtt,
303 	 *  while considering overflow in calculation of time^3
304 	 * (so time^3 is done by using 64 bit)
305 	 * and without the support of division of 64bit numbers
306 	 * (so all divisions are done by using 32 bit)
307 	 *  also NOTE the unit of those variables
308 	 *	  time  = (t - K) / 2^bictcp_HZ
309 	 *	  c = bic_scale >> 10
310 	 * rtt  = (srtt >> 3) / HZ
311 	 * !!! The following code does not have overflow problems,
312 	 * if the cwnd < 1 million packets !!!
313 	 */
314 
315 	t = (__s32)(tcp_jiffies32 - ca->epoch_start) * USEC_PER_JIFFY;
316 	t += ca->delay_min;
317 	/* change the unit from usec to bictcp_HZ */
318 	t <<= BICTCP_HZ;
319 	t /= USEC_PER_SEC;
320 
321 	if (t < ca->bic_K)		/* t - K */
322 		offs = ca->bic_K - t;
323 	else
324 		offs = t - ca->bic_K;
325 
326 	/* c/rtt * (t-K)^3 */
327 	delta = (cube_rtt_scale * offs * offs * offs) >> (10+3*BICTCP_HZ);
328 	if (t < ca->bic_K)                            /* below origin*/
329 		bic_target = ca->bic_origin_point - delta;
330 	else                                          /* above origin*/
331 		bic_target = ca->bic_origin_point + delta;
332 
333 	/* cubic function - calc bictcp_cnt*/
334 	if (bic_target > cwnd) {
335 		ca->cnt = cwnd / (bic_target - cwnd);
336 	} else {
337 		ca->cnt = 100 * cwnd;              /* very small increment*/
338 	}
339 
340 	/*
341 	 * The initial growth of cubic function may be too conservative
342 	 * when the available bandwidth is still unknown.
343 	 */
344 	if (ca->last_max_cwnd == 0 && ca->cnt > 20)
345 		ca->cnt = 20;	/* increase cwnd 5% per RTT */
346 
347 tcp_friendliness:
348 	/* TCP Friendly */
349 	if (tcp_friendliness) {
350 		__u32 scale = beta_scale;
351 		__u32 n;
352 
353 		/* update tcp cwnd */
354 		delta = (cwnd * scale) >> 3;
355 		if (ca->ack_cnt > delta && delta) {
356 			n = ca->ack_cnt / delta;
357 			ca->ack_cnt -= n * delta;
358 			ca->tcp_cwnd += n;
359 		}
360 
361 		if (ca->tcp_cwnd > cwnd) {	/* if bic is slower than tcp */
362 			delta = ca->tcp_cwnd - cwnd;
363 			max_cnt = cwnd / delta;
364 			if (ca->cnt > max_cnt)
365 				ca->cnt = max_cnt;
366 		}
367 	}
368 
369 	/* The maximum rate of cwnd increase CUBIC allows is 1 packet per
370 	 * 2 packets ACKed, meaning cwnd grows at 1.5x per RTT.
371 	 */
372 	ca->cnt = max(ca->cnt, 2U);
373 }
374 
375 SEC("struct_ops")
376 void BPF_PROG(bpf_cubic_cong_avoid, struct sock *sk, __u32 ack, __u32 acked)
377 {
378 	struct tcp_sock *tp = tcp_sk(sk);
379 	struct bpf_bictcp *ca = inet_csk_ca(sk);
380 
381 	if (!tcp_is_cwnd_limited(sk))
382 		return;
383 
384 	if (tcp_in_slow_start(tp)) {
385 		if (hystart && after(ack, ca->end_seq))
386 			bictcp_hystart_reset(sk);
387 		acked = tcp_slow_start(tp, acked);
388 		if (!acked)
389 			return;
390 	}
391 	bictcp_update(ca, tp->snd_cwnd, acked);
392 	tcp_cong_avoid_ai(tp, ca->cnt, acked);
393 }
394 
395 SEC("struct_ops")
396 __u32 BPF_PROG(bpf_cubic_recalc_ssthresh, struct sock *sk)
397 {
398 	const struct tcp_sock *tp = tcp_sk(sk);
399 	struct bpf_bictcp *ca = inet_csk_ca(sk);
400 
401 	ca->epoch_start = 0;	/* end of epoch */
402 
403 	/* Wmax and fast convergence */
404 	if (tp->snd_cwnd < ca->last_max_cwnd && fast_convergence)
405 		ca->last_max_cwnd = (tp->snd_cwnd * (BICTCP_BETA_SCALE + beta))
406 			/ (2 * BICTCP_BETA_SCALE);
407 	else
408 		ca->last_max_cwnd = tp->snd_cwnd;
409 
410 	return max((tp->snd_cwnd * beta) / BICTCP_BETA_SCALE, 2U);
411 }
412 
413 SEC("struct_ops")
414 void BPF_PROG(bpf_cubic_state, struct sock *sk, __u8 new_state)
415 {
416 	if (new_state == TCP_CA_Loss) {
417 		bictcp_reset(inet_csk_ca(sk));
418 		bictcp_hystart_reset(sk);
419 	}
420 }
421 
422 #define GSO_MAX_SIZE		65536
423 
424 /* Account for TSO/GRO delays.
425  * Otherwise short RTT flows could get too small ssthresh, since during
426  * slow start we begin with small TSO packets and ca->delay_min would
427  * not account for long aggregation delay when TSO packets get bigger.
428  * Ideally even with a very small RTT we would like to have at least one
429  * TSO packet being sent and received by GRO, and another one in qdisc layer.
430  * We apply another 100% factor because @rate is doubled at this point.
431  * We cap the cushion to 1ms.
432  */
433 static __u32 hystart_ack_delay(struct sock *sk)
434 {
435 	unsigned long rate;
436 
437 	rate = sk->sk_pacing_rate;
438 	if (!rate)
439 		return 0;
440 	return min((__u64)USEC_PER_MSEC,
441 		   div64_ul((__u64)GSO_MAX_SIZE * 4 * USEC_PER_SEC, rate));
442 }
443 
444 static void hystart_update(struct sock *sk, __u32 delay)
445 {
446 	struct tcp_sock *tp = tcp_sk(sk);
447 	struct bpf_bictcp *ca = inet_csk_ca(sk);
448 	__u32 threshold;
449 
450 	if (hystart_detect & HYSTART_ACK_TRAIN) {
451 		__u32 now = bictcp_clock_us(sk);
452 
453 		/* first detection parameter - ack-train detection */
454 		if ((__s32)(now - ca->last_ack) <= hystart_ack_delta_us) {
455 			ca->last_ack = now;
456 
457 			threshold = ca->delay_min + hystart_ack_delay(sk);
458 
459 			/* Hystart ack train triggers if we get ack past
460 			 * ca->delay_min/2.
461 			 * Pacing might have delayed packets up to RTT/2
462 			 * during slow start.
463 			 */
464 			if (sk->sk_pacing_status == SK_PACING_NONE)
465 				threshold >>= 1;
466 
467 			if ((__s32)(now - ca->round_start) > threshold) {
468 				ca->found = 1;
469 				tp->snd_ssthresh = tp->snd_cwnd;
470 			}
471 		}
472 	}
473 
474 	if (hystart_detect & HYSTART_DELAY) {
475 		/* obtain the minimum delay of more than sampling packets */
476 		if (ca->curr_rtt > delay)
477 			ca->curr_rtt = delay;
478 		if (ca->sample_cnt < HYSTART_MIN_SAMPLES) {
479 			ca->sample_cnt++;
480 		} else {
481 			if (ca->curr_rtt > ca->delay_min +
482 			    HYSTART_DELAY_THRESH(ca->delay_min >> 3)) {
483 				ca->found = 1;
484 				tp->snd_ssthresh = tp->snd_cwnd;
485 			}
486 		}
487 	}
488 }
489 
490 int bpf_cubic_acked_called = 0;
491 
492 SEC("struct_ops")
493 void BPF_PROG(bpf_cubic_acked, struct sock *sk, const struct ack_sample *sample)
494 {
495 	const struct tcp_sock *tp = tcp_sk(sk);
496 	struct bpf_bictcp *ca = inet_csk_ca(sk);
497 	__u32 delay;
498 
499 	bpf_cubic_acked_called = 1;
500 	/* Some calls are for duplicates without timestamps */
501 	if (sample->rtt_us < 0)
502 		return;
503 
504 	/* Discard delay samples right after fast recovery */
505 	if (ca->epoch_start && (__s32)(tcp_jiffies32 - ca->epoch_start) < HZ)
506 		return;
507 
508 	delay = sample->rtt_us;
509 	if (delay == 0)
510 		delay = 1;
511 
512 	/* first time call or link delay decreases */
513 	if (ca->delay_min == 0 || ca->delay_min > delay)
514 		ca->delay_min = delay;
515 
516 	/* hystart triggers when cwnd is larger than some threshold */
517 	if (!ca->found && tcp_in_slow_start(tp) && hystart &&
518 	    tp->snd_cwnd >= hystart_low_window)
519 		hystart_update(sk, delay);
520 }
521 
522 extern __u32 tcp_reno_undo_cwnd(struct sock *sk) __ksym;
523 
524 SEC("struct_ops")
525 __u32 BPF_PROG(bpf_cubic_undo_cwnd, struct sock *sk)
526 {
527 	return tcp_reno_undo_cwnd(sk);
528 }
529 
530 SEC(".struct_ops")
531 struct tcp_congestion_ops cubic = {
532 	.init		= (void *)bpf_cubic_init,
533 	.ssthresh	= (void *)bpf_cubic_recalc_ssthresh,
534 	.cong_avoid	= (void *)bpf_cubic_cong_avoid,
535 	.set_state	= (void *)bpf_cubic_state,
536 	.undo_cwnd	= (void *)bpf_cubic_undo_cwnd,
537 	.cwnd_event_tx_start	= (void *)bpf_cubic_cwnd_event_tx_start,
538 	.pkts_acked     = (void *)bpf_cubic_acked,
539 	.name		= "bpf_cubic",
540 };
541