blob: 0096ca5b0954085b9bdd5d570415f69f2b90e516 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/congestion_control/bbr_sender.h"
6
7#include <algorithm>
8#include <sstream>
vasilvv872e7a32019-03-12 16:42:44 -07009#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -050010
11#include "net/third_party/quiche/src/quic/core/congestion_control/rtt_stats.h"
12#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
wub967ba572019-04-01 09:27:52 -070013#include "net/third_party/quiche/src/quic/core/quic_time.h"
wubbe29b9e2019-11-24 06:56:04 -080014#include "net/third_party/quiche/src/quic/core/quic_time_accumulator.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050015#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
16#include "net/third_party/quiche/src/quic/platform/api/quic_fallthrough.h"
17#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
18#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
19#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050020
21namespace quic {
22
23namespace {
24// Constants based on TCP defaults.
25// The minimum CWND to ensure delayed acks don't reduce bandwidth measurements.
26// Does not inflate the pacing rate.
27const QuicByteCount kDefaultMinimumCongestionWindow = 4 * kMaxSegmentSize;
28
29// The gain used for the STARTUP, equal to 2/ln(2).
30const float kDefaultHighGain = 2.885f;
31// The newly derived gain for STARTUP, equal to 4 * ln(2)
32const float kDerivedHighGain = 2.773f;
33// The newly derived CWND gain for STARTUP, 2.
wub5b352f12019-05-07 11:45:26 -070034const float kDerivedHighCWNDGain = 2.0f;
QUICHE teama6ef0a62019-03-07 20:34:33 -050035// The gain used in STARTUP after loss has been detected.
36// 1.5 is enough to allow for 25% exogenous loss and still observe a 25% growth
37// in measured bandwidth.
38const float kStartupAfterLossGain = 1.5f;
39// The cycle of gains used during the PROBE_BW stage.
40const float kPacingGain[] = {1.25, 0.75, 1, 1, 1, 1, 1, 1};
41
42// The length of the gain cycle.
43const size_t kGainCycleLength = sizeof(kPacingGain) / sizeof(kPacingGain[0]);
44// The size of the bandwidth filter window, in round-trips.
45const QuicRoundTripCount kBandwidthWindowSize = kGainCycleLength + 2;
46
47// The time after which the current min_rtt value expires.
48const QuicTime::Delta kMinRttExpiry = QuicTime::Delta::FromSeconds(10);
49// The minimum time the connection can spend in PROBE_RTT mode.
50const QuicTime::Delta kProbeRttTime = QuicTime::Delta::FromMilliseconds(200);
51// If the bandwidth does not increase by the factor of |kStartupGrowthTarget|
52// within |kRoundTripsWithoutGrowthBeforeExitingStartup| rounds, the connection
53// will exit the STARTUP mode.
54const float kStartupGrowthTarget = 1.25;
55const QuicRoundTripCount kRoundTripsWithoutGrowthBeforeExitingStartup = 3;
56// Coefficient of target congestion window to use when basing PROBE_RTT on BDP.
57const float kModerateProbeRttMultiplier = 0.75;
58// Coefficient to determine if a new RTT is sufficiently similar to min_rtt that
59// we don't need to enter PROBE_RTT.
60const float kSimilarMinRttThreshold = 1.125;
61
62} // namespace
63
64BbrSender::DebugState::DebugState(const BbrSender& sender)
65 : mode(sender.mode_),
66 max_bandwidth(sender.max_bandwidth_.GetBest()),
67 round_trip_count(sender.round_trip_count_),
68 gain_cycle_index(sender.cycle_current_offset_),
69 congestion_window(sender.congestion_window_),
70 is_at_full_bandwidth(sender.is_at_full_bandwidth_),
71 bandwidth_at_last_round(sender.bandwidth_at_last_round_),
72 rounds_without_bandwidth_gain(sender.rounds_without_bandwidth_gain_),
73 min_rtt(sender.min_rtt_),
74 min_rtt_timestamp(sender.min_rtt_timestamp_),
75 recovery_state(sender.recovery_state_),
76 recovery_window(sender.recovery_window_),
77 last_sample_is_app_limited(sender.last_sample_is_app_limited_),
78 end_of_app_limited_phase(sender.sampler_.end_of_app_limited_phase()) {}
79
80BbrSender::DebugState::DebugState(const DebugState& state) = default;
81
wub967ba572019-04-01 09:27:52 -070082BbrSender::BbrSender(QuicTime now,
83 const RttStats* rtt_stats,
QUICHE teama6ef0a62019-03-07 20:34:33 -050084 const QuicUnackedPacketMap* unacked_packets,
85 QuicPacketCount initial_tcp_congestion_window,
86 QuicPacketCount max_tcp_congestion_window,
wub967ba572019-04-01 09:27:52 -070087 QuicRandom* random,
88 QuicConnectionStats* stats)
QUICHE teama6ef0a62019-03-07 20:34:33 -050089 : rtt_stats_(rtt_stats),
90 unacked_packets_(unacked_packets),
91 random_(random),
wub967ba572019-04-01 09:27:52 -070092 stats_(stats),
QUICHE teama6ef0a62019-03-07 20:34:33 -050093 mode_(STARTUP),
vasilvv4abb5662019-08-14 08:23:49 -070094 sampler_(unacked_packets, kBandwidthWindowSize),
QUICHE teama6ef0a62019-03-07 20:34:33 -050095 round_trip_count_(0),
96 max_bandwidth_(kBandwidthWindowSize, QuicBandwidth::Zero(), 0),
QUICHE teama6ef0a62019-03-07 20:34:33 -050097 min_rtt_(QuicTime::Delta::Zero()),
98 min_rtt_timestamp_(QuicTime::Zero()),
99 congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS),
100 initial_congestion_window_(initial_tcp_congestion_window *
101 kDefaultTCPMSS),
102 max_congestion_window_(max_tcp_congestion_window * kDefaultTCPMSS),
103 min_congestion_window_(kDefaultMinimumCongestionWindow),
104 high_gain_(kDefaultHighGain),
105 high_cwnd_gain_(kDefaultHighGain),
106 drain_gain_(1.f / kDefaultHighGain),
107 pacing_rate_(QuicBandwidth::Zero()),
108 pacing_gain_(1),
109 congestion_window_gain_(1),
110 congestion_window_gain_constant_(
danzh88e3e052019-06-13 11:47:18 -0700111 static_cast<float>(GetQuicFlag(FLAGS_quic_bbr_cwnd_gain))),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500112 num_startup_rtts_(kRoundTripsWithoutGrowthBeforeExitingStartup),
113 exit_startup_on_loss_(false),
114 cycle_current_offset_(0),
115 last_cycle_start_(QuicTime::Zero()),
116 is_at_full_bandwidth_(false),
117 rounds_without_bandwidth_gain_(0),
118 bandwidth_at_last_round_(QuicBandwidth::Zero()),
119 exiting_quiescence_(false),
120 exit_probe_rtt_at_(QuicTime::Zero()),
121 probe_rtt_round_passed_(false),
122 last_sample_is_app_limited_(false),
123 has_non_app_limited_sample_(false),
124 flexible_app_limited_(false),
125 recovery_state_(NOT_IN_RECOVERY),
126 recovery_window_(max_congestion_window_),
QUICHE teama6ef0a62019-03-07 20:34:33 -0500127 slower_startup_(false),
128 rate_based_startup_(false),
129 startup_rate_reduction_multiplier_(0),
130 startup_bytes_lost_(0),
131 enable_ack_aggregation_during_startup_(false),
132 expire_ack_aggregation_in_startup_(false),
133 drain_to_target_(false),
134 probe_rtt_based_on_bdp_(false),
135 probe_rtt_skipped_if_similar_rtt_(false),
136 probe_rtt_disabled_if_app_limited_(false),
137 app_limited_since_last_probe_rtt_(false),
wub64c34112019-08-19 11:54:55 -0700138 min_rtt_since_last_probe_rtt_(QuicTime::Delta::Infinite()) {
wub967ba572019-04-01 09:27:52 -0700139 if (stats_) {
wubbe29b9e2019-11-24 06:56:04 -0800140 // Clear some startup stats if |stats_| has been used by another sender,
141 // which happens e.g. when QuicConnection switch send algorithms.
wub967ba572019-04-01 09:27:52 -0700142 stats_->slowstart_count = 0;
wubbe29b9e2019-11-24 06:56:04 -0800143 stats_->slowstart_duration = QuicTimeAccumulator();
wub967ba572019-04-01 09:27:52 -0700144 }
145 EnterStartupMode(now);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500146}
147
148BbrSender::~BbrSender() {}
149
150void BbrSender::SetInitialCongestionWindowInPackets(
151 QuicPacketCount congestion_window) {
152 if (mode_ == STARTUP) {
153 initial_congestion_window_ = congestion_window * kDefaultTCPMSS;
154 congestion_window_ = congestion_window * kDefaultTCPMSS;
155 }
156}
157
158bool BbrSender::InSlowStart() const {
159 return mode_ == STARTUP;
160}
161
162void BbrSender::OnPacketSent(QuicTime sent_time,
163 QuicByteCount bytes_in_flight,
164 QuicPacketNumber packet_number,
165 QuicByteCount bytes,
166 HasRetransmittableData is_retransmittable) {
wub967ba572019-04-01 09:27:52 -0700167 if (stats_ && InSlowStart()) {
168 ++stats_->slowstart_packets_sent;
169 stats_->slowstart_bytes_sent += bytes;
170 }
171
QUICHE teama6ef0a62019-03-07 20:34:33 -0500172 last_sent_packet_ = packet_number;
173
174 if (bytes_in_flight == 0 && sampler_.is_app_limited()) {
175 exiting_quiescence_ = true;
176 }
177
QUICHE teama6ef0a62019-03-07 20:34:33 -0500178 sampler_.OnPacketSent(sent_time, packet_number, bytes, bytes_in_flight,
179 is_retransmittable);
180}
181
182bool BbrSender::CanSend(QuicByteCount bytes_in_flight) {
183 return bytes_in_flight < GetCongestionWindow();
184}
185
dschinazi17d42422019-06-18 16:35:07 -0700186QuicBandwidth BbrSender::PacingRate(QuicByteCount /*bytes_in_flight*/) const {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500187 if (pacing_rate_.IsZero()) {
188 return high_gain_ * QuicBandwidth::FromBytesAndTimeDelta(
189 initial_congestion_window_, GetMinRtt());
190 }
191 return pacing_rate_;
192}
193
194QuicBandwidth BbrSender::BandwidthEstimate() const {
195 return max_bandwidth_.GetBest();
196}
197
198QuicByteCount BbrSender::GetCongestionWindow() const {
199 if (mode_ == PROBE_RTT) {
200 return ProbeRttCongestionWindow();
201 }
202
203 if (InRecovery() && !(rate_based_startup_ && mode_ == STARTUP)) {
204 return std::min(congestion_window_, recovery_window_);
205 }
206
207 return congestion_window_;
208}
209
210QuicByteCount BbrSender::GetSlowStartThreshold() const {
211 return 0;
212}
213
214bool BbrSender::InRecovery() const {
215 return recovery_state_ != NOT_IN_RECOVERY;
216}
217
218bool BbrSender::ShouldSendProbingPacket() const {
219 if (pacing_gain_ <= 1) {
220 return false;
221 }
222
223 // TODO(b/77975811): If the pipe is highly under-utilized, consider not
224 // sending a probing transmission, because the extra bandwidth is not needed.
225 // If flexible_app_limited is enabled, check if the pipe is sufficiently full.
226 if (flexible_app_limited_) {
227 return !IsPipeSufficientlyFull();
228 } else {
229 return true;
230 }
231}
232
233bool BbrSender::IsPipeSufficientlyFull() const {
234 // See if we need more bytes in flight to see more bandwidth.
235 if (mode_ == STARTUP) {
236 // STARTUP exits if it doesn't observe a 25% bandwidth increase, so the CWND
237 // must be more than 25% above the target.
238 return unacked_packets_->bytes_in_flight() >=
239 GetTargetCongestionWindow(1.5);
240 }
241 if (pacing_gain_ > 1) {
242 // Super-unity PROBE_BW doesn't exit until 1.25 * BDP is achieved.
243 return unacked_packets_->bytes_in_flight() >=
244 GetTargetCongestionWindow(pacing_gain_);
245 }
246 // If bytes_in_flight are above the target congestion window, it should be
247 // possible to observe the same or more bandwidth if it's available.
248 return unacked_packets_->bytes_in_flight() >= GetTargetCongestionWindow(1.1);
249}
250
251void BbrSender::SetFromConfig(const QuicConfig& config,
252 Perspective perspective) {
253 if (config.HasClientRequestedIndependentOption(kLRTT, perspective)) {
254 exit_startup_on_loss_ = true;
255 }
256 if (config.HasClientRequestedIndependentOption(k1RTT, perspective)) {
257 num_startup_rtts_ = 1;
258 }
259 if (config.HasClientRequestedIndependentOption(k2RTT, perspective)) {
260 num_startup_rtts_ = 2;
261 }
262 if (config.HasClientRequestedIndependentOption(kBBRS, perspective)) {
263 slower_startup_ = true;
264 }
265 if (config.HasClientRequestedIndependentOption(kBBR3, perspective)) {
266 drain_to_target_ = true;
267 }
268 if (config.HasClientRequestedIndependentOption(kBBS1, perspective)) {
269 rate_based_startup_ = true;
270 }
271 if (GetQuicReloadableFlag(quic_bbr_startup_rate_reduction) &&
272 config.HasClientRequestedIndependentOption(kBBS4, perspective)) {
273 rate_based_startup_ = true;
274 // Hits 1.25x pacing multiplier when ~2/3 CWND is lost.
275 startup_rate_reduction_multiplier_ = 1;
276 }
277 if (GetQuicReloadableFlag(quic_bbr_startup_rate_reduction) &&
278 config.HasClientRequestedIndependentOption(kBBS5, perspective)) {
279 rate_based_startup_ = true;
280 // Hits 1.25x pacing multiplier when ~1/3 CWND is lost.
281 startup_rate_reduction_multiplier_ = 2;
282 }
283 if (config.HasClientRequestedIndependentOption(kBBR4, perspective)) {
wub38f86522019-10-07 11:54:53 -0700284 sampler_.SetMaxAckHeightTrackerWindowLength(2 * kBandwidthWindowSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500285 }
286 if (config.HasClientRequestedIndependentOption(kBBR5, perspective)) {
wub38f86522019-10-07 11:54:53 -0700287 sampler_.SetMaxAckHeightTrackerWindowLength(4 * kBandwidthWindowSize);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500288 }
289 if (GetQuicReloadableFlag(quic_bbr_less_probe_rtt) &&
290 config.HasClientRequestedIndependentOption(kBBR6, perspective)) {
291 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_less_probe_rtt, 1, 3);
292 probe_rtt_based_on_bdp_ = true;
293 }
294 if (GetQuicReloadableFlag(quic_bbr_less_probe_rtt) &&
295 config.HasClientRequestedIndependentOption(kBBR7, perspective)) {
296 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_less_probe_rtt, 2, 3);
297 probe_rtt_skipped_if_similar_rtt_ = true;
298 }
299 if (GetQuicReloadableFlag(quic_bbr_less_probe_rtt) &&
300 config.HasClientRequestedIndependentOption(kBBR8, perspective)) {
301 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_less_probe_rtt, 3, 3);
302 probe_rtt_disabled_if_app_limited_ = true;
303 }
304 if (GetQuicReloadableFlag(quic_bbr_flexible_app_limited) &&
305 config.HasClientRequestedIndependentOption(kBBR9, perspective)) {
306 QUIC_RELOADABLE_FLAG_COUNT(quic_bbr_flexible_app_limited);
307 flexible_app_limited_ = true;
308 }
ianswettcfef5c92019-06-18 07:58:39 -0700309 if (config.HasClientRequestedIndependentOption(kBBQ1, perspective)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500310 set_high_gain(kDerivedHighGain);
311 set_high_cwnd_gain(kDerivedHighGain);
312 set_drain_gain(1.f / kDerivedHighGain);
313 }
ianswettcfef5c92019-06-18 07:58:39 -0700314 if (config.HasClientRequestedIndependentOption(kBBQ2, perspective)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500315 set_high_cwnd_gain(kDerivedHighCWNDGain);
316 }
ianswettcfef5c92019-06-18 07:58:39 -0700317 if (config.HasClientRequestedIndependentOption(kBBQ3, perspective)) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500318 enable_ack_aggregation_during_startup_ = true;
319 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500320 if (GetQuicReloadableFlag(quic_bbr_slower_startup4) &&
321 config.HasClientRequestedIndependentOption(kBBQ5, perspective)) {
322 QUIC_RELOADABLE_FLAG_COUNT(quic_bbr_slower_startup4);
323 expire_ack_aggregation_in_startup_ = true;
324 }
325 if (config.HasClientRequestedIndependentOption(kMIN1, perspective)) {
326 min_congestion_window_ = kMaxSegmentSize;
327 }
328}
329
QUICHE teamfdcfe3b2019-11-06 10:54:25 -0800330void BbrSender::AdjustNetworkParameters(const NetworkParams& params) {
QUICHE teamb4e187c2019-11-14 06:22:50 -0800331 const QuicBandwidth& bandwidth = params.bandwidth;
332 const QuicTime::Delta& rtt = params.rtt;
QUICHE teamfdcfe3b2019-11-06 10:54:25 -0800333
fayangbbe9a1b2019-11-07 10:44:08 -0800334 if (GetQuicReloadableFlag(quic_bbr_donot_inject_bandwidth)) {
335 QUIC_RELOADABLE_FLAG_COUNT(quic_bbr_donot_inject_bandwidth);
336 } else if (!bandwidth.IsZero()) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500337 max_bandwidth_.Update(bandwidth, round_trip_count_);
338 }
339 if (!rtt.IsZero() && (min_rtt_ > rtt || min_rtt_.IsZero())) {
340 min_rtt_ = rtt;
341 }
QUICHE teamb4e187c2019-11-14 06:22:50 -0800342
343 if (params.quic_fix_bbr_cwnd_in_bandwidth_resumption && mode_ == STARTUP) {
fayangc050d7a2019-05-17 11:20:38 -0700344 if (bandwidth.IsZero()) {
345 // Ignore bad bandwidth samples.
fayangc050d7a2019-05-17 11:20:38 -0700346 return;
347 }
fayangbbe9a1b2019-11-07 10:44:08 -0800348 const QuicByteCount new_cwnd = std::max(
349 kMinInitialCongestionWindow * kDefaultTCPMSS,
350 std::min(
351 kMaxInitialCongestionWindow * kDefaultTCPMSS,
352 bandwidth * (GetQuicReloadableFlag(quic_bbr_donot_inject_bandwidth)
353 ? GetMinRtt()
354 : rtt_stats_->SmoothedOrInitialRtt())));
fayang14650e42019-06-04 10:30:33 -0700355 if (!rtt_stats_->smoothed_rtt().IsZero()) {
356 QUIC_CODE_COUNT(quic_smoothed_rtt_available);
357 } else if (rtt_stats_->initial_rtt() !=
358 QuicTime::Delta::FromMilliseconds(kInitialRttMs)) {
359 QUIC_CODE_COUNT(quic_client_initial_rtt_available);
360 } else {
361 QUIC_CODE_COUNT(quic_default_initial_rtt);
362 }
QUICHE teamb4e187c2019-11-14 06:22:50 -0800363 if (new_cwnd < congestion_window_ && !params.allow_cwnd_to_decrease) {
fayangc050d7a2019-05-17 11:20:38 -0700364 // Only decrease cwnd if allow_cwnd_to_decrease is true.
fayangf1b99dc2019-05-14 06:29:18 -0700365 return;
366 }
fayang8cafde02019-06-04 06:21:04 -0700367 if (GetQuicReloadableFlag(quic_conservative_cwnd_and_pacing_gains)) {
368 // Decreases cwnd gain and pacing gain. Please note, if pacing_rate_ has
369 // been calculated, it cannot decrease in STARTUP phase.
370 QUIC_RELOADABLE_FLAG_COUNT(quic_conservative_cwnd_and_pacing_gains);
371 set_high_gain(kDerivedHighCWNDGain);
372 set_high_cwnd_gain(kDerivedHighCWNDGain);
373 }
fayangf1b99dc2019-05-14 06:29:18 -0700374 congestion_window_ = new_cwnd;
QUICHE teamb4e187c2019-11-14 06:22:50 -0800375 if (params.quic_bbr_fix_pacing_rate) {
fayangf2c4e3e2019-10-30 07:46:51 -0700376 // Pace at the rate of new_cwnd / RTT.
377 QuicBandwidth new_pacing_rate =
378 QuicBandwidth::FromBytesAndTimeDelta(congestion_window_, GetMinRtt());
379 pacing_rate_ = std::max(pacing_rate_, new_pacing_rate);
380 }
fayangbe83ecd2019-04-26 13:58:09 -0700381 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500382}
383
384void BbrSender::OnCongestionEvent(bool /*rtt_updated*/,
385 QuicByteCount prior_in_flight,
386 QuicTime event_time,
387 const AckedPacketVector& acked_packets,
388 const LostPacketVector& lost_packets) {
389 const QuicByteCount total_bytes_acked_before = sampler_.total_bytes_acked();
390
391 bool is_round_start = false;
392 bool min_rtt_expired = false;
393
394 DiscardLostPackets(lost_packets);
395
396 // Input the new data into the BBR model of the connection.
397 QuicByteCount excess_acked = 0;
398 if (!acked_packets.empty()) {
399 QuicPacketNumber last_acked_packet = acked_packets.rbegin()->packet_number;
400 is_round_start = UpdateRoundTripCounter(last_acked_packet);
401 min_rtt_expired = UpdateBandwidthAndMinRtt(event_time, acked_packets);
402 UpdateRecoveryState(last_acked_packet, !lost_packets.empty(),
403 is_round_start);
404
wub38f86522019-10-07 11:54:53 -0700405 excess_acked =
406 sampler_.OnAckEventEnd(max_bandwidth_.GetBest(), round_trip_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500407 }
408
409 // Handle logic specific to PROBE_BW mode.
410 if (mode_ == PROBE_BW) {
411 UpdateGainCyclePhase(event_time, prior_in_flight, !lost_packets.empty());
412 }
413
414 // Handle logic specific to STARTUP and DRAIN modes.
415 if (is_round_start && !is_at_full_bandwidth_) {
416 CheckIfFullBandwidthReached();
417 }
418 MaybeExitStartupOrDrain(event_time);
419
420 // Handle logic specific to PROBE_RTT.
421 MaybeEnterOrExitProbeRtt(event_time, is_round_start, min_rtt_expired);
422
423 // Calculate number of packets acked and lost.
424 QuicByteCount bytes_acked =
425 sampler_.total_bytes_acked() - total_bytes_acked_before;
426 QuicByteCount bytes_lost = 0;
427 for (const auto& packet : lost_packets) {
428 bytes_lost += packet.bytes_lost;
429 }
430
431 // After the model is updated, recalculate the pacing rate and congestion
432 // window.
433 CalculatePacingRate();
434 CalculateCongestionWindow(bytes_acked, excess_acked);
435 CalculateRecoveryWindow(bytes_acked, bytes_lost);
436
437 // Cleanup internal state.
438 sampler_.RemoveObsoletePackets(unacked_packets_->GetLeastUnacked());
439}
440
441CongestionControlType BbrSender::GetCongestionControlType() const {
442 return kBBR;
443}
444
445QuicTime::Delta BbrSender::GetMinRtt() const {
446 return !min_rtt_.IsZero() ? min_rtt_ : rtt_stats_->initial_rtt();
447}
448
449QuicByteCount BbrSender::GetTargetCongestionWindow(float gain) const {
450 QuicByteCount bdp = GetMinRtt() * BandwidthEstimate();
451 QuicByteCount congestion_window = gain * bdp;
452
453 // BDP estimate will be zero if no bandwidth samples are available yet.
454 if (congestion_window == 0) {
455 congestion_window = gain * initial_congestion_window_;
456 }
457
458 return std::max(congestion_window, min_congestion_window_);
459}
460
461QuicByteCount BbrSender::ProbeRttCongestionWindow() const {
462 if (probe_rtt_based_on_bdp_) {
463 return GetTargetCongestionWindow(kModerateProbeRttMultiplier);
464 }
465 return min_congestion_window_;
466}
467
wub967ba572019-04-01 09:27:52 -0700468void BbrSender::EnterStartupMode(QuicTime now) {
469 if (stats_) {
470 ++stats_->slowstart_count;
wubbe29b9e2019-11-24 06:56:04 -0800471 stats_->slowstart_duration.Start(now);
wub967ba572019-04-01 09:27:52 -0700472 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500473 mode_ = STARTUP;
474 pacing_gain_ = high_gain_;
475 congestion_window_gain_ = high_cwnd_gain_;
476}
477
478void BbrSender::EnterProbeBandwidthMode(QuicTime now) {
479 mode_ = PROBE_BW;
480 congestion_window_gain_ = congestion_window_gain_constant_;
481
482 // Pick a random offset for the gain cycle out of {0, 2..7} range. 1 is
483 // excluded because in that case increased gain and decreased gain would not
484 // follow each other.
485 cycle_current_offset_ = random_->RandUint64() % (kGainCycleLength - 1);
486 if (cycle_current_offset_ >= 1) {
487 cycle_current_offset_ += 1;
488 }
489
490 last_cycle_start_ = now;
491 pacing_gain_ = kPacingGain[cycle_current_offset_];
492}
493
494void BbrSender::DiscardLostPackets(const LostPacketVector& lost_packets) {
495 for (const LostPacket& packet : lost_packets) {
496 sampler_.OnPacketLost(packet.packet_number);
wub967ba572019-04-01 09:27:52 -0700497 if (mode_ == STARTUP) {
498 if (stats_) {
499 ++stats_->slowstart_packets_lost;
500 stats_->slowstart_bytes_lost += packet.bytes_lost;
501 }
502 if (startup_rate_reduction_multiplier_ != 0) {
503 startup_bytes_lost_ += packet.bytes_lost;
504 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500505 }
506 }
507}
508
509bool BbrSender::UpdateRoundTripCounter(QuicPacketNumber last_acked_packet) {
510 if (!current_round_trip_end_.IsInitialized() ||
511 last_acked_packet > current_round_trip_end_) {
512 round_trip_count_++;
513 current_round_trip_end_ = last_sent_packet_;
wub967ba572019-04-01 09:27:52 -0700514 if (stats_ && InSlowStart()) {
515 ++stats_->slowstart_num_rtts;
516 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500517 return true;
518 }
519
520 return false;
521}
522
523bool BbrSender::UpdateBandwidthAndMinRtt(
524 QuicTime now,
525 const AckedPacketVector& acked_packets) {
526 QuicTime::Delta sample_min_rtt = QuicTime::Delta::Infinite();
527 for (const auto& packet : acked_packets) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500528 BandwidthSample bandwidth_sample =
529 sampler_.OnPacketAcknowledged(now, packet.packet_number);
wub03637f52019-05-30 10:52:20 -0700530 if (!bandwidth_sample.state_at_send.is_valid) {
wubfb4e2132019-04-05 12:30:09 -0700531 // From the sampler's perspective, the packet has never been sent, or the
532 // packet has been acked or marked as lost previously.
533 continue;
534 }
535
wub254545c2019-04-04 13:56:52 -0700536 last_sample_is_app_limited_ = bandwidth_sample.state_at_send.is_app_limited;
537 has_non_app_limited_sample_ |=
538 !bandwidth_sample.state_at_send.is_app_limited;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500539 if (!bandwidth_sample.rtt.IsZero()) {
540 sample_min_rtt = std::min(sample_min_rtt, bandwidth_sample.rtt);
541 }
542
wub254545c2019-04-04 13:56:52 -0700543 if (!bandwidth_sample.state_at_send.is_app_limited ||
QUICHE teama6ef0a62019-03-07 20:34:33 -0500544 bandwidth_sample.bandwidth > BandwidthEstimate()) {
545 max_bandwidth_.Update(bandwidth_sample.bandwidth, round_trip_count_);
546 }
547 }
548
549 // If none of the RTT samples are valid, return immediately.
550 if (sample_min_rtt.IsInfinite()) {
551 return false;
552 }
553 min_rtt_since_last_probe_rtt_ =
554 std::min(min_rtt_since_last_probe_rtt_, sample_min_rtt);
555
556 // Do not expire min_rtt if none was ever available.
557 bool min_rtt_expired =
558 !min_rtt_.IsZero() && (now > (min_rtt_timestamp_ + kMinRttExpiry));
559
560 if (min_rtt_expired || sample_min_rtt < min_rtt_ || min_rtt_.IsZero()) {
561 QUIC_DVLOG(2) << "Min RTT updated, old value: " << min_rtt_
562 << ", new value: " << sample_min_rtt
563 << ", current time: " << now.ToDebuggingValue();
564
565 if (min_rtt_expired && ShouldExtendMinRttExpiry()) {
566 min_rtt_expired = false;
567 } else {
568 min_rtt_ = sample_min_rtt;
569 }
570 min_rtt_timestamp_ = now;
571 // Reset since_last_probe_rtt fields.
572 min_rtt_since_last_probe_rtt_ = QuicTime::Delta::Infinite();
573 app_limited_since_last_probe_rtt_ = false;
574 }
575 DCHECK(!min_rtt_.IsZero());
576
577 return min_rtt_expired;
578}
579
580bool BbrSender::ShouldExtendMinRttExpiry() const {
581 if (probe_rtt_disabled_if_app_limited_ && app_limited_since_last_probe_rtt_) {
582 // Extend the current min_rtt if we've been app limited recently.
583 return true;
584 }
585 const bool min_rtt_increased_since_last_probe =
586 min_rtt_since_last_probe_rtt_ > min_rtt_ * kSimilarMinRttThreshold;
587 if (probe_rtt_skipped_if_similar_rtt_ && app_limited_since_last_probe_rtt_ &&
588 !min_rtt_increased_since_last_probe) {
589 // Extend the current min_rtt if we've been app limited recently and an rtt
590 // has been measured in that time that's less than 12.5% more than the
591 // current min_rtt.
592 return true;
593 }
594 return false;
595}
596
597void BbrSender::UpdateGainCyclePhase(QuicTime now,
598 QuicByteCount prior_in_flight,
599 bool has_losses) {
600 const QuicByteCount bytes_in_flight = unacked_packets_->bytes_in_flight();
601 // In most cases, the cycle is advanced after an RTT passes.
602 bool should_advance_gain_cycling = now - last_cycle_start_ > GetMinRtt();
603
604 // If the pacing gain is above 1.0, the connection is trying to probe the
605 // bandwidth by increasing the number of bytes in flight to at least
606 // pacing_gain * BDP. Make sure that it actually reaches the target, as long
607 // as there are no losses suggesting that the buffers are not able to hold
608 // that much.
609 if (pacing_gain_ > 1.0 && !has_losses &&
610 prior_in_flight < GetTargetCongestionWindow(pacing_gain_)) {
611 should_advance_gain_cycling = false;
612 }
613
614 // If pacing gain is below 1.0, the connection is trying to drain the extra
615 // queue which could have been incurred by probing prior to it. If the number
616 // of bytes in flight falls down to the estimated BDP value earlier, conclude
617 // that the queue has been successfully drained and exit this cycle early.
618 if (pacing_gain_ < 1.0 && bytes_in_flight <= GetTargetCongestionWindow(1)) {
619 should_advance_gain_cycling = true;
620 }
621
622 if (should_advance_gain_cycling) {
623 cycle_current_offset_ = (cycle_current_offset_ + 1) % kGainCycleLength;
624 last_cycle_start_ = now;
625 // Stay in low gain mode until the target BDP is hit.
626 // Low gain mode will be exited immediately when the target BDP is achieved.
627 if (drain_to_target_ && pacing_gain_ < 1 &&
628 kPacingGain[cycle_current_offset_] == 1 &&
629 bytes_in_flight > GetTargetCongestionWindow(1)) {
630 return;
631 }
632 pacing_gain_ = kPacingGain[cycle_current_offset_];
633 }
634}
635
636void BbrSender::CheckIfFullBandwidthReached() {
637 if (last_sample_is_app_limited_) {
638 return;
639 }
640
641 QuicBandwidth target = bandwidth_at_last_round_ * kStartupGrowthTarget;
642 if (BandwidthEstimate() >= target) {
643 bandwidth_at_last_round_ = BandwidthEstimate();
644 rounds_without_bandwidth_gain_ = 0;
645 if (expire_ack_aggregation_in_startup_) {
646 // Expire old excess delivery measurements now that bandwidth increased.
wub38f86522019-10-07 11:54:53 -0700647 sampler_.ResetMaxAckHeightTracker(0, round_trip_count_);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500648 }
649 return;
650 }
651
652 rounds_without_bandwidth_gain_++;
653 if ((rounds_without_bandwidth_gain_ >= num_startup_rtts_) ||
654 (exit_startup_on_loss_ && InRecovery())) {
655 DCHECK(has_non_app_limited_sample_);
656 is_at_full_bandwidth_ = true;
657 }
658}
659
660void BbrSender::MaybeExitStartupOrDrain(QuicTime now) {
661 if (mode_ == STARTUP && is_at_full_bandwidth_) {
wub967ba572019-04-01 09:27:52 -0700662 OnExitStartup(now);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500663 mode_ = DRAIN;
664 pacing_gain_ = drain_gain_;
665 congestion_window_gain_ = high_cwnd_gain_;
666 }
667 if (mode_ == DRAIN &&
668 unacked_packets_->bytes_in_flight() <= GetTargetCongestionWindow(1)) {
669 EnterProbeBandwidthMode(now);
670 }
671}
672
wub967ba572019-04-01 09:27:52 -0700673void BbrSender::OnExitStartup(QuicTime now) {
674 DCHECK_EQ(mode_, STARTUP);
675 if (stats_) {
wubbe29b9e2019-11-24 06:56:04 -0800676 stats_->slowstart_duration.Stop(now);
wub967ba572019-04-01 09:27:52 -0700677 }
678}
679
QUICHE teama6ef0a62019-03-07 20:34:33 -0500680void BbrSender::MaybeEnterOrExitProbeRtt(QuicTime now,
681 bool is_round_start,
682 bool min_rtt_expired) {
683 if (min_rtt_expired && !exiting_quiescence_ && mode_ != PROBE_RTT) {
wub967ba572019-04-01 09:27:52 -0700684 if (InSlowStart()) {
685 OnExitStartup(now);
686 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500687 mode_ = PROBE_RTT;
688 pacing_gain_ = 1;
689 // Do not decide on the time to exit PROBE_RTT until the |bytes_in_flight|
690 // is at the target small value.
691 exit_probe_rtt_at_ = QuicTime::Zero();
692 }
693
694 if (mode_ == PROBE_RTT) {
695 sampler_.OnAppLimited();
696
697 if (exit_probe_rtt_at_ == QuicTime::Zero()) {
698 // If the window has reached the appropriate size, schedule exiting
699 // PROBE_RTT. The CWND during PROBE_RTT is kMinimumCongestionWindow, but
700 // we allow an extra packet since QUIC checks CWND before sending a
701 // packet.
702 if (unacked_packets_->bytes_in_flight() <
dschinazi66dea072019-04-09 11:41:06 -0700703 ProbeRttCongestionWindow() + kMaxOutgoingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500704 exit_probe_rtt_at_ = now + kProbeRttTime;
705 probe_rtt_round_passed_ = false;
706 }
707 } else {
708 if (is_round_start) {
709 probe_rtt_round_passed_ = true;
710 }
711 if (now >= exit_probe_rtt_at_ && probe_rtt_round_passed_) {
712 min_rtt_timestamp_ = now;
713 if (!is_at_full_bandwidth_) {
wub967ba572019-04-01 09:27:52 -0700714 EnterStartupMode(now);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500715 } else {
716 EnterProbeBandwidthMode(now);
717 }
718 }
719 }
720 }
721
722 exiting_quiescence_ = false;
723}
724
725void BbrSender::UpdateRecoveryState(QuicPacketNumber last_acked_packet,
726 bool has_losses,
727 bool is_round_start) {
728 // Exit recovery when there are no losses for a round.
729 if (has_losses) {
730 end_recovery_at_ = last_sent_packet_;
731 }
732
733 switch (recovery_state_) {
734 case NOT_IN_RECOVERY:
735 // Enter conservation on the first loss.
736 if (has_losses) {
737 recovery_state_ = CONSERVATION;
738 // This will cause the |recovery_window_| to be set to the correct
739 // value in CalculateRecoveryWindow().
740 recovery_window_ = 0;
741 // Since the conservation phase is meant to be lasting for a whole
742 // round, extend the current round as if it were started right now.
743 current_round_trip_end_ = last_sent_packet_;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500744 }
745 break;
746
747 case CONSERVATION:
748 if (is_round_start) {
749 recovery_state_ = GROWTH;
750 }
751 QUIC_FALLTHROUGH_INTENDED;
752
753 case GROWTH:
754 // Exit recovery if appropriate.
755 if (!has_losses && last_acked_packet > end_recovery_at_) {
756 recovery_state_ = NOT_IN_RECOVERY;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500757 }
758
759 break;
760 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500761}
762
QUICHE teama6ef0a62019-03-07 20:34:33 -0500763void BbrSender::CalculatePacingRate() {
764 if (BandwidthEstimate().IsZero()) {
765 return;
766 }
767
768 QuicBandwidth target_rate = pacing_gain_ * BandwidthEstimate();
769 if (is_at_full_bandwidth_) {
770 pacing_rate_ = target_rate;
771 return;
772 }
773
774 // Pace at the rate of initial_window / RTT as soon as RTT measurements are
775 // available.
776 if (pacing_rate_.IsZero() && !rtt_stats_->min_rtt().IsZero()) {
777 pacing_rate_ = QuicBandwidth::FromBytesAndTimeDelta(
778 initial_congestion_window_, rtt_stats_->min_rtt());
779 return;
780 }
781 // Slow the pacing rate in STARTUP once loss has ever been detected.
782 const bool has_ever_detected_loss = end_recovery_at_.IsInitialized();
783 if (slower_startup_ && has_ever_detected_loss &&
784 has_non_app_limited_sample_) {
785 pacing_rate_ = kStartupAfterLossGain * BandwidthEstimate();
786 return;
787 }
788
789 // Slow the pacing rate in STARTUP by the bytes_lost / CWND.
790 if (startup_rate_reduction_multiplier_ != 0 && has_ever_detected_loss &&
791 has_non_app_limited_sample_) {
792 pacing_rate_ =
793 (1 - (startup_bytes_lost_ * startup_rate_reduction_multiplier_ * 1.0f /
794 congestion_window_)) *
795 target_rate;
796 // Ensure the pacing rate doesn't drop below the startup growth target times
797 // the bandwidth estimate.
798 pacing_rate_ =
799 std::max(pacing_rate_, kStartupGrowthTarget * BandwidthEstimate());
800 return;
801 }
802
803 // Do not decrease the pacing rate during startup.
804 pacing_rate_ = std::max(pacing_rate_, target_rate);
805}
806
807void BbrSender::CalculateCongestionWindow(QuicByteCount bytes_acked,
808 QuicByteCount excess_acked) {
809 if (mode_ == PROBE_RTT) {
810 return;
811 }
812
813 QuicByteCount target_window =
814 GetTargetCongestionWindow(congestion_window_gain_);
815 if (is_at_full_bandwidth_) {
816 // Add the max recently measured ack aggregation to CWND.
wub38f86522019-10-07 11:54:53 -0700817 target_window += sampler_.max_ack_height();
QUICHE teama6ef0a62019-03-07 20:34:33 -0500818 } else if (enable_ack_aggregation_during_startup_) {
819 // Add the most recent excess acked. Because CWND never decreases in
820 // STARTUP, this will automatically create a very localized max filter.
821 target_window += excess_acked;
822 }
823
824 // Instead of immediately setting the target CWND as the new one, BBR grows
825 // the CWND towards |target_window| by only increasing it |bytes_acked| at a
826 // time.
827 const bool add_bytes_acked =
828 !GetQuicReloadableFlag(quic_bbr_no_bytes_acked_in_startup_recovery) ||
829 !InRecovery();
830 if (is_at_full_bandwidth_) {
831 congestion_window_ =
832 std::min(target_window, congestion_window_ + bytes_acked);
833 } else if (add_bytes_acked &&
834 (congestion_window_ < target_window ||
835 sampler_.total_bytes_acked() < initial_congestion_window_)) {
836 // If the connection is not yet out of startup phase, do not decrease the
837 // window.
838 congestion_window_ = congestion_window_ + bytes_acked;
839 }
840
841 // Enforce the limits on the congestion window.
842 congestion_window_ = std::max(congestion_window_, min_congestion_window_);
843 congestion_window_ = std::min(congestion_window_, max_congestion_window_);
844}
845
846void BbrSender::CalculateRecoveryWindow(QuicByteCount bytes_acked,
847 QuicByteCount bytes_lost) {
848 if (rate_based_startup_ && mode_ == STARTUP) {
849 return;
850 }
851
852 if (recovery_state_ == NOT_IN_RECOVERY) {
853 return;
854 }
855
856 // Set up the initial recovery window.
857 if (recovery_window_ == 0) {
858 recovery_window_ = unacked_packets_->bytes_in_flight() + bytes_acked;
859 recovery_window_ = std::max(min_congestion_window_, recovery_window_);
860 return;
861 }
862
863 // Remove losses from the recovery window, while accounting for a potential
864 // integer underflow.
865 recovery_window_ = recovery_window_ >= bytes_lost
866 ? recovery_window_ - bytes_lost
867 : kMaxSegmentSize;
868
869 // In CONSERVATION mode, just subtracting losses is sufficient. In GROWTH,
870 // release additional |bytes_acked| to achieve a slow-start-like behavior.
871 if (recovery_state_ == GROWTH) {
872 recovery_window_ += bytes_acked;
873 }
874
875 // Sanity checks. Ensure that we always allow to send at least an MSS or
876 // |bytes_acked| in response, whichever is larger.
877 recovery_window_ = std::max(
878 recovery_window_, unacked_packets_->bytes_in_flight() + bytes_acked);
879 if (GetQuicReloadableFlag(quic_bbr_one_mss_conservation)) {
ianswettec9bf882019-11-11 08:21:00 -0800880 QUIC_RELOADABLE_FLAG_COUNT(quic_bbr_one_mss_conservation);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500881 recovery_window_ =
882 std::max(recovery_window_,
883 unacked_packets_->bytes_in_flight() + kMaxSegmentSize);
884 }
885 recovery_window_ = std::max(min_congestion_window_, recovery_window_);
886}
887
vasilvvc48c8712019-03-11 13:38:16 -0700888std::string BbrSender::GetDebugState() const {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500889 std::ostringstream stream;
890 stream << ExportDebugState();
891 return stream.str();
892}
893
894void BbrSender::OnApplicationLimited(QuicByteCount bytes_in_flight) {
895 if (bytes_in_flight >= GetCongestionWindow()) {
896 return;
897 }
898 if (flexible_app_limited_ && IsPipeSufficientlyFull()) {
899 return;
900 }
901
902 app_limited_since_last_probe_rtt_ = true;
903 sampler_.OnAppLimited();
904 QUIC_DVLOG(2) << "Becoming application limited. Last sent packet: "
905 << last_sent_packet_ << ", CWND: " << GetCongestionWindow();
906}
907
wub5cd49592019-11-25 15:17:13 -0800908void BbrSender::PopulateConnectionStats(QuicConnectionStats* stats) const {
909 stats->num_ack_aggregation_epochs = sampler_.num_ack_aggregation_epochs();
910}
911
QUICHE teama6ef0a62019-03-07 20:34:33 -0500912BbrSender::DebugState BbrSender::ExportDebugState() const {
913 return DebugState(*this);
914}
915
vasilvvc48c8712019-03-11 13:38:16 -0700916static std::string ModeToString(BbrSender::Mode mode) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500917 switch (mode) {
918 case BbrSender::STARTUP:
919 return "STARTUP";
920 case BbrSender::DRAIN:
921 return "DRAIN";
922 case BbrSender::PROBE_BW:
923 return "PROBE_BW";
924 case BbrSender::PROBE_RTT:
925 return "PROBE_RTT";
926 }
927 return "???";
928}
929
930std::ostream& operator<<(std::ostream& os, const BbrSender::Mode& mode) {
931 os << ModeToString(mode);
932 return os;
933}
934
935std::ostream& operator<<(std::ostream& os, const BbrSender::DebugState& state) {
936 os << "Mode: " << ModeToString(state.mode) << std::endl;
937 os << "Maximum bandwidth: " << state.max_bandwidth << std::endl;
938 os << "Round trip counter: " << state.round_trip_count << std::endl;
939 os << "Gain cycle index: " << static_cast<int>(state.gain_cycle_index)
940 << std::endl;
941 os << "Congestion window: " << state.congestion_window << " bytes"
942 << std::endl;
943
944 if (state.mode == BbrSender::STARTUP) {
945 os << "(startup) Bandwidth at last round: " << state.bandwidth_at_last_round
946 << std::endl;
947 os << "(startup) Rounds without gain: "
948 << state.rounds_without_bandwidth_gain << std::endl;
949 }
950
951 os << "Minimum RTT: " << state.min_rtt << std::endl;
952 os << "Minimum RTT timestamp: " << state.min_rtt_timestamp.ToDebuggingValue()
953 << std::endl;
954
955 os << "Last sample is app-limited: "
956 << (state.last_sample_is_app_limited ? "yes" : "no");
957
958 return os;
959}
960
961} // namespace quic