xref: /linux/net/ipv4/tcp_bbr.c (revision 4ce06406958b67fdddcc2e6948237dd6ff6ba112)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Bottleneck Bandwidth and RTT (BBR) congestion control
3  *
4  * BBR congestion control computes the sending rate based on the delivery
5  * rate (throughput) estimated from ACKs. In a nutshell:
6  *
7  *   On each ACK, update our model of the network path:
8  *      bottleneck_bandwidth = windowed_max(delivered / elapsed, 10 round trips)
9  *      min_rtt = windowed_min(rtt, 10 seconds)
10  *   pacing_rate = pacing_gain * bottleneck_bandwidth
11  *   cwnd = max(cwnd_gain * bottleneck_bandwidth * min_rtt, 4)
12  *
13  * The core algorithm does not react directly to packet losses or delays,
14  * although BBR may adjust the size of next send per ACK when loss is
15  * observed, or adjust the sending rate if it estimates there is a
16  * traffic policer, in order to keep the drop rate reasonable.
17  *
18  * Here is a state transition diagram for BBR:
19  *
20  *             |
21  *             V
22  *    +---> STARTUP  ----+
23  *    |        |         |
24  *    |        V         |
25  *    |      DRAIN   ----+
26  *    |        |         |
27  *    |        V         |
28  *    +---> PROBE_BW ----+
29  *    |      ^    |      |
30  *    |      |    |      |
31  *    |      +----+      |
32  *    |                  |
33  *    +---- PROBE_RTT <--+
34  *
35  * A BBR flow starts in STARTUP, and ramps up its sending rate quickly.
36  * When it estimates the pipe is full, it enters DRAIN to drain the queue.
37  * In steady state a BBR flow only uses PROBE_BW and PROBE_RTT.
38  * A long-lived BBR flow spends the vast majority of its time remaining
39  * (repeatedly) in PROBE_BW, fully probing and utilizing the pipe's bandwidth
40  * in a fair manner, with a small, bounded queue. *If* a flow has been
41  * continuously sending for the entire min_rtt window, and hasn't seen an RTT
42  * sample that matches or decreases its min_rtt estimate for 10 seconds, then
43  * it briefly enters PROBE_RTT to cut inflight to a minimum value to re-probe
44  * the path's two-way propagation delay (min_rtt). When exiting PROBE_RTT, if
45  * we estimated that we reached the full bw of the pipe then we enter PROBE_BW;
46  * otherwise we enter STARTUP to try to fill the pipe.
47  *
48  * BBR is described in detail in:
49  *   "BBR: Congestion-Based Congestion Control",
50  *   Neal Cardwell, Yuchung Cheng, C. Stephen Gunn, Soheil Hassas Yeganeh,
51  *   Van Jacobson. ACM Queue, Vol. 14 No. 5, September-October 2016.
52  *
53  * There is a public e-mail list for discussing BBR development and testing:
54  *   https://groups.google.com/forum/#!forum/bbr-dev
55  *
56  * NOTE: BBR might be used with the fq qdisc ("man tc-fq") with pacing enabled,
57  * otherwise TCP stack falls back to an internal pacing using one high
58  * resolution timer per TCP socket and may use more resources.
59  */
60 #include <linux/btf.h>
61 #include <linux/btf_ids.h>
62 #include <linux/module.h>
63 #include <net/tcp.h>
64 #include <linux/inet_diag.h>
65 #include <linux/inet.h>
66 #include <linux/random.h>
67 #include <linux/win_minmax.h>
68 
69 /* Scale factor for rate in pkt/uSec unit to avoid truncation in bandwidth
70  * estimation. The rate unit ~= (1500 bytes / 1 usec / 2^24) ~= 715 bps.
71  * This handles bandwidths from 0.06pps (715bps) to 256Mpps (3Tbps) in a u32.
72  * Since the minimum window is >=4 packets, the lower bound isn't
73  * an issue. The upper bound isn't an issue with existing technologies.
74  */
75 #define BW_SCALE 24
76 #define BW_UNIT (1 << BW_SCALE)
77 
78 #define BBR_SCALE 8	/* scaling factor for fractions in BBR (e.g. gains) */
79 #define BBR_UNIT (1 << BBR_SCALE)
80 
81 /* BBR has the following modes for deciding how fast to send: */
82 enum bbr_mode {
83 	BBR_STARTUP,	/* ramp up sending rate rapidly to fill pipe */
84 	BBR_DRAIN,	/* drain any queue created during startup */
85 	BBR_PROBE_BW,	/* discover, share bw: pace around estimated bw */
86 	BBR_PROBE_RTT,	/* cut inflight to min to probe min_rtt */
87 };
88 
89 /* BBR congestion control block */
90 struct bbr {
91 	u32	min_rtt_us;	        /* min RTT in min_rtt_win_sec window */
92 	u32	min_rtt_stamp;	        /* timestamp of min_rtt_us */
93 	u32	probe_rtt_done_stamp;   /* end time for BBR_PROBE_RTT mode */
94 	struct minmax bw;	/* Max recent delivery rate in pkts/uS << 24 */
95 	u32	rtt_cnt;	    /* count of packet-timed rounds elapsed */
96 	u32     next_rtt_delivered; /* scb->tx.delivered at end of round */
97 	u64	cycle_mstamp;	     /* time of this cycle phase start */
98 	u32     mode:3,		     /* current bbr_mode in state machine */
99 		prev_ca_state:3,     /* CA state on previous ACK */
100 		packet_conservation:1,  /* use packet conservation? */
101 		round_start:1,	     /* start of packet-timed tx->ack round? */
102 		idle_restart:1,	     /* restarting after idle? */
103 		probe_rtt_round_done:1,  /* a BBR_PROBE_RTT round at 4 pkts? */
104 		unused:13,
105 		lt_is_sampling:1,    /* taking long-term ("LT") samples now? */
106 		lt_rtt_cnt:7,	     /* round trips in long-term interval */
107 		lt_use_bw:1;	     /* use lt_bw as our bw estimate? */
108 	u32	lt_bw;		     /* LT est delivery rate in pkts/uS << 24 */
109 	u32	lt_last_delivered;   /* LT intvl start: tp->delivered */
110 	u32	lt_last_stamp;	     /* LT intvl start: tp->delivered_mstamp */
111 	u32	lt_last_lost;	     /* LT intvl start: tp->lost */
112 	u32	pacing_gain:10,	/* current gain for setting pacing rate */
113 		cwnd_gain:10,	/* current gain for setting cwnd */
114 		full_bw_reached:1,   /* reached full bw in Startup? */
115 		full_bw_cnt:2,	/* number of rounds without large bw gains */
116 		cycle_idx:3,	/* current index in pacing_gain cycle array */
117 		has_seen_rtt:1, /* have we seen an RTT sample yet? */
118 		unused_b:5;
119 	u32	prior_cwnd;	/* prior cwnd upon entering loss recovery */
120 	u32	full_bw;	/* recent bw, to estimate if pipe is full */
121 
122 	/* For tracking ACK aggregation: */
123 	u64	ack_epoch_mstamp;	/* start of ACK sampling epoch */
124 	u16	extra_acked[2];		/* max excess data ACKed in epoch */
125 	u32	ack_epoch_acked:20,	/* packets (S)ACKed in sampling epoch */
126 		extra_acked_win_rtts:5,	/* age of extra_acked, in round trips */
127 		extra_acked_win_idx:1,	/* current index in extra_acked array */
128 		unused_c:6;
129 };
130 
131 #define CYCLE_LEN	8	/* number of phases in a pacing gain cycle */
132 
133 /* Window length of bw filter (in rounds): */
134 static const int bbr_bw_rtts = CYCLE_LEN + 2;
135 /* Window length of min_rtt filter (in sec): */
136 static const u32 bbr_min_rtt_win_sec = 10;
137 /* Minimum time (in ms) spent at bbr_cwnd_min_target in BBR_PROBE_RTT mode: */
138 static const u32 bbr_probe_rtt_mode_ms = 200;
139 /* Skip TSO below the following bandwidth (bits/sec): */
140 static const int bbr_min_tso_rate = 1200000;
141 
142 /* Pace at ~1% below estimated bw, on average, to reduce queue at bottleneck.
143  * In order to help drive the network toward lower queues and low latency while
144  * maintaining high utilization, the average pacing rate aims to be slightly
145  * lower than the estimated bandwidth. This is an important aspect of the
146  * design.
147  */
148 static const int bbr_pacing_margin_percent = 1;
149 
150 /* We use a high_gain value of 2/ln(2) because it's the smallest pacing gain
151  * that will allow a smoothly increasing pacing rate that will double each RTT
152  * and send the same number of packets per RTT that an un-paced, slow-starting
153  * Reno or CUBIC flow would:
154  */
155 static const int bbr_high_gain  = BBR_UNIT * 2885 / 1000 + 1;
156 /* The pacing gain of 1/high_gain in BBR_DRAIN is calculated to typically drain
157  * the queue created in BBR_STARTUP in a single round:
158  */
159 static const int bbr_drain_gain = BBR_UNIT * 1000 / 2885;
160 /* The gain for deriving steady-state cwnd tolerates delayed/stretched ACKs: */
161 static const int bbr_cwnd_gain  = BBR_UNIT * 2;
162 /* The pacing_gain values for the PROBE_BW gain cycle, to discover/share bw: */
163 static const int bbr_pacing_gain[] = {
164 	BBR_UNIT * 5 / 4,	/* probe for more available bw */
165 	BBR_UNIT * 3 / 4,	/* drain queue and/or yield bw to other flows */
166 	BBR_UNIT, BBR_UNIT, BBR_UNIT,	/* cruise at 1.0*bw to utilize pipe, */
167 	BBR_UNIT, BBR_UNIT, BBR_UNIT	/* without creating excess queue... */
168 };
169 /* Randomize the starting gain cycling phase over N phases: */
170 static const u32 bbr_cycle_rand = 7;
171 
172 /* Try to keep at least this many packets in flight, if things go smoothly. For
173  * smooth functioning, a sliding window protocol ACKing every other packet
174  * needs at least 4 packets in flight:
175  */
176 static const u32 bbr_cwnd_min_target = 4;
177 
178 /* To estimate if BBR_STARTUP mode (i.e. high_gain) has filled pipe... */
179 /* If bw has increased significantly (1.25x), there may be more bw available: */
180 static const u32 bbr_full_bw_thresh = BBR_UNIT * 5 / 4;
181 /* But after 3 rounds w/o significant bw growth, estimate pipe is full: */
182 static const u32 bbr_full_bw_cnt = 3;
183 
184 /* "long-term" ("LT") bandwidth estimator parameters... */
185 /* The minimum number of rounds in an LT bw sampling interval: */
186 static const u32 bbr_lt_intvl_min_rtts = 4;
187 /* If lost/delivered ratio > 20%, interval is "lossy" and we may be policed: */
188 static const u32 bbr_lt_loss_thresh = 50;
189 /* If 2 intervals have a bw ratio <= 1/8, their bw is "consistent": */
190 static const u32 bbr_lt_bw_ratio = BBR_UNIT / 8;
191 /* If 2 intervals have a bw diff <= 4 Kbit/sec their bw is "consistent": */
192 static const u32 bbr_lt_bw_diff = 4000 / 8;
193 /* If we estimate we're policed, use lt_bw for this many round trips: */
194 static const u32 bbr_lt_bw_max_rtts = 48;
195 
196 /* Gain factor for adding extra_acked to target cwnd: */
197 static const int bbr_extra_acked_gain = BBR_UNIT;
198 /* Window length of extra_acked window. */
199 static const u32 bbr_extra_acked_win_rtts = 5;
200 /* Max allowed val for ack_epoch_acked, after which sampling epoch is reset */
201 static const u32 bbr_ack_epoch_acked_reset_thresh = 1U << 20;
202 /* Time period for clamping cwnd increment due to ack aggregation */
203 static const u32 bbr_extra_acked_max_us = 100 * 1000;
204 
205 static void bbr_check_probe_rtt_done(struct sock *sk);
206 
207 /* Do we estimate that STARTUP filled the pipe? */
208 static bool bbr_full_bw_reached(const struct sock *sk)
209 {
210 	const struct bbr *bbr = inet_csk_ca(sk);
211 
212 	return bbr->full_bw_reached;
213 }
214 
215 /* Return the windowed max recent bandwidth sample, in pkts/uS << BW_SCALE. */
216 static u32 bbr_max_bw(const struct sock *sk)
217 {
218 	struct bbr *bbr = inet_csk_ca(sk);
219 
220 	return minmax_get(&bbr->bw);
221 }
222 
223 /* Return the estimated bandwidth of the path, in pkts/uS << BW_SCALE. */
224 static u32 bbr_bw(const struct sock *sk)
225 {
226 	struct bbr *bbr = inet_csk_ca(sk);
227 
228 	return bbr->lt_use_bw ? bbr->lt_bw : bbr_max_bw(sk);
229 }
230 
231 /* Return maximum extra acked in past k-2k round trips,
232  * where k = bbr_extra_acked_win_rtts.
233  */
234 static u16 bbr_extra_acked(const struct sock *sk)
235 {
236 	struct bbr *bbr = inet_csk_ca(sk);
237 
238 	return max(bbr->extra_acked[0], bbr->extra_acked[1]);
239 }
240 
241 /* Return rate in bytes per second, optionally with a gain.
242  * The order here is chosen carefully to avoid overflow of u64. This should
243  * work for input rates of up to 2.9Tbit/sec and gain of 2.89x.
244  */
245 static u64 bbr_rate_bytes_per_sec(struct sock *sk, u64 rate, int gain)
246 {
247 	unsigned int mss = tcp_sk(sk)->mss_cache;
248 
249 	rate *= mss;
250 	rate *= gain;
251 	rate >>= BBR_SCALE;
252 	rate *= USEC_PER_SEC / 100 * (100 - bbr_pacing_margin_percent);
253 	return rate >> BW_SCALE;
254 }
255 
256 /* Convert a BBR bw and gain factor to a pacing rate in bytes per second. */
257 static unsigned long bbr_bw_to_pacing_rate(struct sock *sk, u32 bw, int gain)
258 {
259 	u64 rate = bw;
260 
261 	rate = bbr_rate_bytes_per_sec(sk, rate, gain);
262 	rate = min_t(u64, rate, READ_ONCE(sk->sk_max_pacing_rate));
263 	return rate;
264 }
265 
266 /* Initialize pacing rate to: high_gain * init_cwnd / RTT. */
267 static void bbr_init_pacing_rate_from_rtt(struct sock *sk)
268 {
269 	struct tcp_sock *tp = tcp_sk(sk);
270 	struct bbr *bbr = inet_csk_ca(sk);
271 	u64 bw;
272 	u32 rtt_us;
273 
274 	if (tp->srtt_us) {		/* any RTT sample yet? */
275 		rtt_us = max(tp->srtt_us >> 3, 1U);
276 		bbr->has_seen_rtt = 1;
277 	} else {			 /* no RTT sample yet */
278 		rtt_us = USEC_PER_MSEC;	 /* use nominal default RTT */
279 	}
280 	bw = (u64)tcp_snd_cwnd(tp) * BW_UNIT;
281 	do_div(bw, rtt_us);
282 	WRITE_ONCE(sk->sk_pacing_rate,
283 		   bbr_bw_to_pacing_rate(sk, bw, bbr_high_gain));
284 }
285 
286 /* Pace using current bw estimate and a gain factor. */
287 static void bbr_set_pacing_rate(struct sock *sk, u32 bw, int gain)
288 {
289 	struct tcp_sock *tp = tcp_sk(sk);
290 	struct bbr *bbr = inet_csk_ca(sk);
291 	unsigned long rate = bbr_bw_to_pacing_rate(sk, bw, gain);
292 
293 	if (unlikely(!bbr->has_seen_rtt && tp->srtt_us))
294 		bbr_init_pacing_rate_from_rtt(sk);
295 	if (bbr_full_bw_reached(sk) || rate > READ_ONCE(sk->sk_pacing_rate))
296 		WRITE_ONCE(sk->sk_pacing_rate, rate);
297 }
298 
299 /* override sysctl_tcp_min_tso_segs */
300 __bpf_kfunc static u32 bbr_min_tso_segs(struct sock *sk)
301 {
302 	return READ_ONCE(sk->sk_pacing_rate) < (bbr_min_tso_rate >> 3) ? 1 : 2;
303 }
304 
305 static u32 bbr_tso_segs_goal(struct sock *sk)
306 {
307 	struct tcp_sock *tp = tcp_sk(sk);
308 	u32 segs, bytes;
309 
310 	/* Sort of tcp_tso_autosize() but ignoring
311 	 * driver provided sk_gso_max_size.
312 	 */
313 	bytes = min_t(unsigned long,
314 		      READ_ONCE(sk->sk_pacing_rate) >> READ_ONCE(sk->sk_pacing_shift),
315 		      GSO_LEGACY_MAX_SIZE - 1 - MAX_TCP_HEADER);
316 	segs = max_t(u32, bytes / tp->mss_cache, bbr_min_tso_segs(sk));
317 
318 	return min(segs, 0x7FU);
319 }
320 
321 /* Save "last known good" cwnd so we can restore it after losses or PROBE_RTT */
322 static void bbr_save_cwnd(struct sock *sk)
323 {
324 	struct tcp_sock *tp = tcp_sk(sk);
325 	struct bbr *bbr = inet_csk_ca(sk);
326 
327 	if (bbr->prev_ca_state < TCP_CA_Recovery && bbr->mode != BBR_PROBE_RTT)
328 		bbr->prior_cwnd = tcp_snd_cwnd(tp);  /* this cwnd is good enough */
329 	else  /* loss recovery or BBR_PROBE_RTT have temporarily cut cwnd */
330 		bbr->prior_cwnd = max(bbr->prior_cwnd, tcp_snd_cwnd(tp));
331 }
332 
333 __bpf_kfunc static void bbr_cwnd_event_tx_start(struct sock *sk)
334 {
335 	struct tcp_sock *tp = tcp_sk(sk);
336 	struct bbr *bbr = inet_csk_ca(sk);
337 
338 	if (tp->app_limited) {
339 		bbr->idle_restart = 1;
340 		bbr->ack_epoch_mstamp = tp->tcp_mstamp;
341 		bbr->ack_epoch_acked = 0;
342 		/* Avoid pointless buffer overflows: pace at est. bw if we don't
343 		 * need more speed (we're restarting from idle and app-limited).
344 		 */
345 		if (bbr->mode == BBR_PROBE_BW)
346 			bbr_set_pacing_rate(sk, bbr_bw(sk), BBR_UNIT);
347 		else if (bbr->mode == BBR_PROBE_RTT)
348 			bbr_check_probe_rtt_done(sk);
349 	}
350 }
351 
352 /* Calculate bdp based on min RTT and the estimated bottleneck bandwidth:
353  *
354  * bdp = ceil(bw * min_rtt * gain)
355  *
356  * The key factor, gain, controls the amount of queue. While a small gain
357  * builds a smaller queue, it becomes more vulnerable to noise in RTT
358  * measurements (e.g., delayed ACKs or other ACK compression effects). This
359  * noise may cause BBR to under-estimate the rate.
360  */
361 static u32 bbr_bdp(struct sock *sk, u32 bw, int gain)
362 {
363 	struct bbr *bbr = inet_csk_ca(sk);
364 	u32 bdp;
365 	u64 w;
366 
367 	/* If we've never had a valid RTT sample, cap cwnd at the initial
368 	 * default. This should only happen when the connection is not using TCP
369 	 * timestamps and has retransmitted all of the SYN/SYNACK/data packets
370 	 * ACKed so far. In this case, an RTO can cut cwnd to 1, in which
371 	 * case we need to slow-start up toward something safe: TCP_INIT_CWND.
372 	 */
373 	if (unlikely(bbr->min_rtt_us == ~0U))	 /* no valid RTT samples yet? */
374 		return TCP_INIT_CWND;  /* be safe: cap at default initial cwnd*/
375 
376 	w = (u64)bw * bbr->min_rtt_us;
377 
378 	/* Apply a gain to the given value, remove the BW_SCALE shift, and
379 	 * round the value up to avoid a negative feedback loop.
380 	 */
381 	bdp = (((w * gain) >> BBR_SCALE) + BW_UNIT - 1) / BW_UNIT;
382 
383 	return bdp;
384 }
385 
386 /* To achieve full performance in high-speed paths, we budget enough cwnd to
387  * fit full-sized skbs in-flight on both end hosts to fully utilize the path:
388  *   - one skb in sending host Qdisc,
389  *   - one skb in sending host TSO/GSO engine
390  *   - one skb being received by receiver host LRO/GRO/delayed-ACK engine
391  * Don't worry, at low rates (bbr_min_tso_rate) this won't bloat cwnd because
392  * in such cases tso_segs_goal is 1. The minimum cwnd is 4 packets,
393  * which allows 2 outstanding 2-packet sequences, to try to keep pipe
394  * full even with ACK-every-other-packet delayed ACKs.
395  */
396 static u32 bbr_quantization_budget(struct sock *sk, u32 cwnd)
397 {
398 	struct bbr *bbr = inet_csk_ca(sk);
399 
400 	/* Allow enough full-sized skbs in flight to utilize end systems. */
401 	cwnd += 3 * bbr_tso_segs_goal(sk);
402 
403 	/* Reduce delayed ACKs by rounding up cwnd to the next even number. */
404 	cwnd = (cwnd + 1) & ~1U;
405 
406 	/* Ensure gain cycling gets inflight above BDP even for small BDPs. */
407 	if (bbr->mode == BBR_PROBE_BW && bbr->cycle_idx == 0)
408 		cwnd += 2;
409 
410 	return cwnd;
411 }
412 
413 /* Find inflight based on min RTT and the estimated bottleneck bandwidth. */
414 static u32 bbr_inflight(struct sock *sk, u32 bw, int gain)
415 {
416 	u32 inflight;
417 
418 	inflight = bbr_bdp(sk, bw, gain);
419 	inflight = bbr_quantization_budget(sk, inflight);
420 
421 	return inflight;
422 }
423 
424 /* With pacing at lower layers, there's often less data "in the network" than
425  * "in flight". With TSQ and departure time pacing at lower layers (e.g. fq),
426  * we often have several skbs queued in the pacing layer with a pre-scheduled
427  * earliest departure time (EDT). BBR adapts its pacing rate based on the
428  * inflight level that it estimates has already been "baked in" by previous
429  * departure time decisions. We calculate a rough estimate of the number of our
430  * packets that might be in the network at the earliest departure time for the
431  * next skb scheduled:
432  *   in_network_at_edt = inflight_at_edt - (EDT - now) * bw
433  * If we're increasing inflight, then we want to know if the transmit of the
434  * EDT skb will push inflight above the target, so inflight_at_edt includes
435  * bbr_tso_segs_goal() from the skb departing at EDT. If decreasing inflight,
436  * then estimate if inflight will sink too low just before the EDT transmit.
437  */
438 static u32 bbr_packets_in_net_at_edt(struct sock *sk, u32 inflight_now)
439 {
440 	struct tcp_sock *tp = tcp_sk(sk);
441 	struct bbr *bbr = inet_csk_ca(sk);
442 	u64 now_ns, edt_ns, interval_us;
443 	u32 interval_delivered, inflight_at_edt;
444 
445 	now_ns = tp->tcp_clock_cache;
446 	edt_ns = max(tp->tcp_wstamp_ns, now_ns);
447 	interval_us = div_u64(edt_ns - now_ns, NSEC_PER_USEC);
448 	interval_delivered = (u64)bbr_bw(sk) * interval_us >> BW_SCALE;
449 	inflight_at_edt = inflight_now;
450 	if (bbr->pacing_gain > BBR_UNIT)              /* increasing inflight */
451 		inflight_at_edt += bbr_tso_segs_goal(sk);  /* include EDT skb */
452 	if (interval_delivered >= inflight_at_edt)
453 		return 0;
454 	return inflight_at_edt - interval_delivered;
455 }
456 
457 /* Find the cwnd increment based on estimate of ack aggregation */
458 static u32 bbr_ack_aggregation_cwnd(struct sock *sk)
459 {
460 	u32 max_aggr_cwnd, aggr_cwnd = 0;
461 
462 	if (bbr_extra_acked_gain && bbr_full_bw_reached(sk)) {
463 		max_aggr_cwnd = ((u64)bbr_bw(sk) * bbr_extra_acked_max_us)
464 				/ BW_UNIT;
465 		aggr_cwnd = (bbr_extra_acked_gain * bbr_extra_acked(sk))
466 			     >> BBR_SCALE;
467 		aggr_cwnd = min(aggr_cwnd, max_aggr_cwnd);
468 	}
469 
470 	return aggr_cwnd;
471 }
472 
473 /* An optimization in BBR to reduce losses: On the first round of recovery, we
474  * follow the packet conservation principle: send P packets per P packets acked.
475  * After that, we slow-start and send at most 2*P packets per P packets acked.
476  * After recovery finishes, or upon undo, we restore the cwnd we had when
477  * recovery started (capped by the target cwnd based on estimated BDP).
478  *
479  * TODO(ycheng/ncardwell): implement a rate-based approach.
480  */
481 static bool bbr_set_cwnd_to_recover_or_restore(
482 	struct sock *sk, const struct rate_sample *rs, u32 acked, u32 *new_cwnd)
483 {
484 	struct tcp_sock *tp = tcp_sk(sk);
485 	struct bbr *bbr = inet_csk_ca(sk);
486 	u8 prev_state = bbr->prev_ca_state, state = inet_csk(sk)->icsk_ca_state;
487 	u32 cwnd = tcp_snd_cwnd(tp);
488 
489 	/* An ACK for P pkts should release at most 2*P packets. We do this
490 	 * in two steps. First, here we deduct the number of lost packets.
491 	 * Then, in bbr_set_cwnd() we slow start up toward the target cwnd.
492 	 */
493 	if (rs->losses > 0)
494 		cwnd = max_t(s32, cwnd - rs->losses, 1);
495 
496 	if (state == TCP_CA_Recovery && prev_state != TCP_CA_Recovery) {
497 		/* Starting 1st round of Recovery, so do packet conservation. */
498 		bbr->packet_conservation = 1;
499 		bbr->next_rtt_delivered = tp->delivered;  /* start round now */
500 		/* Cut unused cwnd from app behavior, TSQ, or TSO deferral: */
501 		cwnd = tcp_packets_in_flight(tp) + acked;
502 	} else if (prev_state >= TCP_CA_Recovery && state < TCP_CA_Recovery) {
503 		/* Exiting loss recovery; restore cwnd saved before recovery. */
504 		cwnd = max(cwnd, bbr->prior_cwnd);
505 		bbr->packet_conservation = 0;
506 	}
507 	bbr->prev_ca_state = state;
508 
509 	if (bbr->packet_conservation) {
510 		*new_cwnd = max(cwnd, tcp_packets_in_flight(tp) + acked);
511 		return true;	/* yes, using packet conservation */
512 	}
513 	*new_cwnd = cwnd;
514 	return false;
515 }
516 
517 /* Slow-start up toward target cwnd (if bw estimate is growing, or packet loss
518  * has drawn us down below target), or snap down to target if we're above it.
519  */
520 static void bbr_set_cwnd(struct sock *sk, const struct rate_sample *rs,
521 			 u32 acked, u32 bw, int gain)
522 {
523 	struct tcp_sock *tp = tcp_sk(sk);
524 	struct bbr *bbr = inet_csk_ca(sk);
525 	u32 cwnd = tcp_snd_cwnd(tp), target_cwnd = 0;
526 
527 	if (!acked)
528 		goto done;  /* no packet fully ACKed; just apply caps */
529 
530 	if (bbr_set_cwnd_to_recover_or_restore(sk, rs, acked, &cwnd))
531 		goto done;
532 
533 	target_cwnd = bbr_bdp(sk, bw, gain);
534 
535 	/* Increment the cwnd to account for excess ACKed data that seems
536 	 * due to aggregation (of data and/or ACKs) visible in the ACK stream.
537 	 */
538 	target_cwnd += bbr_ack_aggregation_cwnd(sk);
539 	target_cwnd = bbr_quantization_budget(sk, target_cwnd);
540 
541 	/* If we're below target cwnd, slow start cwnd toward target cwnd. */
542 	if (bbr_full_bw_reached(sk))  /* only cut cwnd if we filled the pipe */
543 		cwnd = min(cwnd + acked, target_cwnd);
544 	else if (cwnd < target_cwnd || tp->delivered < TCP_INIT_CWND)
545 		cwnd = cwnd + acked;
546 	cwnd = max(cwnd, bbr_cwnd_min_target);
547 
548 done:
549 	tcp_snd_cwnd_set(tp, min(cwnd, tp->snd_cwnd_clamp));	/* apply global cap */
550 	if (bbr->mode == BBR_PROBE_RTT)  /* drain queue, refresh min_rtt */
551 		tcp_snd_cwnd_set(tp, min(tcp_snd_cwnd(tp), bbr_cwnd_min_target));
552 }
553 
554 /* End cycle phase if it's time and/or we hit the phase's in-flight target. */
555 static bool bbr_is_next_cycle_phase(struct sock *sk,
556 				    const struct rate_sample *rs)
557 {
558 	struct tcp_sock *tp = tcp_sk(sk);
559 	struct bbr *bbr = inet_csk_ca(sk);
560 	bool is_full_length =
561 		tcp_stamp_us_delta(tp->delivered_mstamp, bbr->cycle_mstamp) >
562 		bbr->min_rtt_us;
563 	u32 inflight, bw;
564 
565 	/* The pacing_gain of 1.0 paces at the estimated bw to try to fully
566 	 * use the pipe without increasing the queue.
567 	 */
568 	if (bbr->pacing_gain == BBR_UNIT)
569 		return is_full_length;		/* just use wall clock time */
570 
571 	inflight = bbr_packets_in_net_at_edt(sk, rs->prior_in_flight);
572 	bw = bbr_max_bw(sk);
573 
574 	/* A pacing_gain > 1.0 probes for bw by trying to raise inflight to at
575 	 * least pacing_gain*BDP; this may take more than min_rtt if min_rtt is
576 	 * small (e.g. on a LAN). We do not persist if packets are lost, since
577 	 * a path with small buffers may not hold that much.
578 	 */
579 	if (bbr->pacing_gain > BBR_UNIT)
580 		return is_full_length &&
581 			(rs->losses ||  /* perhaps pacing_gain*BDP won't fit */
582 			 inflight >= bbr_inflight(sk, bw, bbr->pacing_gain));
583 
584 	/* A pacing_gain < 1.0 tries to drain extra queue we added if bw
585 	 * probing didn't find more bw. If inflight falls to match BDP then we
586 	 * estimate queue is drained; persisting would underutilize the pipe.
587 	 */
588 	return is_full_length ||
589 		inflight <= bbr_inflight(sk, bw, BBR_UNIT);
590 }
591 
592 static void bbr_advance_cycle_phase(struct sock *sk)
593 {
594 	struct tcp_sock *tp = tcp_sk(sk);
595 	struct bbr *bbr = inet_csk_ca(sk);
596 
597 	bbr->cycle_idx = (bbr->cycle_idx + 1) & (CYCLE_LEN - 1);
598 	bbr->cycle_mstamp = tp->delivered_mstamp;
599 }
600 
601 /* Gain cycling: cycle pacing gain to converge to fair share of available bw. */
602 static void bbr_update_cycle_phase(struct sock *sk,
603 				   const struct rate_sample *rs)
604 {
605 	struct bbr *bbr = inet_csk_ca(sk);
606 
607 	if (bbr->mode == BBR_PROBE_BW && bbr_is_next_cycle_phase(sk, rs))
608 		bbr_advance_cycle_phase(sk);
609 }
610 
611 static void bbr_reset_startup_mode(struct sock *sk)
612 {
613 	struct bbr *bbr = inet_csk_ca(sk);
614 
615 	bbr->mode = BBR_STARTUP;
616 }
617 
618 static void bbr_reset_probe_bw_mode(struct sock *sk)
619 {
620 	struct bbr *bbr = inet_csk_ca(sk);
621 
622 	bbr->mode = BBR_PROBE_BW;
623 	bbr->cycle_idx = CYCLE_LEN - 1 - get_random_u32_below(bbr_cycle_rand);
624 	bbr_advance_cycle_phase(sk);	/* flip to next phase of gain cycle */
625 }
626 
627 static void bbr_reset_mode(struct sock *sk)
628 {
629 	if (!bbr_full_bw_reached(sk))
630 		bbr_reset_startup_mode(sk);
631 	else
632 		bbr_reset_probe_bw_mode(sk);
633 }
634 
635 /* Start a new long-term sampling interval. */
636 static void bbr_reset_lt_bw_sampling_interval(struct sock *sk)
637 {
638 	struct tcp_sock *tp = tcp_sk(sk);
639 	struct bbr *bbr = inet_csk_ca(sk);
640 
641 	bbr->lt_last_stamp = div_u64(tp->delivered_mstamp, USEC_PER_MSEC);
642 	bbr->lt_last_delivered = tp->delivered;
643 	bbr->lt_last_lost = tp->lost;
644 	bbr->lt_rtt_cnt = 0;
645 }
646 
647 /* Completely reset long-term bandwidth sampling. */
648 static void bbr_reset_lt_bw_sampling(struct sock *sk)
649 {
650 	struct bbr *bbr = inet_csk_ca(sk);
651 
652 	bbr->lt_bw = 0;
653 	bbr->lt_use_bw = 0;
654 	bbr->lt_is_sampling = false;
655 	bbr_reset_lt_bw_sampling_interval(sk);
656 }
657 
658 /* Long-term bw sampling interval is done. Estimate whether we're policed. */
659 static void bbr_lt_bw_interval_done(struct sock *sk, u32 bw)
660 {
661 	struct bbr *bbr = inet_csk_ca(sk);
662 	u32 diff;
663 
664 	if (bbr->lt_bw) {  /* do we have bw from a previous interval? */
665 		/* Is new bw close to the lt_bw from the previous interval? */
666 		diff = abs(bw - bbr->lt_bw);
667 		if ((diff * BBR_UNIT <= bbr_lt_bw_ratio * bbr->lt_bw) ||
668 		    (bbr_rate_bytes_per_sec(sk, diff, BBR_UNIT) <=
669 		     bbr_lt_bw_diff)) {
670 			/* All criteria are met; estimate we're policed. */
671 			bbr->lt_bw = (bw + bbr->lt_bw) >> 1;  /* avg 2 intvls */
672 			bbr->lt_use_bw = 1;
673 			bbr->pacing_gain = BBR_UNIT;  /* try to avoid drops */
674 			bbr->lt_rtt_cnt = 0;
675 			return;
676 		}
677 	}
678 	bbr->lt_bw = bw;
679 	bbr_reset_lt_bw_sampling_interval(sk);
680 }
681 
682 /* Token-bucket traffic policers are common (see "An Internet-Wide Analysis of
683  * Traffic Policing", SIGCOMM 2016). BBR detects token-bucket policers and
684  * explicitly models their policed rate, to reduce unnecessary losses. We
685  * estimate that we're policed if we see 2 consecutive sampling intervals with
686  * consistent throughput and high packet loss. If we think we're being policed,
687  * set lt_bw to the "long-term" average delivery rate from those 2 intervals.
688  */
689 static void bbr_lt_bw_sampling(struct sock *sk, const struct rate_sample *rs)
690 {
691 	struct tcp_sock *tp = tcp_sk(sk);
692 	struct bbr *bbr = inet_csk_ca(sk);
693 	u32 lost, delivered;
694 	u64 bw;
695 	u32 t;
696 
697 	if (bbr->lt_use_bw) {	/* already using long-term rate, lt_bw? */
698 		if (bbr->mode == BBR_PROBE_BW && bbr->round_start &&
699 		    ++bbr->lt_rtt_cnt >= bbr_lt_bw_max_rtts) {
700 			bbr_reset_lt_bw_sampling(sk);    /* stop using lt_bw */
701 			bbr_reset_probe_bw_mode(sk);  /* restart gain cycling */
702 		}
703 		return;
704 	}
705 
706 	/* Wait for the first loss before sampling, to let the policer exhaust
707 	 * its tokens and estimate the steady-state rate allowed by the policer.
708 	 * Starting samples earlier includes bursts that over-estimate the bw.
709 	 */
710 	if (!bbr->lt_is_sampling) {
711 		if (!rs->losses)
712 			return;
713 		bbr_reset_lt_bw_sampling_interval(sk);
714 		bbr->lt_is_sampling = true;
715 	}
716 
717 	/* To avoid underestimates, reset sampling if we run out of data. */
718 	if (rs->is_app_limited) {
719 		bbr_reset_lt_bw_sampling(sk);
720 		return;
721 	}
722 
723 	if (bbr->round_start)
724 		bbr->lt_rtt_cnt++;	/* count round trips in this interval */
725 	if (bbr->lt_rtt_cnt < bbr_lt_intvl_min_rtts)
726 		return;		/* sampling interval needs to be longer */
727 	if (bbr->lt_rtt_cnt > 4 * bbr_lt_intvl_min_rtts) {
728 		bbr_reset_lt_bw_sampling(sk);  /* interval is too long */
729 		return;
730 	}
731 
732 	/* End sampling interval when a packet is lost, so we estimate the
733 	 * policer tokens were exhausted. Stopping the sampling before the
734 	 * tokens are exhausted under-estimates the policed rate.
735 	 */
736 	if (!rs->losses)
737 		return;
738 
739 	/* Calculate packets lost and delivered in sampling interval. */
740 	lost = tp->lost - bbr->lt_last_lost;
741 	delivered = tp->delivered - bbr->lt_last_delivered;
742 	/* Is loss rate (lost/delivered) >= lt_loss_thresh? If not, wait. */
743 	if (!delivered || (lost << BBR_SCALE) < bbr_lt_loss_thresh * delivered)
744 		return;
745 
746 	/* Find average delivery rate in this sampling interval. */
747 	t = div_u64(tp->delivered_mstamp, USEC_PER_MSEC) - bbr->lt_last_stamp;
748 	if ((s32)t < 1)
749 		return;		/* interval is less than one ms, so wait */
750 	/* Check if can multiply without overflow */
751 	if (t >= ~0U / USEC_PER_MSEC) {
752 		bbr_reset_lt_bw_sampling(sk);  /* interval too long; reset */
753 		return;
754 	}
755 	t *= USEC_PER_MSEC;
756 	bw = (u64)delivered * BW_UNIT;
757 	do_div(bw, t);
758 	bbr_lt_bw_interval_done(sk, bw);
759 }
760 
761 /* Estimate the bandwidth based on how fast packets are delivered */
762 static void bbr_update_bw(struct sock *sk, const struct rate_sample *rs)
763 {
764 	struct tcp_sock *tp = tcp_sk(sk);
765 	struct bbr *bbr = inet_csk_ca(sk);
766 	u64 bw;
767 
768 	bbr->round_start = 0;
769 	if (rs->delivered < 0 || rs->interval_us <= 0)
770 		return; /* Not a valid observation */
771 
772 	/* See if we've reached the next RTT */
773 	if (!before(rs->prior_delivered, bbr->next_rtt_delivered)) {
774 		bbr->next_rtt_delivered = tp->delivered;
775 		bbr->rtt_cnt++;
776 		bbr->round_start = 1;
777 		bbr->packet_conservation = 0;
778 	}
779 
780 	bbr_lt_bw_sampling(sk, rs);
781 
782 	/* Divide delivered by the interval to find a (lower bound) bottleneck
783 	 * bandwidth sample. Delivered is in packets and interval_us in uS and
784 	 * ratio will be <<1 for most connections. So delivered is first scaled.
785 	 */
786 	bw = div64_long((u64)rs->delivered * BW_UNIT, rs->interval_us);
787 
788 	/* If this sample is application-limited, it is likely to have a very
789 	 * low delivered count that represents application behavior rather than
790 	 * the available network rate. Such a sample could drag down estimated
791 	 * bw, causing needless slow-down. Thus, to continue to send at the
792 	 * last measured network rate, we filter out app-limited samples unless
793 	 * they describe the path bw at least as well as our bw model.
794 	 *
795 	 * So the goal during app-limited phase is to proceed with the best
796 	 * network rate no matter how long. We automatically leave this
797 	 * phase when app writes faster than the network can deliver :)
798 	 */
799 	if (!rs->is_app_limited || bw >= bbr_max_bw(sk)) {
800 		/* Incorporate new sample into our max bw filter. */
801 		minmax_running_max(&bbr->bw, bbr_bw_rtts, bbr->rtt_cnt, bw);
802 	}
803 }
804 
805 /* Estimates the windowed max degree of ack aggregation.
806  * This is used to provision extra in-flight data to keep sending during
807  * inter-ACK silences.
808  *
809  * Degree of ack aggregation is estimated as extra data acked beyond expected.
810  *
811  * max_extra_acked = "maximum recent excess data ACKed beyond max_bw * interval"
812  * cwnd += max_extra_acked
813  *
814  * Max extra_acked is clamped by cwnd and bw * bbr_extra_acked_max_us (100 ms).
815  * Max filter is an approximate sliding window of 5-10 (packet timed) round
816  * trips.
817  */
818 static void bbr_update_ack_aggregation(struct sock *sk,
819 				       const struct rate_sample *rs)
820 {
821 	u32 epoch_us, expected_acked, extra_acked;
822 	struct bbr *bbr = inet_csk_ca(sk);
823 	struct tcp_sock *tp = tcp_sk(sk);
824 
825 	if (!bbr_extra_acked_gain || rs->acked_sacked <= 0 ||
826 	    rs->delivered < 0 || rs->interval_us <= 0)
827 		return;
828 
829 	if (bbr->round_start) {
830 		bbr->extra_acked_win_rtts = min(0x1F,
831 						bbr->extra_acked_win_rtts + 1);
832 		if (bbr->extra_acked_win_rtts >= bbr_extra_acked_win_rtts) {
833 			bbr->extra_acked_win_rtts = 0;
834 			bbr->extra_acked_win_idx = bbr->extra_acked_win_idx ?
835 						   0 : 1;
836 			bbr->extra_acked[bbr->extra_acked_win_idx] = 0;
837 		}
838 	}
839 
840 	/* Compute how many packets we expected to be delivered over epoch. */
841 	epoch_us = tcp_stamp_us_delta(tp->delivered_mstamp,
842 				      bbr->ack_epoch_mstamp);
843 	expected_acked = ((u64)bbr_bw(sk) * epoch_us) / BW_UNIT;
844 
845 	/* Reset the aggregation epoch if ACK rate is below expected rate or
846 	 * significantly large no. of ack received since epoch (potentially
847 	 * quite old epoch).
848 	 */
849 	if (bbr->ack_epoch_acked <= expected_acked ||
850 	    (bbr->ack_epoch_acked + rs->acked_sacked >=
851 	     bbr_ack_epoch_acked_reset_thresh)) {
852 		bbr->ack_epoch_acked = 0;
853 		bbr->ack_epoch_mstamp = tp->delivered_mstamp;
854 		expected_acked = 0;
855 	}
856 
857 	/* Compute excess data delivered, beyond what was expected. */
858 	bbr->ack_epoch_acked = min_t(u32, 0xFFFFF,
859 				     bbr->ack_epoch_acked + rs->acked_sacked);
860 	extra_acked = bbr->ack_epoch_acked - expected_acked;
861 	extra_acked = min(extra_acked, tcp_snd_cwnd(tp));
862 	if (extra_acked > bbr->extra_acked[bbr->extra_acked_win_idx])
863 		bbr->extra_acked[bbr->extra_acked_win_idx] = extra_acked;
864 }
865 
866 /* Estimate when the pipe is full, using the change in delivery rate: BBR
867  * estimates that STARTUP filled the pipe if the estimated bw hasn't changed by
868  * at least bbr_full_bw_thresh (25%) after bbr_full_bw_cnt (3) non-app-limited
869  * rounds. Why 3 rounds: 1: rwin autotuning grows the rwin, 2: we fill the
870  * higher rwin, 3: we get higher delivery rate samples. Or transient
871  * cross-traffic or radio noise can go away. CUBIC Hystart shares a similar
872  * design goal, but uses delay and inter-ACK spacing instead of bandwidth.
873  */
874 static void bbr_check_full_bw_reached(struct sock *sk,
875 				      const struct rate_sample *rs)
876 {
877 	struct bbr *bbr = inet_csk_ca(sk);
878 	u32 bw_thresh;
879 
880 	if (bbr_full_bw_reached(sk) || !bbr->round_start || rs->is_app_limited)
881 		return;
882 
883 	bw_thresh = (u64)bbr->full_bw * bbr_full_bw_thresh >> BBR_SCALE;
884 	if (bbr_max_bw(sk) >= bw_thresh) {
885 		bbr->full_bw = bbr_max_bw(sk);
886 		bbr->full_bw_cnt = 0;
887 		return;
888 	}
889 	++bbr->full_bw_cnt;
890 	bbr->full_bw_reached = bbr->full_bw_cnt >= bbr_full_bw_cnt;
891 }
892 
893 /* If pipe is probably full, drain the queue and then enter steady-state. */
894 static void bbr_check_drain(struct sock *sk, const struct rate_sample *rs)
895 {
896 	struct bbr *bbr = inet_csk_ca(sk);
897 
898 	if (bbr->mode == BBR_STARTUP && bbr_full_bw_reached(sk)) {
899 		bbr->mode = BBR_DRAIN;	/* drain queue we created */
900 		tcp_sk(sk)->snd_ssthresh =
901 				bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT);
902 	}	/* fall through to check if in-flight is already small: */
903 	if (bbr->mode == BBR_DRAIN &&
904 	    bbr_packets_in_net_at_edt(sk, tcp_packets_in_flight(tcp_sk(sk))) <=
905 	    bbr_inflight(sk, bbr_max_bw(sk), BBR_UNIT))
906 		bbr_reset_probe_bw_mode(sk);  /* we estimate queue is drained */
907 }
908 
909 static void bbr_check_probe_rtt_done(struct sock *sk)
910 {
911 	struct tcp_sock *tp = tcp_sk(sk);
912 	struct bbr *bbr = inet_csk_ca(sk);
913 
914 	if (!(bbr->probe_rtt_done_stamp &&
915 	      after(tcp_jiffies32, bbr->probe_rtt_done_stamp)))
916 		return;
917 
918 	bbr->min_rtt_stamp = tcp_jiffies32;  /* wait a while until PROBE_RTT */
919 	tcp_snd_cwnd_set(tp, max(tcp_snd_cwnd(tp), bbr->prior_cwnd));
920 	bbr_reset_mode(sk);
921 }
922 
923 /* The goal of PROBE_RTT mode is to have BBR flows cooperatively and
924  * periodically drain the bottleneck queue, to converge to measure the true
925  * min_rtt (unloaded propagation delay). This allows the flows to keep queues
926  * small (reducing queuing delay and packet loss) and achieve fairness among
927  * BBR flows.
928  *
929  * The min_rtt filter window is 10 seconds. When the min_rtt estimate expires,
930  * we enter PROBE_RTT mode and cap the cwnd at bbr_cwnd_min_target=4 packets.
931  * After at least bbr_probe_rtt_mode_ms=200ms and at least one packet-timed
932  * round trip elapsed with that flight size <= 4, we leave PROBE_RTT mode and
933  * re-enter the previous mode. BBR uses 200ms to approximately bound the
934  * performance penalty of PROBE_RTT's cwnd capping to roughly 2% (200ms/10s).
935  *
936  * Note that flows need only pay 2% if they are busy sending over the last 10
937  * seconds. Interactive applications (e.g., Web, RPCs, video chunks) often have
938  * natural silences or low-rate periods within 10 seconds where the rate is low
939  * enough for long enough to drain its queue in the bottleneck. We pick up
940  * these min RTT measurements opportunistically with our min_rtt filter. :-)
941  */
942 static void bbr_update_min_rtt(struct sock *sk, const struct rate_sample *rs)
943 {
944 	struct tcp_sock *tp = tcp_sk(sk);
945 	struct bbr *bbr = inet_csk_ca(sk);
946 	bool filter_expired;
947 
948 	/* Track min RTT seen in the min_rtt_win_sec filter window: */
949 	filter_expired = after(tcp_jiffies32,
950 			       bbr->min_rtt_stamp + bbr_min_rtt_win_sec * HZ);
951 	if (rs->rtt_us >= 0 &&
952 	    (rs->rtt_us < bbr->min_rtt_us ||
953 	     (filter_expired && !rs->is_ack_delayed))) {
954 		bbr->min_rtt_us = rs->rtt_us;
955 		bbr->min_rtt_stamp = tcp_jiffies32;
956 	}
957 
958 	if (bbr_probe_rtt_mode_ms > 0 && filter_expired &&
959 	    !bbr->idle_restart && bbr->mode != BBR_PROBE_RTT) {
960 		bbr->mode = BBR_PROBE_RTT;  /* dip, drain queue */
961 		bbr_save_cwnd(sk);  /* note cwnd so we can restore it */
962 		bbr->probe_rtt_done_stamp = 0;
963 	}
964 
965 	if (bbr->mode == BBR_PROBE_RTT) {
966 		/* Ignore low rate samples during this mode. */
967 		tp->app_limited =
968 			(tp->delivered + tcp_packets_in_flight(tp)) ? : 1;
969 		/* Maintain min packets in flight for max(200 ms, 1 round). */
970 		if (!bbr->probe_rtt_done_stamp &&
971 		    tcp_packets_in_flight(tp) <= bbr_cwnd_min_target) {
972 			bbr->probe_rtt_done_stamp = tcp_jiffies32 +
973 				msecs_to_jiffies(bbr_probe_rtt_mode_ms);
974 			bbr->probe_rtt_round_done = 0;
975 			bbr->next_rtt_delivered = tp->delivered;
976 		} else if (bbr->probe_rtt_done_stamp) {
977 			if (bbr->round_start)
978 				bbr->probe_rtt_round_done = 1;
979 			if (bbr->probe_rtt_round_done)
980 				bbr_check_probe_rtt_done(sk);
981 		}
982 	}
983 	/* Restart after idle ends only once we process a new S/ACK for data */
984 	if (rs->delivered > 0)
985 		bbr->idle_restart = 0;
986 }
987 
988 static void bbr_update_gains(struct sock *sk)
989 {
990 	struct bbr *bbr = inet_csk_ca(sk);
991 
992 	switch (bbr->mode) {
993 	case BBR_STARTUP:
994 		bbr->pacing_gain = bbr_high_gain;
995 		bbr->cwnd_gain	 = bbr_high_gain;
996 		break;
997 	case BBR_DRAIN:
998 		bbr->pacing_gain = bbr_drain_gain;	/* slow, to drain */
999 		bbr->cwnd_gain	 = bbr_high_gain;	/* keep cwnd */
1000 		break;
1001 	case BBR_PROBE_BW:
1002 		bbr->pacing_gain = (bbr->lt_use_bw ?
1003 				    BBR_UNIT :
1004 				    bbr_pacing_gain[bbr->cycle_idx]);
1005 		bbr->cwnd_gain	 = bbr_cwnd_gain;
1006 		break;
1007 	case BBR_PROBE_RTT:
1008 		bbr->pacing_gain = BBR_UNIT;
1009 		bbr->cwnd_gain	 = BBR_UNIT;
1010 		break;
1011 	default:
1012 		WARN_ONCE(1, "BBR bad mode: %u\n", bbr->mode);
1013 		break;
1014 	}
1015 }
1016 
1017 static void bbr_update_model(struct sock *sk, const struct rate_sample *rs)
1018 {
1019 	bbr_update_bw(sk, rs);
1020 	bbr_update_ack_aggregation(sk, rs);
1021 	bbr_update_cycle_phase(sk, rs);
1022 	bbr_check_full_bw_reached(sk, rs);
1023 	bbr_check_drain(sk, rs);
1024 	bbr_update_min_rtt(sk, rs);
1025 	bbr_update_gains(sk);
1026 }
1027 
1028 __bpf_kfunc static void bbr_main(struct sock *sk, u32 ack, int flag, const struct rate_sample *rs)
1029 {
1030 	struct bbr *bbr = inet_csk_ca(sk);
1031 	u32 bw;
1032 
1033 	bbr_update_model(sk, rs);
1034 
1035 	bw = bbr_bw(sk);
1036 	bbr_set_pacing_rate(sk, bw, bbr->pacing_gain);
1037 	bbr_set_cwnd(sk, rs, rs->acked_sacked, bw, bbr->cwnd_gain);
1038 }
1039 
1040 __bpf_kfunc static void bbr_init(struct sock *sk)
1041 {
1042 	struct tcp_sock *tp = tcp_sk(sk);
1043 	struct bbr *bbr = inet_csk_ca(sk);
1044 
1045 	bbr->prior_cwnd = 0;
1046 	tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
1047 	bbr->rtt_cnt = 0;
1048 	bbr->next_rtt_delivered = tp->delivered;
1049 	bbr->prev_ca_state = TCP_CA_Open;
1050 	bbr->packet_conservation = 0;
1051 
1052 	bbr->probe_rtt_done_stamp = 0;
1053 	bbr->probe_rtt_round_done = 0;
1054 	bbr->min_rtt_us = tcp_min_rtt(tp);
1055 	bbr->min_rtt_stamp = tcp_jiffies32;
1056 
1057 	minmax_reset(&bbr->bw, bbr->rtt_cnt, 0);  /* init max bw to 0 */
1058 
1059 	bbr->has_seen_rtt = 0;
1060 	bbr_init_pacing_rate_from_rtt(sk);
1061 
1062 	bbr->round_start = 0;
1063 	bbr->idle_restart = 0;
1064 	bbr->full_bw_reached = 0;
1065 	bbr->full_bw = 0;
1066 	bbr->full_bw_cnt = 0;
1067 	bbr->cycle_mstamp = 0;
1068 	bbr->cycle_idx = 0;
1069 	bbr_reset_lt_bw_sampling(sk);
1070 	bbr_reset_startup_mode(sk);
1071 
1072 	bbr->ack_epoch_mstamp = tp->tcp_mstamp;
1073 	bbr->ack_epoch_acked = 0;
1074 	bbr->extra_acked_win_rtts = 0;
1075 	bbr->extra_acked_win_idx = 0;
1076 	bbr->extra_acked[0] = 0;
1077 	bbr->extra_acked[1] = 0;
1078 
1079 	cmpxchg(&sk->sk_pacing_status, SK_PACING_NONE, SK_PACING_NEEDED);
1080 }
1081 
1082 __bpf_kfunc static u32 bbr_sndbuf_expand(struct sock *sk)
1083 {
1084 	/* Provision 3 * cwnd since BBR may slow-start even during recovery. */
1085 	return 3;
1086 }
1087 
1088 /* In theory BBR does not need to undo the cwnd since it does not
1089  * always reduce cwnd on losses (see bbr_main()). Keep it for now.
1090  */
1091 __bpf_kfunc static u32 bbr_undo_cwnd(struct sock *sk)
1092 {
1093 	struct bbr *bbr = inet_csk_ca(sk);
1094 
1095 	bbr->full_bw = 0;   /* spurious slow-down; reset full pipe detection */
1096 	bbr->full_bw_cnt = 0;
1097 	bbr_reset_lt_bw_sampling(sk);
1098 	return tcp_snd_cwnd(tcp_sk(sk));
1099 }
1100 
1101 /* Entering loss recovery, so save cwnd for when we exit or undo recovery. */
1102 __bpf_kfunc static u32 bbr_ssthresh(struct sock *sk)
1103 {
1104 	bbr_save_cwnd(sk);
1105 	return tcp_sk(sk)->snd_ssthresh;
1106 }
1107 
1108 static size_t bbr_get_info(struct sock *sk, u32 ext, int *attr,
1109 			   union tcp_cc_info *info)
1110 {
1111 	if (ext & (1 << (INET_DIAG_BBRINFO - 1)) ||
1112 	    ext & (1 << (INET_DIAG_VEGASINFO - 1))) {
1113 		struct tcp_sock *tp = tcp_sk(sk);
1114 		struct bbr *bbr = inet_csk_ca(sk);
1115 		u64 bw = bbr_bw(sk);
1116 
1117 		bw = bw * tp->mss_cache * USEC_PER_SEC >> BW_SCALE;
1118 		memset(&info->bbr, 0, sizeof(info->bbr));
1119 		info->bbr.bbr_bw_lo		= (u32)bw;
1120 		info->bbr.bbr_bw_hi		= (u32)(bw >> 32);
1121 		info->bbr.bbr_min_rtt		= bbr->min_rtt_us;
1122 		info->bbr.bbr_pacing_gain	= bbr->pacing_gain;
1123 		info->bbr.bbr_cwnd_gain		= bbr->cwnd_gain;
1124 		*attr = INET_DIAG_BBRINFO;
1125 		return sizeof(info->bbr);
1126 	}
1127 	return 0;
1128 }
1129 
1130 __bpf_kfunc static void bbr_set_state(struct sock *sk, u8 new_state)
1131 {
1132 	struct bbr *bbr = inet_csk_ca(sk);
1133 
1134 	if (new_state == TCP_CA_Loss) {
1135 		struct rate_sample rs = { .losses = 1 };
1136 
1137 		bbr->prev_ca_state = TCP_CA_Loss;
1138 		bbr->full_bw = 0;
1139 		bbr->round_start = 1;	/* treat RTO like end of a round */
1140 		bbr_lt_bw_sampling(sk, &rs);
1141 	}
1142 }
1143 
1144 static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = {
1145 	.flags		= TCP_CONG_NON_RESTRICTED,
1146 	.name		= "bbr",
1147 	.owner		= THIS_MODULE,
1148 	.init		= bbr_init,
1149 	.cong_control	= bbr_main,
1150 	.sndbuf_expand	= bbr_sndbuf_expand,
1151 	.undo_cwnd	= bbr_undo_cwnd,
1152 	.cwnd_event_tx_start	= bbr_cwnd_event_tx_start,
1153 	.ssthresh	= bbr_ssthresh,
1154 	.min_tso_segs	= bbr_min_tso_segs,
1155 	.get_info	= bbr_get_info,
1156 	.set_state	= bbr_set_state,
1157 };
1158 
1159 BTF_KFUNCS_START(tcp_bbr_check_kfunc_ids)
1160 BTF_ID_FLAGS(func, bbr_init)
1161 BTF_ID_FLAGS(func, bbr_main)
1162 BTF_ID_FLAGS(func, bbr_sndbuf_expand)
1163 BTF_ID_FLAGS(func, bbr_undo_cwnd)
1164 BTF_ID_FLAGS(func, bbr_cwnd_event_tx_start)
1165 BTF_ID_FLAGS(func, bbr_ssthresh)
1166 BTF_ID_FLAGS(func, bbr_min_tso_segs)
1167 BTF_ID_FLAGS(func, bbr_set_state)
1168 BTF_KFUNCS_END(tcp_bbr_check_kfunc_ids)
1169 
1170 static const struct btf_kfunc_id_set tcp_bbr_kfunc_set = {
1171 	.owner = THIS_MODULE,
1172 	.set   = &tcp_bbr_check_kfunc_ids,
1173 };
1174 
1175 static int __init bbr_register(void)
1176 {
1177 	int ret;
1178 
1179 	BUILD_BUG_ON(sizeof(struct bbr) > ICSK_CA_PRIV_SIZE);
1180 
1181 	ret = register_btf_kfunc_id_set(BPF_PROG_TYPE_STRUCT_OPS, &tcp_bbr_kfunc_set);
1182 	if (ret < 0)
1183 		return ret;
1184 	return tcp_register_congestion_control(&tcp_bbr_cong_ops);
1185 }
1186 
1187 static void __exit bbr_unregister(void)
1188 {
1189 	tcp_unregister_congestion_control(&tcp_bbr_cong_ops);
1190 }
1191 
1192 module_init(bbr_register);
1193 module_exit(bbr_unregister);
1194 
1195 MODULE_AUTHOR("Van Jacobson <vanj@google.com>");
1196 MODULE_AUTHOR("Neal Cardwell <ncardwell@google.com>");
1197 MODULE_AUTHOR("Yuchung Cheng <ycheng@google.com>");
1198 MODULE_AUTHOR("Soheil Hassas Yeganeh <soheil@google.com>");
1199 MODULE_LICENSE("Dual BSD/GPL");
1200 MODULE_DESCRIPTION("TCP BBR (Bottleneck Bandwidth and RTT)");
1201