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