perf bpf: Move perf_event_output() from stdio.h to bpf.h
[linux/fpc-iii.git] / net / ipv4 / tcp_bbr.c
blob9277abdd822a0915308863d68d6f40a102cbb2b5
1 /* Bottleneck Bandwidth and RTT (BBR) congestion control
3 * BBR congestion control computes the sending rate based on the delivery
4 * rate (throughput) estimated from ACKs. In a nutshell:
6 * On each ACK, update our model of the network path:
7 * bottleneck_bandwidth = windowed_max(delivered / elapsed, 10 round trips)
8 * min_rtt = windowed_min(rtt, 10 seconds)
9 * pacing_rate = pacing_gain * bottleneck_bandwidth
10 * cwnd = max(cwnd_gain * bottleneck_bandwidth * min_rtt, 4)
12 * The core algorithm does not react directly to packet losses or delays,
13 * although BBR may adjust the size of next send per ACK when loss is
14 * observed, or adjust the sending rate if it estimates there is a
15 * traffic policer, in order to keep the drop rate reasonable.
17 * Here is a state transition diagram for BBR:
19 * |
20 * V
21 * +---> STARTUP ----+
22 * | | |
23 * | V |
24 * | DRAIN ----+
25 * | | |
26 * | V |
27 * +---> PROBE_BW ----+
28 * | ^ | |
29 * | | | |
30 * | +----+ |
31 * | |
32 * +---- PROBE_RTT <--+
34 * A BBR flow starts in STARTUP, and ramps up its sending rate quickly.
35 * When it estimates the pipe is full, it enters DRAIN to drain the queue.
36 * In steady state a BBR flow only uses PROBE_BW and PROBE_RTT.
37 * A long-lived BBR flow spends the vast majority of its time remaining
38 * (repeatedly) in PROBE_BW, fully probing and utilizing the pipe's bandwidth
39 * in a fair manner, with a small, bounded queue. *If* a flow has been
40 * continuously sending for the entire min_rtt window, and hasn't seen an RTT
41 * sample that matches or decreases its min_rtt estimate for 10 seconds, then
42 * it briefly enters PROBE_RTT to cut inflight to a minimum value to re-probe
43 * the path's two-way propagation delay (min_rtt). When exiting PROBE_RTT, if
44 * we estimated that we reached the full bw of the pipe then we enter PROBE_BW;
45 * otherwise we enter STARTUP to try to fill the pipe.
47 * BBR is described in detail in:
48 * "BBR: Congestion-Based Congestion Control",
49 * Neal Cardwell, Yuchung Cheng, C. Stephen Gunn, Soheil Hassas Yeganeh,
50 * Van Jacobson. ACM Queue, Vol. 14 No. 5, September-October 2016.
52 * There is a public e-mail list for discussing BBR development and testing:
53 * https://groups.google.com/forum/#!forum/bbr-dev
55 * NOTE: BBR might be used with the fq qdisc ("man tc-fq") with pacing enabled,
56 * otherwise TCP stack falls back to an internal pacing using one high
57 * resolution timer per TCP socket and may use more resources.
59 #include <linux/module.h>
60 #include <net/tcp.h>
61 #include <linux/inet_diag.h>
62 #include <linux/inet.h>
63 #include <linux/random.h>
64 #include <linux/win_minmax.h>
66 /* Scale factor for rate in pkt/uSec unit to avoid truncation in bandwidth
67 * estimation. The rate unit ~= (1500 bytes / 1 usec / 2^24) ~= 715 bps.
68 * This handles bandwidths from 0.06pps (715bps) to 256Mpps (3Tbps) in a u32.
69 * Since the minimum window is >=4 packets, the lower bound isn't
70 * an issue. The upper bound isn't an issue with existing technologies.
72 #define BW_SCALE 24
73 #define BW_UNIT (1 << BW_SCALE)
75 #define BBR_SCALE 8 /* scaling factor for fractions in BBR (e.g. gains) */
76 #define BBR_UNIT (1 << BBR_SCALE)
78 /* BBR has the following modes for deciding how fast to send: */
79 enum bbr_mode {
80 BBR_STARTUP, /* ramp up sending rate rapidly to fill pipe */
81 BBR_DRAIN, /* drain any queue created during startup */
82 BBR_PROBE_BW, /* discover, share bw: pace around estimated bw */
83 BBR_PROBE_RTT, /* cut inflight to min to probe min_rtt */
86 /* BBR congestion control block */
87 struct bbr {
88 u32 min_rtt_us; /* min RTT in min_rtt_win_sec window */
89 u32 min_rtt_stamp; /* timestamp of min_rtt_us */
90 u32 probe_rtt_done_stamp; /* end time for BBR_PROBE_RTT mode */
91 struct minmax bw; /* Max recent delivery rate in pkts/uS << 24 */
92 u32 rtt_cnt; /* count of packet-timed rounds elapsed */
93 u32 next_rtt_delivered; /* scb->tx.delivered at end of round */
94 u64 cycle_mstamp; /* time of this cycle phase start */
95 u32 mode:3, /* current bbr_mode in state machine */
96 prev_ca_state:3, /* CA state on previous ACK */
97 packet_conservation:1, /* use packet conservation? */
98 round_start:1, /* start of packet-timed tx->ack round? */
99 idle_restart:1, /* restarting after idle? */
100 probe_rtt_round_done:1, /* a BBR_PROBE_RTT round at 4 pkts? */
101 unused:13,
102 lt_is_sampling:1, /* taking long-term ("LT") samples now? */
103 lt_rtt_cnt:7, /* round trips in long-term interval */
104 lt_use_bw:1; /* use lt_bw as our bw estimate? */
105 u32 lt_bw; /* LT est delivery rate in pkts/uS << 24 */
106 u32 lt_last_delivered; /* LT intvl start: tp->delivered */
107 u32 lt_last_stamp; /* LT intvl start: tp->delivered_mstamp */
108 u32 lt_last_lost; /* LT intvl start: tp->lost */
109 u32 pacing_gain:10, /* current gain for setting pacing rate */
110 cwnd_gain:10, /* current gain for setting cwnd */
111 full_bw_reached:1, /* reached full bw in Startup? */
112 full_bw_cnt:2, /* number of rounds without large bw gains */
113 cycle_idx:3, /* current index in pacing_gain cycle array */
114 has_seen_rtt:1, /* have we seen an RTT sample yet? */
115 unused_b:5;
116 u32 prior_cwnd; /* prior cwnd upon entering loss recovery */
117 u32 full_bw; /* recent bw, to estimate if pipe is full */
120 #define CYCLE_LEN 8 /* number of phases in a pacing gain cycle */
122 /* Window length of bw filter (in rounds): */
123 static const int bbr_bw_rtts = CYCLE_LEN + 2;
124 /* Window length of min_rtt filter (in sec): */
125 static const u32 bbr_min_rtt_win_sec = 10;
126 /* Minimum time (in ms) spent at bbr_cwnd_min_target in BBR_PROBE_RTT mode: */
127 static const u32 bbr_probe_rtt_mode_ms = 200;
128 /* Skip TSO below the following bandwidth (bits/sec): */
129 static const int bbr_min_tso_rate = 1200000;
131 /* Pace at ~1% below estimated bw, on average, to reduce queue at bottleneck. */
132 static const int bbr_pacing_margin_percent = 1;
134 /* We use a high_gain value of 2/ln(2) because it's the smallest pacing gain
135 * that will allow a smoothly increasing pacing rate that will double each RTT
136 * and send the same number of packets per RTT that an un-paced, slow-starting
137 * Reno or CUBIC flow would:
139 static const int bbr_high_gain = BBR_UNIT * 2885 / 1000 + 1;
140 /* The pacing gain of 1/high_gain in BBR_DRAIN is calculated to typically drain
141 * the queue created in BBR_STARTUP in a single round:
143 static const int bbr_drain_gain = BBR_UNIT * 1000 / 2885;
144 /* The gain for deriving steady-state cwnd tolerates delayed/stretched ACKs: */
145 static const int bbr_cwnd_gain = BBR_UNIT * 2;
146 /* The pacing_gain values for the PROBE_BW gain cycle, to discover/share bw: */
147 static const int bbr_pacing_gain[] = {
148 BBR_UNIT * 5 / 4, /* probe for more available bw */
149 BBR_UNIT * 3 / 4, /* drain queue and/or yield bw to other flows */
150 BBR_UNIT, BBR_UNIT, BBR_UNIT, /* cruise at 1.0*bw to utilize pipe, */
151 BBR_UNIT, BBR_UNIT, BBR_UNIT /* without creating excess queue... */
153 /* Randomize the starting gain cycling phase over N phases: */
154 static const u32 bbr_cycle_rand = 7;
156 /* Try to keep at least this many packets in flight, if things go smoothly. For
157 * smooth functioning, a sliding window protocol ACKing every other packet
158 * needs at least 4 packets in flight:
160 static const u32 bbr_cwnd_min_target = 4;
162 /* To estimate if BBR_STARTUP mode (i.e. high_gain) has filled pipe... */
163 /* If bw has increased significantly (1.25x), there may be more bw available: */
164 static const u32 bbr_full_bw_thresh = BBR_UNIT * 5 / 4;
165 /* But after 3 rounds w/o significant bw growth, estimate pipe is full: */
166 static const u32 bbr_full_bw_cnt = 3;
168 /* "long-term" ("LT") bandwidth estimator parameters... */
169 /* The minimum number of rounds in an LT bw sampling interval: */
170 static const u32 bbr_lt_intvl_min_rtts = 4;
171 /* If lost/delivered ratio > 20%, interval is "lossy" and we may be policed: */
172 static const u32 bbr_lt_loss_thresh = 50;
173 /* If 2 intervals have a bw ratio <= 1/8, their bw is "consistent": */
174 static const u32 bbr_lt_bw_ratio = BBR_UNIT / 8;
175 /* If 2 intervals have a bw diff <= 4 Kbit/sec their bw is "consistent": */
176 static const u32 bbr_lt_bw_diff = 4000 / 8;
177 /* If we estimate we're policed, use lt_bw for this many round trips: */
178 static const u32 bbr_lt_bw_max_rtts = 48;
180 static void bbr_check_probe_rtt_done(struct sock *sk);
182 /* Do we estimate that STARTUP filled the pipe? */
183 static bool bbr_full_bw_reached(const struct sock *sk)
185 const struct bbr *bbr = inet_csk_ca(sk);
187 return bbr->full_bw_reached;
190 /* Return the windowed max recent bandwidth sample, in pkts/uS << BW_SCALE. */
191 static u32 bbr_max_bw(const struct sock *sk)
193 struct bbr *bbr = inet_csk_ca(sk);
195 return minmax_get(&bbr->bw);
198 /* Return the estimated bandwidth of the path, in pkts/uS << BW_SCALE. */
199 static u32 bbr_bw(const struct sock *sk)
201 struct bbr *bbr = inet_csk_ca(sk);
203 return bbr->lt_use_bw ? bbr->lt_bw : bbr_max_bw(sk);
206 /* Return rate in bytes per second, optionally with a gain.
207 * The order here is chosen carefully to avoid overflow of u64. This should
208 * work for input rates of up to 2.9Tbit/sec and gain of 2.89x.
210 static u64 bbr_rate_bytes_per_sec(struct sock *sk, u64 rate, int gain)
212 unsigned int mss = tcp_sk(sk)->mss_cache;
214 rate *= mss;
215 rate *= gain;
216 rate >>= BBR_SCALE;
217 rate *= USEC_PER_SEC / 100 * (100 - bbr_pacing_margin_percent);
218 return rate >> BW_SCALE;
221 /* Convert a BBR bw and gain factor to a pacing rate in bytes per second. */
222 static unsigned long bbr_bw_to_pacing_rate(struct sock *sk, u32 bw, int gain)
224 u64 rate = bw;
226 rate = bbr_rate_bytes_per_sec(sk, rate, gain);
227 rate = min_t(u64, rate, sk->sk_max_pacing_rate);
228 return rate;
231 /* Initialize pacing rate to: high_gain * init_cwnd / RTT. */
232 static void bbr_init_pacing_rate_from_rtt(struct sock *sk)
234 struct tcp_sock *tp = tcp_sk(sk);
235 struct bbr *bbr = inet_csk_ca(sk);
236 u64 bw;
237 u32 rtt_us;
239 if (tp->srtt_us) { /* any RTT sample yet? */
240 rtt_us = max(tp->srtt_us >> 3, 1U);
241 bbr->has_seen_rtt = 1;
242 } else { /* no RTT sample yet */
243 rtt_us = USEC_PER_MSEC; /* use nominal default RTT */
245 bw = (u64)tp->snd_cwnd * BW_UNIT;
246 do_div(bw, rtt_us);
247 sk->sk_pacing_rate = bbr_bw_to_pacing_rate(sk, bw, bbr_high_gain);
250 /* Pace using current bw estimate and a gain factor. In order to help drive the
251 * network toward lower queues while maintaining high utilization and low
252 * latency, the average pacing rate aims to be slightly (~1%) lower than the
253 * estimated bandwidth. This is an important aspect of the design. In this
254 * implementation this slightly lower pacing rate is achieved implicitly by not
255 * including link-layer headers in the packet size used for the pacing rate.
257 static void bbr_set_pacing_rate(struct sock *sk, u32 bw, int gain)
259 struct tcp_sock *tp = tcp_sk(sk);
260 struct bbr *bbr = inet_csk_ca(sk);
261 unsigned long rate = bbr_bw_to_pacing_rate(sk, bw, gain);
263 if (unlikely(!bbr->has_seen_rtt && tp->srtt_us))
264 bbr_init_pacing_rate_from_rtt(sk);
265 if (bbr_full_bw_reached(sk) || rate > sk->sk_pacing_rate)
266 sk->sk_pacing_rate = rate;
269 /* override sysctl_tcp_min_tso_segs */
270 static u32 bbr_min_tso_segs(struct sock *sk)
272 return sk->sk_pacing_rate < (bbr_min_tso_rate >> 3) ? 1 : 2;
275 static u32 bbr_tso_segs_goal(struct sock *sk)
277 struct tcp_sock *tp = tcp_sk(sk);
278 u32 segs, bytes;
280 /* Sort of tcp_tso_autosize() but ignoring
281 * driver provided sk_gso_max_size.
283 bytes = min_t(unsigned long, sk->sk_pacing_rate >> sk->sk_pacing_shift,
284 GSO_MAX_SIZE - 1 - MAX_TCP_HEADER);
285 segs = max_t(u32, bytes / tp->mss_cache, bbr_min_tso_segs(sk));
287 return min(segs, 0x7FU);
290 /* Save "last known good" cwnd so we can restore it after losses or PROBE_RTT */
291 static void bbr_save_cwnd(struct sock *sk)
293 struct tcp_sock *tp = tcp_sk(sk);
294 struct bbr *bbr = inet_csk_ca(sk);
296 if (bbr->prev_ca_state < TCP_CA_Recovery && bbr->mode != BBR_PROBE_RTT)
297 bbr->prior_cwnd = tp->snd_cwnd; /* this cwnd is good enough */
298 else /* loss recovery or BBR_PROBE_RTT have temporarily cut cwnd */
299 bbr->prior_cwnd = max(bbr->prior_cwnd, tp->snd_cwnd);
302 static void bbr_cwnd_event(struct sock *sk, enum tcp_ca_event event)
304 struct tcp_sock *tp = tcp_sk(sk);
305 struct bbr *bbr = inet_csk_ca(sk);
307 if (event == CA_EVENT_TX_START && tp->app_limited) {
308 bbr->idle_restart = 1;
309 /* Avoid pointless buffer overflows: pace at est. bw if we don't
310 * need more speed (we're restarting from idle and app-limited).
312 if (bbr->mode == BBR_PROBE_BW)
313 bbr_set_pacing_rate(sk, bbr_bw(sk), BBR_UNIT);
314 else if (bbr->mode == BBR_PROBE_RTT)
315 bbr_check_probe_rtt_done(sk);
319 /* Find target cwnd. Right-size the cwnd based on min RTT and the
320 * estimated bottleneck bandwidth:
322 * cwnd = bw * min_rtt * gain = BDP * gain
324 * The key factor, gain, controls the amount of queue. While a small gain
325 * builds a smaller queue, it becomes more vulnerable to noise in RTT
326 * measurements (e.g., delayed ACKs or other ACK compression effects). This
327 * noise may cause BBR to under-estimate the rate.
329 * To achieve full performance in high-speed paths, we budget enough cwnd to
330 * fit full-sized skbs in-flight on both end hosts to fully utilize the path:
331 * - one skb in sending host Qdisc,
332 * - one skb in sending host TSO/GSO engine
333 * - one skb being received by receiver host LRO/GRO/delayed-ACK engine
334 * Don't worry, at low rates (bbr_min_tso_rate) this won't bloat cwnd because
335 * in such cases tso_segs_goal is 1. The minimum cwnd is 4 packets,
336 * which allows 2 outstanding 2-packet sequences, to try to keep pipe
337 * full even with ACK-every-other-packet delayed ACKs.
339 static u32 bbr_target_cwnd(struct sock *sk, u32 bw, int gain)
341 struct bbr *bbr = inet_csk_ca(sk);
342 u32 cwnd;
343 u64 w;
345 /* If we've never had a valid RTT sample, cap cwnd at the initial
346 * default. This should only happen when the connection is not using TCP
347 * timestamps and has retransmitted all of the SYN/SYNACK/data packets
348 * ACKed so far. In this case, an RTO can cut cwnd to 1, in which
349 * case we need to slow-start up toward something safe: TCP_INIT_CWND.
351 if (unlikely(bbr->min_rtt_us == ~0U)) /* no valid RTT samples yet? */
352 return TCP_INIT_CWND; /* be safe: cap at default initial cwnd*/
354 w = (u64)bw * bbr->min_rtt_us;
356 /* Apply a gain to the given value, then remove the BW_SCALE shift. */
357 cwnd = (((w * gain) >> BBR_SCALE) + BW_UNIT - 1) / BW_UNIT;
359 /* Allow enough full-sized skbs in flight to utilize end systems. */
360 cwnd += 3 * bbr_tso_segs_goal(sk);
362 /* Reduce delayed ACKs by rounding up cwnd to the next even number. */
363 cwnd = (cwnd + 1) & ~1U;
365 /* Ensure gain cycling gets inflight above BDP even for small BDPs. */
366 if (bbr->mode == BBR_PROBE_BW && gain > BBR_UNIT)
367 cwnd += 2;
369 return cwnd;
372 /* With pacing at lower layers, there's often less data "in the network" than
373 * "in flight". With TSQ and departure time pacing at lower layers (e.g. fq),
374 * we often have several skbs queued in the pacing layer with a pre-scheduled
375 * earliest departure time (EDT). BBR adapts its pacing rate based on the
376 * inflight level that it estimates has already been "baked in" by previous
377 * departure time decisions. We calculate a rough estimate of the number of our
378 * packets that might be in the network at the earliest departure time for the
379 * next skb scheduled:
380 * in_network_at_edt = inflight_at_edt - (EDT - now) * bw
381 * If we're increasing inflight, then we want to know if the transmit of the
382 * EDT skb will push inflight above the target, so inflight_at_edt includes
383 * bbr_tso_segs_goal() from the skb departing at EDT. If decreasing inflight,
384 * then estimate if inflight will sink too low just before the EDT transmit.
386 static u32 bbr_packets_in_net_at_edt(struct sock *sk, u32 inflight_now)
388 struct tcp_sock *tp = tcp_sk(sk);
389 struct bbr *bbr = inet_csk_ca(sk);
390 u64 now_ns, edt_ns, interval_us;
391 u32 interval_delivered, inflight_at_edt;
393 now_ns = tp->tcp_clock_cache;
394 edt_ns = max(tp->tcp_wstamp_ns, now_ns);
395 interval_us = div_u64(edt_ns - now_ns, NSEC_PER_USEC);
396 interval_delivered = (u64)bbr_bw(sk) * interval_us >> BW_SCALE;
397 inflight_at_edt = inflight_now;
398 if (bbr->pacing_gain > BBR_UNIT) /* increasing inflight */
399 inflight_at_edt += bbr_tso_segs_goal(sk); /* include EDT skb */
400 if (interval_delivered >= inflight_at_edt)
401 return 0;
402 return inflight_at_edt - interval_delivered;
405 /* An optimization in BBR to reduce losses: On the first round of recovery, we
406 * follow the packet conservation principle: send P packets per P packets acked.
407 * After that, we slow-start and send at most 2*P packets per P packets acked.
408 * After recovery finishes, or upon undo, we restore the cwnd we had when
409 * recovery started (capped by the target cwnd based on estimated BDP).
411 * TODO(ycheng/ncardwell): implement a rate-based approach.
413 static bool bbr_set_cwnd_to_recover_or_restore(
414 struct sock *sk, const struct rate_sample *rs, u32 acked, u32 *new_cwnd)
416 struct tcp_sock *tp = tcp_sk(sk);
417 struct bbr *bbr = inet_csk_ca(sk);
418 u8 prev_state = bbr->prev_ca_state, state = inet_csk(sk)->icsk_ca_state;
419 u32 cwnd = tp->snd_cwnd;
421 /* An ACK for P pkts should release at most 2*P packets. We do this
422 * in two steps. First, here we deduct the number of lost packets.
423 * Then, in bbr_set_cwnd() we slow start up toward the target cwnd.
425 if (rs->losses > 0)
426 cwnd = max_t(s32, cwnd - rs->losses, 1);
428 if (state == TCP_CA_Recovery && prev_state != TCP_CA_Recovery) {
429 /* Starting 1st round of Recovery, so do packet conservation. */
430 bbr->packet_conservation = 1;
431 bbr->next_rtt_delivered = tp->delivered; /* start round now */
432 /* Cut unused cwnd from app behavior, TSQ, or TSO deferral: */
433 cwnd = tcp_packets_in_flight(tp) + acked;
434 } else if (prev_state >= TCP_CA_Recovery && state < TCP_CA_Recovery) {
435 /* Exiting loss recovery; restore cwnd saved before recovery. */
436 cwnd = max(cwnd, bbr->prior_cwnd);
437 bbr->packet_conservation = 0;
439 bbr->prev_ca_state = state;
441 if (bbr->packet_conservation) {
442 *new_cwnd = max(cwnd, tcp_packets_in_flight(tp) + acked);
443 return true; /* yes, using packet conservation */
445 *new_cwnd = cwnd;
446 return false;
449 /* Slow-start up toward target cwnd (if bw estimate is growing, or packet loss
450 * has drawn us down below target), or snap down to target if we're above it.
452 static void bbr_set_cwnd(struct sock *sk, const struct rate_sample *rs,
453 u32 acked, u32 bw, int gain)
455 struct tcp_sock *tp = tcp_sk(sk);
456 struct bbr *bbr = inet_csk_ca(sk);
457 u32 cwnd = tp->snd_cwnd, target_cwnd = 0;
459 if (!acked)
460 goto done; /* no packet fully ACKed; just apply caps */
462 if (bbr_set_cwnd_to_recover_or_restore(sk, rs, acked, &cwnd))
463 goto done;
465 /* If we're below target cwnd, slow start cwnd toward target cwnd. */
466 target_cwnd = bbr_target_cwnd(sk, bw, gain);
467 if (bbr_full_bw_reached(sk)) /* only cut cwnd if we filled the pipe */
468 cwnd = min(cwnd + acked, target_cwnd);
469 else if (cwnd < target_cwnd || tp->delivered < TCP_INIT_CWND)
470 cwnd = cwnd + acked;
471 cwnd = max(cwnd, bbr_cwnd_min_target);
473 done:
474 tp->snd_cwnd = min(cwnd, tp->snd_cwnd_clamp); /* apply global cap */
475 if (bbr->mode == BBR_PROBE_RTT) /* drain queue, refresh min_rtt */
476 tp->snd_cwnd = min(tp->snd_cwnd, bbr_cwnd_min_target);
479 /* End cycle phase if it's time and/or we hit the phase's in-flight target. */
480 static bool bbr_is_next_cycle_phase(struct sock *sk,
481 const struct rate_sample *rs)
483 struct tcp_sock *tp = tcp_sk(sk);
484 struct bbr *bbr = inet_csk_ca(sk);
485 bool is_full_length =
486 tcp_stamp_us_delta(tp->delivered_mstamp, bbr->cycle_mstamp) >
487 bbr->min_rtt_us;
488 u32 inflight, bw;
490 /* The pacing_gain of 1.0 paces at the estimated bw to try to fully
491 * use the pipe without increasing the queue.
493 if (bbr->pacing_gain == BBR_UNIT)
494 return is_full_length; /* just use wall clock time */
496 inflight = bbr_packets_in_net_at_edt(sk, rs->prior_in_flight);
497 bw = bbr_max_bw(sk);
499 /* A pacing_gain > 1.0 probes for bw by trying to raise inflight to at
500 * least pacing_gain*BDP; this may take more than min_rtt if min_rtt is
501 * small (e.g. on a LAN). We do not persist if packets are lost, since
502 * a path with small buffers may not hold that much.
504 if (bbr->pacing_gain > BBR_UNIT)
505 return is_full_length &&
506 (rs->losses || /* perhaps pacing_gain*BDP won't fit */
507 inflight >= bbr_target_cwnd(sk, bw, bbr->pacing_gain));
509 /* A pacing_gain < 1.0 tries to drain extra queue we added if bw
510 * probing didn't find more bw. If inflight falls to match BDP then we
511 * estimate queue is drained; persisting would underutilize the pipe.
513 return is_full_length ||
514 inflight <= bbr_target_cwnd(sk, bw, BBR_UNIT);
517 static void bbr_advance_cycle_phase(struct sock *sk)
519 struct tcp_sock *tp = tcp_sk(sk);
520 struct bbr *bbr = inet_csk_ca(sk);
522 bbr->cycle_idx = (bbr->cycle_idx + 1) & (CYCLE_LEN - 1);
523 bbr->cycle_mstamp = tp->delivered_mstamp;
526 /* Gain cycling: cycle pacing gain to converge to fair share of available bw. */
527 static void bbr_update_cycle_phase(struct sock *sk,
528 const struct rate_sample *rs)
530 struct bbr *bbr = inet_csk_ca(sk);
532 if (bbr->mode == BBR_PROBE_BW && bbr_is_next_cycle_phase(sk, rs))
533 bbr_advance_cycle_phase(sk);
536 static void bbr_reset_startup_mode(struct sock *sk)
538 struct bbr *bbr = inet_csk_ca(sk);
540 bbr->mode = BBR_STARTUP;
543 static void bbr_reset_probe_bw_mode(struct sock *sk)
545 struct bbr *bbr = inet_csk_ca(sk);
547 bbr->mode = BBR_PROBE_BW;
548 bbr->cycle_idx = CYCLE_LEN - 1 - prandom_u32_max(bbr_cycle_rand);
549 bbr_advance_cycle_phase(sk); /* flip to next phase of gain cycle */
552 static void bbr_reset_mode(struct sock *sk)
554 if (!bbr_full_bw_reached(sk))
555 bbr_reset_startup_mode(sk);
556 else
557 bbr_reset_probe_bw_mode(sk);
560 /* Start a new long-term sampling interval. */
561 static void bbr_reset_lt_bw_sampling_interval(struct sock *sk)
563 struct tcp_sock *tp = tcp_sk(sk);
564 struct bbr *bbr = inet_csk_ca(sk);
566 bbr->lt_last_stamp = div_u64(tp->delivered_mstamp, USEC_PER_MSEC);
567 bbr->lt_last_delivered = tp->delivered;
568 bbr->lt_last_lost = tp->lost;
569 bbr->lt_rtt_cnt = 0;
572 /* Completely reset long-term bandwidth sampling. */
573 static void bbr_reset_lt_bw_sampling(struct sock *sk)
575 struct bbr *bbr = inet_csk_ca(sk);
577 bbr->lt_bw = 0;
578 bbr->lt_use_bw = 0;
579 bbr->lt_is_sampling = false;
580 bbr_reset_lt_bw_sampling_interval(sk);
583 /* Long-term bw sampling interval is done. Estimate whether we're policed. */
584 static void bbr_lt_bw_interval_done(struct sock *sk, u32 bw)
586 struct bbr *bbr = inet_csk_ca(sk);
587 u32 diff;
589 if (bbr->lt_bw) { /* do we have bw from a previous interval? */
590 /* Is new bw close to the lt_bw from the previous interval? */
591 diff = abs(bw - bbr->lt_bw);
592 if ((diff * BBR_UNIT <= bbr_lt_bw_ratio * bbr->lt_bw) ||
593 (bbr_rate_bytes_per_sec(sk, diff, BBR_UNIT) <=
594 bbr_lt_bw_diff)) {
595 /* All criteria are met; estimate we're policed. */
596 bbr->lt_bw = (bw + bbr->lt_bw) >> 1; /* avg 2 intvls */
597 bbr->lt_use_bw = 1;
598 bbr->pacing_gain = BBR_UNIT; /* try to avoid drops */
599 bbr->lt_rtt_cnt = 0;
600 return;
603 bbr->lt_bw = bw;
604 bbr_reset_lt_bw_sampling_interval(sk);
607 /* Token-bucket traffic policers are common (see "An Internet-Wide Analysis of
608 * Traffic Policing", SIGCOMM 2016). BBR detects token-bucket policers and
609 * explicitly models their policed rate, to reduce unnecessary losses. We
610 * estimate that we're policed if we see 2 consecutive sampling intervals with
611 * consistent throughput and high packet loss. If we think we're being policed,
612 * set lt_bw to the "long-term" average delivery rate from those 2 intervals.
614 static void bbr_lt_bw_sampling(struct sock *sk, const struct rate_sample *rs)
616 struct tcp_sock *tp = tcp_sk(sk);
617 struct bbr *bbr = inet_csk_ca(sk);
618 u32 lost, delivered;
619 u64 bw;
620 u32 t;
622 if (bbr->lt_use_bw) { /* already using long-term rate, lt_bw? */
623 if (bbr->mode == BBR_PROBE_BW && bbr->round_start &&
624 ++bbr->lt_rtt_cnt >= bbr_lt_bw_max_rtts) {
625 bbr_reset_lt_bw_sampling(sk); /* stop using lt_bw */
626 bbr_reset_probe_bw_mode(sk); /* restart gain cycling */
628 return;
631 /* Wait for the first loss before sampling, to let the policer exhaust
632 * its tokens and estimate the steady-state rate allowed by the policer.
633 * Starting samples earlier includes bursts that over-estimate the bw.
635 if (!bbr->lt_is_sampling) {
636 if (!rs->losses)
637 return;
638 bbr_reset_lt_bw_sampling_interval(sk);
639 bbr->lt_is_sampling = true;
642 /* To avoid underestimates, reset sampling if we run out of data. */
643 if (rs->is_app_limited) {
644 bbr_reset_lt_bw_sampling(sk);
645 return;
648 if (bbr->round_start)
649 bbr->lt_rtt_cnt++; /* count round trips in this interval */
650 if (bbr->lt_rtt_cnt < bbr_lt_intvl_min_rtts)
651 return; /* sampling interval needs to be longer */
652 if (bbr->lt_rtt_cnt > 4 * bbr_lt_intvl_min_rtts) {
653 bbr_reset_lt_bw_sampling(sk); /* interval is too long */
654 return;
657 /* End sampling interval when a packet is lost, so we estimate the
658 * policer tokens were exhausted. Stopping the sampling before the
659 * tokens are exhausted under-estimates the policed rate.
661 if (!rs->losses)
662 return;
664 /* Calculate packets lost and delivered in sampling interval. */
665 lost = tp->lost - bbr->lt_last_lost;
666 delivered = tp->delivered - bbr->lt_last_delivered;
667 /* Is loss rate (lost/delivered) >= lt_loss_thresh? If not, wait. */
668 if (!delivered || (lost << BBR_SCALE) < bbr_lt_loss_thresh * delivered)
669 return;
671 /* Find average delivery rate in this sampling interval. */
672 t = div_u64(tp->delivered_mstamp, USEC_PER_MSEC) - bbr->lt_last_stamp;
673 if ((s32)t < 1)
674 return; /* interval is less than one ms, so wait */
675 /* Check if can multiply without overflow */
676 if (t >= ~0U / USEC_PER_MSEC) {
677 bbr_reset_lt_bw_sampling(sk); /* interval too long; reset */
678 return;
680 t *= USEC_PER_MSEC;
681 bw = (u64)delivered * BW_UNIT;
682 do_div(bw, t);
683 bbr_lt_bw_interval_done(sk, bw);
686 /* Estimate the bandwidth based on how fast packets are delivered */
687 static void bbr_update_bw(struct sock *sk, const struct rate_sample *rs)
689 struct tcp_sock *tp = tcp_sk(sk);
690 struct bbr *bbr = inet_csk_ca(sk);
691 u64 bw;
693 bbr->round_start = 0;
694 if (rs->delivered < 0 || rs->interval_us <= 0)
695 return; /* Not a valid observation */
697 /* See if we've reached the next RTT */
698 if (!before(rs->prior_delivered, bbr->next_rtt_delivered)) {
699 bbr->next_rtt_delivered = tp->delivered;
700 bbr->rtt_cnt++;
701 bbr->round_start = 1;
702 bbr->packet_conservation = 0;
705 bbr_lt_bw_sampling(sk, rs);
707 /* Divide delivered by the interval to find a (lower bound) bottleneck
708 * bandwidth sample. Delivered is in packets and interval_us in uS and
709 * ratio will be <<1 for most connections. So delivered is first scaled.
711 bw = (u64)rs->delivered * BW_UNIT;
712 do_div(bw, rs->interval_us);
714 /* If this sample is application-limited, it is likely to have a very
715 * low delivered count that represents application behavior rather than
716 * the available network rate. Such a sample could drag down estimated
717 * bw, causing needless slow-down. Thus, to continue to send at the
718 * last measured network rate, we filter out app-limited samples unless
719 * they describe the path bw at least as well as our bw model.
721 * So the goal during app-limited phase is to proceed with the best
722 * network rate no matter how long. We automatically leave this
723 * phase when app writes faster than the network can deliver :)
725 if (!rs->is_app_limited || bw >= bbr_max_bw(sk)) {
726 /* Incorporate new sample into our max bw filter. */
727 minmax_running_max(&bbr->bw, bbr_bw_rtts, bbr->rtt_cnt, bw);
731 /* Estimate when the pipe is full, using the change in delivery rate: BBR
732 * estimates that STARTUP filled the pipe if the estimated bw hasn't changed by
733 * at least bbr_full_bw_thresh (25%) after bbr_full_bw_cnt (3) non-app-limited
734 * rounds. Why 3 rounds: 1: rwin autotuning grows the rwin, 2: we fill the
735 * higher rwin, 3: we get higher delivery rate samples. Or transient
736 * cross-traffic or radio noise can go away. CUBIC Hystart shares a similar
737 * design goal, but uses delay and inter-ACK spacing instead of bandwidth.
739 static void bbr_check_full_bw_reached(struct sock *sk,
740 const struct rate_sample *rs)
742 struct bbr *bbr = inet_csk_ca(sk);
743 u32 bw_thresh;
745 if (bbr_full_bw_reached(sk) || !bbr->round_start || rs->is_app_limited)
746 return;
748 bw_thresh = (u64)bbr->full_bw * bbr_full_bw_thresh >> BBR_SCALE;
749 if (bbr_max_bw(sk) >= bw_thresh) {
750 bbr->full_bw = bbr_max_bw(sk);
751 bbr->full_bw_cnt = 0;
752 return;
754 ++bbr->full_bw_cnt;
755 bbr->full_bw_reached = bbr->full_bw_cnt >= bbr_full_bw_cnt;
758 /* If pipe is probably full, drain the queue and then enter steady-state. */
759 static void bbr_check_drain(struct sock *sk, const struct rate_sample *rs)
761 struct bbr *bbr = inet_csk_ca(sk);
763 if (bbr->mode == BBR_STARTUP && bbr_full_bw_reached(sk)) {
764 bbr->mode = BBR_DRAIN; /* drain queue we created */
765 tcp_sk(sk)->snd_ssthresh =
766 bbr_target_cwnd(sk, bbr_max_bw(sk), BBR_UNIT);
767 } /* fall through to check if in-flight is already small: */
768 if (bbr->mode == BBR_DRAIN &&
769 bbr_packets_in_net_at_edt(sk, tcp_packets_in_flight(tcp_sk(sk))) <=
770 bbr_target_cwnd(sk, bbr_max_bw(sk), BBR_UNIT))
771 bbr_reset_probe_bw_mode(sk); /* we estimate queue is drained */
774 static void bbr_check_probe_rtt_done(struct sock *sk)
776 struct tcp_sock *tp = tcp_sk(sk);
777 struct bbr *bbr = inet_csk_ca(sk);
779 if (!(bbr->probe_rtt_done_stamp &&
780 after(tcp_jiffies32, bbr->probe_rtt_done_stamp)))
781 return;
783 bbr->min_rtt_stamp = tcp_jiffies32; /* wait a while until PROBE_RTT */
784 tp->snd_cwnd = max(tp->snd_cwnd, bbr->prior_cwnd);
785 bbr_reset_mode(sk);
788 /* The goal of PROBE_RTT mode is to have BBR flows cooperatively and
789 * periodically drain the bottleneck queue, to converge to measure the true
790 * min_rtt (unloaded propagation delay). This allows the flows to keep queues
791 * small (reducing queuing delay and packet loss) and achieve fairness among
792 * BBR flows.
794 * The min_rtt filter window is 10 seconds. When the min_rtt estimate expires,
795 * we enter PROBE_RTT mode and cap the cwnd at bbr_cwnd_min_target=4 packets.
796 * After at least bbr_probe_rtt_mode_ms=200ms and at least one packet-timed
797 * round trip elapsed with that flight size <= 4, we leave PROBE_RTT mode and
798 * re-enter the previous mode. BBR uses 200ms to approximately bound the
799 * performance penalty of PROBE_RTT's cwnd capping to roughly 2% (200ms/10s).
801 * Note that flows need only pay 2% if they are busy sending over the last 10
802 * seconds. Interactive applications (e.g., Web, RPCs, video chunks) often have
803 * natural silences or low-rate periods within 10 seconds where the rate is low
804 * enough for long enough to drain its queue in the bottleneck. We pick up
805 * these min RTT measurements opportunistically with our min_rtt filter. :-)
807 static void bbr_update_min_rtt(struct sock *sk, const struct rate_sample *rs)
809 struct tcp_sock *tp = tcp_sk(sk);
810 struct bbr *bbr = inet_csk_ca(sk);
811 bool filter_expired;
813 /* Track min RTT seen in the min_rtt_win_sec filter window: */
814 filter_expired = after(tcp_jiffies32,
815 bbr->min_rtt_stamp + bbr_min_rtt_win_sec * HZ);
816 if (rs->rtt_us >= 0 &&
817 (rs->rtt_us <= bbr->min_rtt_us ||
818 (filter_expired && !rs->is_ack_delayed))) {
819 bbr->min_rtt_us = rs->rtt_us;
820 bbr->min_rtt_stamp = tcp_jiffies32;
823 if (bbr_probe_rtt_mode_ms > 0 && filter_expired &&
824 !bbr->idle_restart && bbr->mode != BBR_PROBE_RTT) {
825 bbr->mode = BBR_PROBE_RTT; /* dip, drain queue */
826 bbr_save_cwnd(sk); /* note cwnd so we can restore it */
827 bbr->probe_rtt_done_stamp = 0;
830 if (bbr->mode == BBR_PROBE_RTT) {
831 /* Ignore low rate samples during this mode. */
832 tp->app_limited =
833 (tp->delivered + tcp_packets_in_flight(tp)) ? : 1;
834 /* Maintain min packets in flight for max(200 ms, 1 round). */
835 if (!bbr->probe_rtt_done_stamp &&
836 tcp_packets_in_flight(tp) <= bbr_cwnd_min_target) {
837 bbr->probe_rtt_done_stamp = tcp_jiffies32 +
838 msecs_to_jiffies(bbr_probe_rtt_mode_ms);
839 bbr->probe_rtt_round_done = 0;
840 bbr->next_rtt_delivered = tp->delivered;
841 } else if (bbr->probe_rtt_done_stamp) {
842 if (bbr->round_start)
843 bbr->probe_rtt_round_done = 1;
844 if (bbr->probe_rtt_round_done)
845 bbr_check_probe_rtt_done(sk);
848 /* Restart after idle ends only once we process a new S/ACK for data */
849 if (rs->delivered > 0)
850 bbr->idle_restart = 0;
853 static void bbr_update_gains(struct sock *sk)
855 struct bbr *bbr = inet_csk_ca(sk);
857 switch (bbr->mode) {
858 case BBR_STARTUP:
859 bbr->pacing_gain = bbr_high_gain;
860 bbr->cwnd_gain = bbr_high_gain;
861 break;
862 case BBR_DRAIN:
863 bbr->pacing_gain = bbr_drain_gain; /* slow, to drain */
864 bbr->cwnd_gain = bbr_high_gain; /* keep cwnd */
865 break;
866 case BBR_PROBE_BW:
867 bbr->pacing_gain = (bbr->lt_use_bw ?
868 BBR_UNIT :
869 bbr_pacing_gain[bbr->cycle_idx]);
870 bbr->cwnd_gain = bbr_cwnd_gain;
871 break;
872 case BBR_PROBE_RTT:
873 bbr->pacing_gain = BBR_UNIT;
874 bbr->cwnd_gain = BBR_UNIT;
875 break;
876 default:
877 WARN_ONCE(1, "BBR bad mode: %u\n", bbr->mode);
878 break;
882 static void bbr_update_model(struct sock *sk, const struct rate_sample *rs)
884 bbr_update_bw(sk, rs);
885 bbr_update_cycle_phase(sk, rs);
886 bbr_check_full_bw_reached(sk, rs);
887 bbr_check_drain(sk, rs);
888 bbr_update_min_rtt(sk, rs);
889 bbr_update_gains(sk);
892 static void bbr_main(struct sock *sk, const struct rate_sample *rs)
894 struct bbr *bbr = inet_csk_ca(sk);
895 u32 bw;
897 bbr_update_model(sk, rs);
899 bw = bbr_bw(sk);
900 bbr_set_pacing_rate(sk, bw, bbr->pacing_gain);
901 bbr_set_cwnd(sk, rs, rs->acked_sacked, bw, bbr->cwnd_gain);
904 static void bbr_init(struct sock *sk)
906 struct tcp_sock *tp = tcp_sk(sk);
907 struct bbr *bbr = inet_csk_ca(sk);
909 bbr->prior_cwnd = 0;
910 tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
911 bbr->rtt_cnt = 0;
912 bbr->next_rtt_delivered = 0;
913 bbr->prev_ca_state = TCP_CA_Open;
914 bbr->packet_conservation = 0;
916 bbr->probe_rtt_done_stamp = 0;
917 bbr->probe_rtt_round_done = 0;
918 bbr->min_rtt_us = tcp_min_rtt(tp);
919 bbr->min_rtt_stamp = tcp_jiffies32;
921 minmax_reset(&bbr->bw, bbr->rtt_cnt, 0); /* init max bw to 0 */
923 bbr->has_seen_rtt = 0;
924 bbr_init_pacing_rate_from_rtt(sk);
926 bbr->round_start = 0;
927 bbr->idle_restart = 0;
928 bbr->full_bw_reached = 0;
929 bbr->full_bw = 0;
930 bbr->full_bw_cnt = 0;
931 bbr->cycle_mstamp = 0;
932 bbr->cycle_idx = 0;
933 bbr_reset_lt_bw_sampling(sk);
934 bbr_reset_startup_mode(sk);
936 cmpxchg(&sk->sk_pacing_status, SK_PACING_NONE, SK_PACING_NEEDED);
939 static u32 bbr_sndbuf_expand(struct sock *sk)
941 /* Provision 3 * cwnd since BBR may slow-start even during recovery. */
942 return 3;
945 /* In theory BBR does not need to undo the cwnd since it does not
946 * always reduce cwnd on losses (see bbr_main()). Keep it for now.
948 static u32 bbr_undo_cwnd(struct sock *sk)
950 struct bbr *bbr = inet_csk_ca(sk);
952 bbr->full_bw = 0; /* spurious slow-down; reset full pipe detection */
953 bbr->full_bw_cnt = 0;
954 bbr_reset_lt_bw_sampling(sk);
955 return tcp_sk(sk)->snd_cwnd;
958 /* Entering loss recovery, so save cwnd for when we exit or undo recovery. */
959 static u32 bbr_ssthresh(struct sock *sk)
961 bbr_save_cwnd(sk);
962 return tcp_sk(sk)->snd_ssthresh;
965 static size_t bbr_get_info(struct sock *sk, u32 ext, int *attr,
966 union tcp_cc_info *info)
968 if (ext & (1 << (INET_DIAG_BBRINFO - 1)) ||
969 ext & (1 << (INET_DIAG_VEGASINFO - 1))) {
970 struct tcp_sock *tp = tcp_sk(sk);
971 struct bbr *bbr = inet_csk_ca(sk);
972 u64 bw = bbr_bw(sk);
974 bw = bw * tp->mss_cache * USEC_PER_SEC >> BW_SCALE;
975 memset(&info->bbr, 0, sizeof(info->bbr));
976 info->bbr.bbr_bw_lo = (u32)bw;
977 info->bbr.bbr_bw_hi = (u32)(bw >> 32);
978 info->bbr.bbr_min_rtt = bbr->min_rtt_us;
979 info->bbr.bbr_pacing_gain = bbr->pacing_gain;
980 info->bbr.bbr_cwnd_gain = bbr->cwnd_gain;
981 *attr = INET_DIAG_BBRINFO;
982 return sizeof(info->bbr);
984 return 0;
987 static void bbr_set_state(struct sock *sk, u8 new_state)
989 struct bbr *bbr = inet_csk_ca(sk);
991 if (new_state == TCP_CA_Loss) {
992 struct rate_sample rs = { .losses = 1 };
994 bbr->prev_ca_state = TCP_CA_Loss;
995 bbr->full_bw = 0;
996 bbr->round_start = 1; /* treat RTO like end of a round */
997 bbr_lt_bw_sampling(sk, &rs);
1001 static struct tcp_congestion_ops tcp_bbr_cong_ops __read_mostly = {
1002 .flags = TCP_CONG_NON_RESTRICTED,
1003 .name = "bbr",
1004 .owner = THIS_MODULE,
1005 .init = bbr_init,
1006 .cong_control = bbr_main,
1007 .sndbuf_expand = bbr_sndbuf_expand,
1008 .undo_cwnd = bbr_undo_cwnd,
1009 .cwnd_event = bbr_cwnd_event,
1010 .ssthresh = bbr_ssthresh,
1011 .min_tso_segs = bbr_min_tso_segs,
1012 .get_info = bbr_get_info,
1013 .set_state = bbr_set_state,
1016 static int __init bbr_register(void)
1018 BUILD_BUG_ON(sizeof(struct bbr) > ICSK_CA_PRIV_SIZE);
1019 return tcp_register_congestion_control(&tcp_bbr_cong_ops);
1022 static void __exit bbr_unregister(void)
1024 tcp_unregister_congestion_control(&tcp_bbr_cong_ops);
1027 module_init(bbr_register);
1028 module_exit(bbr_unregister);
1030 MODULE_AUTHOR("Van Jacobson <vanj@google.com>");
1031 MODULE_AUTHOR("Neal Cardwell <ncardwell@google.com>");
1032 MODULE_AUTHOR("Yuchung Cheng <ycheng@google.com>");
1033 MODULE_AUTHOR("Soheil Hassas Yeganeh <soheil@google.com>");
1034 MODULE_LICENSE("Dual BSD/GPL");
1035 MODULE_DESCRIPTION("TCP BBR (Bottleneck Bandwidth and RTT)");