blob: 1c0d274fe1d855b5cdae727a9f9f9f2bb0659e02 [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"
QUICHE teama6ef0a62019-03-07 20:34:33 -050014#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
15#include "net/third_party/quiche/src/quic/platform/api/quic_fallthrough.h"
16#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
17#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
18#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050019
20namespace quic {
21
22namespace {
23// Constants based on TCP defaults.
24// The minimum CWND to ensure delayed acks don't reduce bandwidth measurements.
25// Does not inflate the pacing rate.
26const QuicByteCount kDefaultMinimumCongestionWindow = 4 * kMaxSegmentSize;
27
28// The gain used for the STARTUP, equal to 2/ln(2).
29const float kDefaultHighGain = 2.885f;
30// The newly derived gain for STARTUP, equal to 4 * ln(2)
31const float kDerivedHighGain = 2.773f;
32// The newly derived CWND gain for STARTUP, 2.
33const float kDerivedHighCWNDGain = 2.773f;
34// The gain used in STARTUP after loss has been detected.
35// 1.5 is enough to allow for 25% exogenous loss and still observe a 25% growth
36// in measured bandwidth.
37const float kStartupAfterLossGain = 1.5f;
38// The cycle of gains used during the PROBE_BW stage.
39const float kPacingGain[] = {1.25, 0.75, 1, 1, 1, 1, 1, 1};
40
41// The length of the gain cycle.
42const size_t kGainCycleLength = sizeof(kPacingGain) / sizeof(kPacingGain[0]);
43// The size of the bandwidth filter window, in round-trips.
44const QuicRoundTripCount kBandwidthWindowSize = kGainCycleLength + 2;
45
46// The time after which the current min_rtt value expires.
47const QuicTime::Delta kMinRttExpiry = QuicTime::Delta::FromSeconds(10);
48// The minimum time the connection can spend in PROBE_RTT mode.
49const QuicTime::Delta kProbeRttTime = QuicTime::Delta::FromMilliseconds(200);
50// If the bandwidth does not increase by the factor of |kStartupGrowthTarget|
51// within |kRoundTripsWithoutGrowthBeforeExitingStartup| rounds, the connection
52// will exit the STARTUP mode.
53const float kStartupGrowthTarget = 1.25;
54const QuicRoundTripCount kRoundTripsWithoutGrowthBeforeExitingStartup = 3;
55// Coefficient of target congestion window to use when basing PROBE_RTT on BDP.
56const float kModerateProbeRttMultiplier = 0.75;
57// Coefficient to determine if a new RTT is sufficiently similar to min_rtt that
58// we don't need to enter PROBE_RTT.
59const float kSimilarMinRttThreshold = 1.125;
60
61} // namespace
62
63BbrSender::DebugState::DebugState(const BbrSender& sender)
64 : mode(sender.mode_),
65 max_bandwidth(sender.max_bandwidth_.GetBest()),
66 round_trip_count(sender.round_trip_count_),
67 gain_cycle_index(sender.cycle_current_offset_),
68 congestion_window(sender.congestion_window_),
69 is_at_full_bandwidth(sender.is_at_full_bandwidth_),
70 bandwidth_at_last_round(sender.bandwidth_at_last_round_),
71 rounds_without_bandwidth_gain(sender.rounds_without_bandwidth_gain_),
72 min_rtt(sender.min_rtt_),
73 min_rtt_timestamp(sender.min_rtt_timestamp_),
74 recovery_state(sender.recovery_state_),
75 recovery_window(sender.recovery_window_),
76 last_sample_is_app_limited(sender.last_sample_is_app_limited_),
77 end_of_app_limited_phase(sender.sampler_.end_of_app_limited_phase()) {}
78
79BbrSender::DebugState::DebugState(const DebugState& state) = default;
80
wub967ba572019-04-01 09:27:52 -070081BbrSender::BbrSender(QuicTime now,
82 const RttStats* rtt_stats,
QUICHE teama6ef0a62019-03-07 20:34:33 -050083 const QuicUnackedPacketMap* unacked_packets,
84 QuicPacketCount initial_tcp_congestion_window,
85 QuicPacketCount max_tcp_congestion_window,
wub967ba572019-04-01 09:27:52 -070086 QuicRandom* random,
87 QuicConnectionStats* stats)
QUICHE teama6ef0a62019-03-07 20:34:33 -050088 : rtt_stats_(rtt_stats),
89 unacked_packets_(unacked_packets),
90 random_(random),
wub967ba572019-04-01 09:27:52 -070091 stats_(stats),
QUICHE teama6ef0a62019-03-07 20:34:33 -050092 mode_(STARTUP),
93 round_trip_count_(0),
94 max_bandwidth_(kBandwidthWindowSize, QuicBandwidth::Zero(), 0),
95 max_ack_height_(kBandwidthWindowSize, 0, 0),
96 aggregation_epoch_start_time_(QuicTime::Zero()),
97 aggregation_epoch_bytes_(0),
98 min_rtt_(QuicTime::Delta::Zero()),
99 min_rtt_timestamp_(QuicTime::Zero()),
100 congestion_window_(initial_tcp_congestion_window * kDefaultTCPMSS),
101 initial_congestion_window_(initial_tcp_congestion_window *
102 kDefaultTCPMSS),
103 max_congestion_window_(max_tcp_congestion_window * kDefaultTCPMSS),
104 min_congestion_window_(kDefaultMinimumCongestionWindow),
105 high_gain_(kDefaultHighGain),
106 high_cwnd_gain_(kDefaultHighGain),
107 drain_gain_(1.f / kDefaultHighGain),
108 pacing_rate_(QuicBandwidth::Zero()),
109 pacing_gain_(1),
110 congestion_window_gain_(1),
111 congestion_window_gain_constant_(
112 static_cast<float>(FLAGS_quic_bbr_cwnd_gain)),
113 num_startup_rtts_(kRoundTripsWithoutGrowthBeforeExitingStartup),
114 exit_startup_on_loss_(false),
115 cycle_current_offset_(0),
116 last_cycle_start_(QuicTime::Zero()),
117 is_at_full_bandwidth_(false),
118 rounds_without_bandwidth_gain_(0),
119 bandwidth_at_last_round_(QuicBandwidth::Zero()),
120 exiting_quiescence_(false),
121 exit_probe_rtt_at_(QuicTime::Zero()),
122 probe_rtt_round_passed_(false),
123 last_sample_is_app_limited_(false),
124 has_non_app_limited_sample_(false),
125 flexible_app_limited_(false),
126 recovery_state_(NOT_IN_RECOVERY),
127 recovery_window_(max_congestion_window_),
128 is_app_limited_recovery_(false),
129 slower_startup_(false),
130 rate_based_startup_(false),
131 startup_rate_reduction_multiplier_(0),
132 startup_bytes_lost_(0),
133 enable_ack_aggregation_during_startup_(false),
134 expire_ack_aggregation_in_startup_(false),
135 drain_to_target_(false),
136 probe_rtt_based_on_bdp_(false),
137 probe_rtt_skipped_if_similar_rtt_(false),
138 probe_rtt_disabled_if_app_limited_(false),
139 app_limited_since_last_probe_rtt_(false),
wubfb4e2132019-04-05 12:30:09 -0700140 min_rtt_since_last_probe_rtt_(QuicTime::Delta::Infinite()),
141 always_get_bw_sample_when_acked_(
142 GetQuicReloadableFlag(quic_always_get_bw_sample_when_acked)) {
wub967ba572019-04-01 09:27:52 -0700143 if (stats_) {
144 stats_->slowstart_count = 0;
145 stats_->slowstart_start_time = QuicTime::Zero();
146 }
147 EnterStartupMode(now);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500148}
149
150BbrSender::~BbrSender() {}
151
152void BbrSender::SetInitialCongestionWindowInPackets(
153 QuicPacketCount congestion_window) {
154 if (mode_ == STARTUP) {
155 initial_congestion_window_ = congestion_window * kDefaultTCPMSS;
156 congestion_window_ = congestion_window * kDefaultTCPMSS;
157 }
158}
159
160bool BbrSender::InSlowStart() const {
161 return mode_ == STARTUP;
162}
163
164void BbrSender::OnPacketSent(QuicTime sent_time,
165 QuicByteCount bytes_in_flight,
166 QuicPacketNumber packet_number,
167 QuicByteCount bytes,
168 HasRetransmittableData is_retransmittable) {
wub967ba572019-04-01 09:27:52 -0700169 if (stats_ && InSlowStart()) {
170 ++stats_->slowstart_packets_sent;
171 stats_->slowstart_bytes_sent += bytes;
172 }
173
QUICHE teama6ef0a62019-03-07 20:34:33 -0500174 last_sent_packet_ = packet_number;
175
176 if (bytes_in_flight == 0 && sampler_.is_app_limited()) {
177 exiting_quiescence_ = true;
178 }
179
180 if (!aggregation_epoch_start_time_.IsInitialized()) {
181 aggregation_epoch_start_time_ = sent_time;
182 }
183
184 sampler_.OnPacketSent(sent_time, packet_number, bytes, bytes_in_flight,
185 is_retransmittable);
186}
187
188bool BbrSender::CanSend(QuicByteCount bytes_in_flight) {
189 return bytes_in_flight < GetCongestionWindow();
190}
191
192QuicBandwidth BbrSender::PacingRate(QuicByteCount bytes_in_flight) const {
193 if (pacing_rate_.IsZero()) {
194 return high_gain_ * QuicBandwidth::FromBytesAndTimeDelta(
195 initial_congestion_window_, GetMinRtt());
196 }
197 return pacing_rate_;
198}
199
200QuicBandwidth BbrSender::BandwidthEstimate() const {
201 return max_bandwidth_.GetBest();
202}
203
204QuicByteCount BbrSender::GetCongestionWindow() const {
205 if (mode_ == PROBE_RTT) {
206 return ProbeRttCongestionWindow();
207 }
208
209 if (InRecovery() && !(rate_based_startup_ && mode_ == STARTUP)) {
210 return std::min(congestion_window_, recovery_window_);
211 }
212
213 return congestion_window_;
214}
215
216QuicByteCount BbrSender::GetSlowStartThreshold() const {
217 return 0;
218}
219
220bool BbrSender::InRecovery() const {
221 return recovery_state_ != NOT_IN_RECOVERY;
222}
223
224bool BbrSender::ShouldSendProbingPacket() const {
225 if (pacing_gain_ <= 1) {
226 return false;
227 }
228
229 // TODO(b/77975811): If the pipe is highly under-utilized, consider not
230 // sending a probing transmission, because the extra bandwidth is not needed.
231 // If flexible_app_limited is enabled, check if the pipe is sufficiently full.
232 if (flexible_app_limited_) {
233 return !IsPipeSufficientlyFull();
234 } else {
235 return true;
236 }
237}
238
239bool BbrSender::IsPipeSufficientlyFull() const {
240 // See if we need more bytes in flight to see more bandwidth.
241 if (mode_ == STARTUP) {
242 // STARTUP exits if it doesn't observe a 25% bandwidth increase, so the CWND
243 // must be more than 25% above the target.
244 return unacked_packets_->bytes_in_flight() >=
245 GetTargetCongestionWindow(1.5);
246 }
247 if (pacing_gain_ > 1) {
248 // Super-unity PROBE_BW doesn't exit until 1.25 * BDP is achieved.
249 return unacked_packets_->bytes_in_flight() >=
250 GetTargetCongestionWindow(pacing_gain_);
251 }
252 // If bytes_in_flight are above the target congestion window, it should be
253 // possible to observe the same or more bandwidth if it's available.
254 return unacked_packets_->bytes_in_flight() >= GetTargetCongestionWindow(1.1);
255}
256
257void BbrSender::SetFromConfig(const QuicConfig& config,
258 Perspective perspective) {
259 if (config.HasClientRequestedIndependentOption(kLRTT, perspective)) {
260 exit_startup_on_loss_ = true;
261 }
262 if (config.HasClientRequestedIndependentOption(k1RTT, perspective)) {
263 num_startup_rtts_ = 1;
264 }
265 if (config.HasClientRequestedIndependentOption(k2RTT, perspective)) {
266 num_startup_rtts_ = 2;
267 }
268 if (config.HasClientRequestedIndependentOption(kBBRS, perspective)) {
269 slower_startup_ = true;
270 }
271 if (config.HasClientRequestedIndependentOption(kBBR3, perspective)) {
272 drain_to_target_ = true;
273 }
274 if (config.HasClientRequestedIndependentOption(kBBS1, perspective)) {
275 rate_based_startup_ = true;
276 }
277 if (GetQuicReloadableFlag(quic_bbr_startup_rate_reduction) &&
278 config.HasClientRequestedIndependentOption(kBBS4, perspective)) {
279 rate_based_startup_ = true;
280 // Hits 1.25x pacing multiplier when ~2/3 CWND is lost.
281 startup_rate_reduction_multiplier_ = 1;
282 }
283 if (GetQuicReloadableFlag(quic_bbr_startup_rate_reduction) &&
284 config.HasClientRequestedIndependentOption(kBBS5, perspective)) {
285 rate_based_startup_ = true;
286 // Hits 1.25x pacing multiplier when ~1/3 CWND is lost.
287 startup_rate_reduction_multiplier_ = 2;
288 }
289 if (config.HasClientRequestedIndependentOption(kBBR4, perspective)) {
290 max_ack_height_.SetWindowLength(2 * kBandwidthWindowSize);
291 }
292 if (config.HasClientRequestedIndependentOption(kBBR5, perspective)) {
293 max_ack_height_.SetWindowLength(4 * kBandwidthWindowSize);
294 }
295 if (GetQuicReloadableFlag(quic_bbr_less_probe_rtt) &&
296 config.HasClientRequestedIndependentOption(kBBR6, perspective)) {
297 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_less_probe_rtt, 1, 3);
298 probe_rtt_based_on_bdp_ = true;
299 }
300 if (GetQuicReloadableFlag(quic_bbr_less_probe_rtt) &&
301 config.HasClientRequestedIndependentOption(kBBR7, perspective)) {
302 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_less_probe_rtt, 2, 3);
303 probe_rtt_skipped_if_similar_rtt_ = true;
304 }
305 if (GetQuicReloadableFlag(quic_bbr_less_probe_rtt) &&
306 config.HasClientRequestedIndependentOption(kBBR8, perspective)) {
307 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_less_probe_rtt, 3, 3);
308 probe_rtt_disabled_if_app_limited_ = true;
309 }
310 if (GetQuicReloadableFlag(quic_bbr_flexible_app_limited) &&
311 config.HasClientRequestedIndependentOption(kBBR9, perspective)) {
312 QUIC_RELOADABLE_FLAG_COUNT(quic_bbr_flexible_app_limited);
313 flexible_app_limited_ = true;
314 }
315 if (GetQuicReloadableFlag(quic_bbr_slower_startup3) &&
316 config.HasClientRequestedIndependentOption(kBBQ1, perspective)) {
317 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_slower_startup3, 1, 4);
318 set_high_gain(kDerivedHighGain);
319 set_high_cwnd_gain(kDerivedHighGain);
320 set_drain_gain(1.f / kDerivedHighGain);
321 }
322 if (GetQuicReloadableFlag(quic_bbr_slower_startup3) &&
323 config.HasClientRequestedIndependentOption(kBBQ2, perspective)) {
324 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_slower_startup3, 2, 4);
325 set_high_cwnd_gain(kDerivedHighCWNDGain);
326 }
327 if (GetQuicReloadableFlag(quic_bbr_slower_startup3) &&
328 config.HasClientRequestedIndependentOption(kBBQ3, perspective)) {
329 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_slower_startup3, 3, 4);
330 enable_ack_aggregation_during_startup_ = true;
331 }
332 if (GetQuicReloadableFlag(quic_bbr_slower_startup3) &&
333 config.HasClientRequestedIndependentOption(kBBQ4, perspective)) {
334 QUIC_RELOADABLE_FLAG_COUNT_N(quic_bbr_slower_startup3, 4, 4);
335 set_drain_gain(kModerateProbeRttMultiplier);
336 }
337 if (GetQuicReloadableFlag(quic_bbr_slower_startup4) &&
338 config.HasClientRequestedIndependentOption(kBBQ5, perspective)) {
339 QUIC_RELOADABLE_FLAG_COUNT(quic_bbr_slower_startup4);
340 expire_ack_aggregation_in_startup_ = true;
341 }
342 if (config.HasClientRequestedIndependentOption(kMIN1, perspective)) {
343 min_congestion_window_ = kMaxSegmentSize;
344 }
345}
346
347void BbrSender::AdjustNetworkParameters(QuicBandwidth bandwidth,
348 QuicTime::Delta rtt) {
349 if (!bandwidth.IsZero()) {
350 max_bandwidth_.Update(bandwidth, round_trip_count_);
351 }
352 if (!rtt.IsZero() && (min_rtt_ > rtt || min_rtt_.IsZero())) {
353 min_rtt_ = rtt;
354 }
355}
356
357void BbrSender::OnCongestionEvent(bool /*rtt_updated*/,
358 QuicByteCount prior_in_flight,
359 QuicTime event_time,
360 const AckedPacketVector& acked_packets,
361 const LostPacketVector& lost_packets) {
362 const QuicByteCount total_bytes_acked_before = sampler_.total_bytes_acked();
363
364 bool is_round_start = false;
365 bool min_rtt_expired = false;
366
367 DiscardLostPackets(lost_packets);
368
369 // Input the new data into the BBR model of the connection.
370 QuicByteCount excess_acked = 0;
371 if (!acked_packets.empty()) {
372 QuicPacketNumber last_acked_packet = acked_packets.rbegin()->packet_number;
373 is_round_start = UpdateRoundTripCounter(last_acked_packet);
374 min_rtt_expired = UpdateBandwidthAndMinRtt(event_time, acked_packets);
375 UpdateRecoveryState(last_acked_packet, !lost_packets.empty(),
376 is_round_start);
377
378 const QuicByteCount bytes_acked =
379 sampler_.total_bytes_acked() - total_bytes_acked_before;
380
381 excess_acked = UpdateAckAggregationBytes(event_time, bytes_acked);
382 }
383
384 // Handle logic specific to PROBE_BW mode.
385 if (mode_ == PROBE_BW) {
386 UpdateGainCyclePhase(event_time, prior_in_flight, !lost_packets.empty());
387 }
388
389 // Handle logic specific to STARTUP and DRAIN modes.
390 if (is_round_start && !is_at_full_bandwidth_) {
391 CheckIfFullBandwidthReached();
392 }
393 MaybeExitStartupOrDrain(event_time);
394
395 // Handle logic specific to PROBE_RTT.
396 MaybeEnterOrExitProbeRtt(event_time, is_round_start, min_rtt_expired);
397
398 // Calculate number of packets acked and lost.
399 QuicByteCount bytes_acked =
400 sampler_.total_bytes_acked() - total_bytes_acked_before;
401 QuicByteCount bytes_lost = 0;
402 for (const auto& packet : lost_packets) {
403 bytes_lost += packet.bytes_lost;
404 }
405
406 // After the model is updated, recalculate the pacing rate and congestion
407 // window.
408 CalculatePacingRate();
409 CalculateCongestionWindow(bytes_acked, excess_acked);
410 CalculateRecoveryWindow(bytes_acked, bytes_lost);
411
412 // Cleanup internal state.
413 sampler_.RemoveObsoletePackets(unacked_packets_->GetLeastUnacked());
414}
415
416CongestionControlType BbrSender::GetCongestionControlType() const {
417 return kBBR;
418}
419
420QuicTime::Delta BbrSender::GetMinRtt() const {
421 return !min_rtt_.IsZero() ? min_rtt_ : rtt_stats_->initial_rtt();
422}
423
424QuicByteCount BbrSender::GetTargetCongestionWindow(float gain) const {
425 QuicByteCount bdp = GetMinRtt() * BandwidthEstimate();
426 QuicByteCount congestion_window = gain * bdp;
427
428 // BDP estimate will be zero if no bandwidth samples are available yet.
429 if (congestion_window == 0) {
430 congestion_window = gain * initial_congestion_window_;
431 }
432
433 return std::max(congestion_window, min_congestion_window_);
434}
435
436QuicByteCount BbrSender::ProbeRttCongestionWindow() const {
437 if (probe_rtt_based_on_bdp_) {
438 return GetTargetCongestionWindow(kModerateProbeRttMultiplier);
439 }
440 return min_congestion_window_;
441}
442
wub967ba572019-04-01 09:27:52 -0700443void BbrSender::EnterStartupMode(QuicTime now) {
444 if (stats_) {
445 ++stats_->slowstart_count;
446 DCHECK_EQ(stats_->slowstart_start_time, QuicTime::Zero()) << mode_;
447 stats_->slowstart_start_time = now;
448 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500449 mode_ = STARTUP;
450 pacing_gain_ = high_gain_;
451 congestion_window_gain_ = high_cwnd_gain_;
452}
453
454void BbrSender::EnterProbeBandwidthMode(QuicTime now) {
455 mode_ = PROBE_BW;
456 congestion_window_gain_ = congestion_window_gain_constant_;
457
458 // Pick a random offset for the gain cycle out of {0, 2..7} range. 1 is
459 // excluded because in that case increased gain and decreased gain would not
460 // follow each other.
461 cycle_current_offset_ = random_->RandUint64() % (kGainCycleLength - 1);
462 if (cycle_current_offset_ >= 1) {
463 cycle_current_offset_ += 1;
464 }
465
466 last_cycle_start_ = now;
467 pacing_gain_ = kPacingGain[cycle_current_offset_];
468}
469
470void BbrSender::DiscardLostPackets(const LostPacketVector& lost_packets) {
471 for (const LostPacket& packet : lost_packets) {
472 sampler_.OnPacketLost(packet.packet_number);
wub967ba572019-04-01 09:27:52 -0700473 if (mode_ == STARTUP) {
474 if (stats_) {
475 ++stats_->slowstart_packets_lost;
476 stats_->slowstart_bytes_lost += packet.bytes_lost;
477 }
478 if (startup_rate_reduction_multiplier_ != 0) {
479 startup_bytes_lost_ += packet.bytes_lost;
480 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500481 }
482 }
483}
484
485bool BbrSender::UpdateRoundTripCounter(QuicPacketNumber last_acked_packet) {
486 if (!current_round_trip_end_.IsInitialized() ||
487 last_acked_packet > current_round_trip_end_) {
488 round_trip_count_++;
489 current_round_trip_end_ = last_sent_packet_;
wub967ba572019-04-01 09:27:52 -0700490 if (stats_ && InSlowStart()) {
491 ++stats_->slowstart_num_rtts;
492 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500493 return true;
494 }
495
496 return false;
497}
498
499bool BbrSender::UpdateBandwidthAndMinRtt(
500 QuicTime now,
501 const AckedPacketVector& acked_packets) {
502 QuicTime::Delta sample_min_rtt = QuicTime::Delta::Infinite();
503 for (const auto& packet : acked_packets) {
wubfb4e2132019-04-05 12:30:09 -0700504 if (!always_get_bw_sample_when_acked_ && packet.bytes_acked == 0) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500505 // Skip acked packets with 0 in flight bytes when updating bandwidth.
506 continue;
507 }
508 BandwidthSample bandwidth_sample =
509 sampler_.OnPacketAcknowledged(now, packet.packet_number);
wubfb4e2132019-04-05 12:30:09 -0700510 if (always_get_bw_sample_when_acked_ &&
511 !bandwidth_sample.state_at_send.is_valid) {
512 // From the sampler's perspective, the packet has never been sent, or the
513 // packet has been acked or marked as lost previously.
514 continue;
515 }
516
wub254545c2019-04-04 13:56:52 -0700517 last_sample_is_app_limited_ = bandwidth_sample.state_at_send.is_app_limited;
518 has_non_app_limited_sample_ |=
519 !bandwidth_sample.state_at_send.is_app_limited;
QUICHE teama6ef0a62019-03-07 20:34:33 -0500520 if (!bandwidth_sample.rtt.IsZero()) {
521 sample_min_rtt = std::min(sample_min_rtt, bandwidth_sample.rtt);
522 }
523
wub254545c2019-04-04 13:56:52 -0700524 if (!bandwidth_sample.state_at_send.is_app_limited ||
QUICHE teama6ef0a62019-03-07 20:34:33 -0500525 bandwidth_sample.bandwidth > BandwidthEstimate()) {
526 max_bandwidth_.Update(bandwidth_sample.bandwidth, round_trip_count_);
527 }
528 }
529
530 // If none of the RTT samples are valid, return immediately.
531 if (sample_min_rtt.IsInfinite()) {
532 return false;
533 }
534 min_rtt_since_last_probe_rtt_ =
535 std::min(min_rtt_since_last_probe_rtt_, sample_min_rtt);
536
537 // Do not expire min_rtt if none was ever available.
538 bool min_rtt_expired =
539 !min_rtt_.IsZero() && (now > (min_rtt_timestamp_ + kMinRttExpiry));
540
541 if (min_rtt_expired || sample_min_rtt < min_rtt_ || min_rtt_.IsZero()) {
542 QUIC_DVLOG(2) << "Min RTT updated, old value: " << min_rtt_
543 << ", new value: " << sample_min_rtt
544 << ", current time: " << now.ToDebuggingValue();
545
546 if (min_rtt_expired && ShouldExtendMinRttExpiry()) {
547 min_rtt_expired = false;
548 } else {
549 min_rtt_ = sample_min_rtt;
550 }
551 min_rtt_timestamp_ = now;
552 // Reset since_last_probe_rtt fields.
553 min_rtt_since_last_probe_rtt_ = QuicTime::Delta::Infinite();
554 app_limited_since_last_probe_rtt_ = false;
555 }
556 DCHECK(!min_rtt_.IsZero());
557
558 return min_rtt_expired;
559}
560
561bool BbrSender::ShouldExtendMinRttExpiry() const {
562 if (probe_rtt_disabled_if_app_limited_ && app_limited_since_last_probe_rtt_) {
563 // Extend the current min_rtt if we've been app limited recently.
564 return true;
565 }
566 const bool min_rtt_increased_since_last_probe =
567 min_rtt_since_last_probe_rtt_ > min_rtt_ * kSimilarMinRttThreshold;
568 if (probe_rtt_skipped_if_similar_rtt_ && app_limited_since_last_probe_rtt_ &&
569 !min_rtt_increased_since_last_probe) {
570 // Extend the current min_rtt if we've been app limited recently and an rtt
571 // has been measured in that time that's less than 12.5% more than the
572 // current min_rtt.
573 return true;
574 }
575 return false;
576}
577
578void BbrSender::UpdateGainCyclePhase(QuicTime now,
579 QuicByteCount prior_in_flight,
580 bool has_losses) {
581 const QuicByteCount bytes_in_flight = unacked_packets_->bytes_in_flight();
582 // In most cases, the cycle is advanced after an RTT passes.
583 bool should_advance_gain_cycling = now - last_cycle_start_ > GetMinRtt();
584
585 // If the pacing gain is above 1.0, the connection is trying to probe the
586 // bandwidth by increasing the number of bytes in flight to at least
587 // pacing_gain * BDP. Make sure that it actually reaches the target, as long
588 // as there are no losses suggesting that the buffers are not able to hold
589 // that much.
590 if (pacing_gain_ > 1.0 && !has_losses &&
591 prior_in_flight < GetTargetCongestionWindow(pacing_gain_)) {
592 should_advance_gain_cycling = false;
593 }
594
595 // If pacing gain is below 1.0, the connection is trying to drain the extra
596 // queue which could have been incurred by probing prior to it. If the number
597 // of bytes in flight falls down to the estimated BDP value earlier, conclude
598 // that the queue has been successfully drained and exit this cycle early.
599 if (pacing_gain_ < 1.0 && bytes_in_flight <= GetTargetCongestionWindow(1)) {
600 should_advance_gain_cycling = true;
601 }
602
603 if (should_advance_gain_cycling) {
604 cycle_current_offset_ = (cycle_current_offset_ + 1) % kGainCycleLength;
605 last_cycle_start_ = now;
606 // Stay in low gain mode until the target BDP is hit.
607 // Low gain mode will be exited immediately when the target BDP is achieved.
608 if (drain_to_target_ && pacing_gain_ < 1 &&
609 kPacingGain[cycle_current_offset_] == 1 &&
610 bytes_in_flight > GetTargetCongestionWindow(1)) {
611 return;
612 }
613 pacing_gain_ = kPacingGain[cycle_current_offset_];
614 }
615}
616
617void BbrSender::CheckIfFullBandwidthReached() {
618 if (last_sample_is_app_limited_) {
619 return;
620 }
621
622 QuicBandwidth target = bandwidth_at_last_round_ * kStartupGrowthTarget;
623 if (BandwidthEstimate() >= target) {
624 bandwidth_at_last_round_ = BandwidthEstimate();
625 rounds_without_bandwidth_gain_ = 0;
626 if (expire_ack_aggregation_in_startup_) {
627 // Expire old excess delivery measurements now that bandwidth increased.
628 max_ack_height_.Reset(0, round_trip_count_);
629 }
630 return;
631 }
632
633 rounds_without_bandwidth_gain_++;
634 if ((rounds_without_bandwidth_gain_ >= num_startup_rtts_) ||
635 (exit_startup_on_loss_ && InRecovery())) {
636 DCHECK(has_non_app_limited_sample_);
637 is_at_full_bandwidth_ = true;
638 }
639}
640
641void BbrSender::MaybeExitStartupOrDrain(QuicTime now) {
642 if (mode_ == STARTUP && is_at_full_bandwidth_) {
wub967ba572019-04-01 09:27:52 -0700643 OnExitStartup(now);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500644 mode_ = DRAIN;
645 pacing_gain_ = drain_gain_;
646 congestion_window_gain_ = high_cwnd_gain_;
647 }
648 if (mode_ == DRAIN &&
649 unacked_packets_->bytes_in_flight() <= GetTargetCongestionWindow(1)) {
650 EnterProbeBandwidthMode(now);
651 }
652}
653
wub967ba572019-04-01 09:27:52 -0700654void BbrSender::OnExitStartup(QuicTime now) {
655 DCHECK_EQ(mode_, STARTUP);
656 if (stats_) {
657 DCHECK_NE(stats_->slowstart_start_time, QuicTime::Zero());
658 if (now > stats_->slowstart_start_time) {
659 stats_->slowstart_duration =
660 now - stats_->slowstart_start_time + stats_->slowstart_duration;
661 }
662 stats_->slowstart_start_time = QuicTime::Zero();
663 }
664}
665
QUICHE teama6ef0a62019-03-07 20:34:33 -0500666void BbrSender::MaybeEnterOrExitProbeRtt(QuicTime now,
667 bool is_round_start,
668 bool min_rtt_expired) {
669 if (min_rtt_expired && !exiting_quiescence_ && mode_ != PROBE_RTT) {
wub967ba572019-04-01 09:27:52 -0700670 if (InSlowStart()) {
671 OnExitStartup(now);
672 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500673 mode_ = PROBE_RTT;
674 pacing_gain_ = 1;
675 // Do not decide on the time to exit PROBE_RTT until the |bytes_in_flight|
676 // is at the target small value.
677 exit_probe_rtt_at_ = QuicTime::Zero();
678 }
679
680 if (mode_ == PROBE_RTT) {
681 sampler_.OnAppLimited();
682
683 if (exit_probe_rtt_at_ == QuicTime::Zero()) {
684 // If the window has reached the appropriate size, schedule exiting
685 // PROBE_RTT. The CWND during PROBE_RTT is kMinimumCongestionWindow, but
686 // we allow an extra packet since QUIC checks CWND before sending a
687 // packet.
688 if (unacked_packets_->bytes_in_flight() <
dschinazi66dea072019-04-09 11:41:06 -0700689 ProbeRttCongestionWindow() + kMaxOutgoingPacketSize) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500690 exit_probe_rtt_at_ = now + kProbeRttTime;
691 probe_rtt_round_passed_ = false;
692 }
693 } else {
694 if (is_round_start) {
695 probe_rtt_round_passed_ = true;
696 }
697 if (now >= exit_probe_rtt_at_ && probe_rtt_round_passed_) {
698 min_rtt_timestamp_ = now;
699 if (!is_at_full_bandwidth_) {
wub967ba572019-04-01 09:27:52 -0700700 EnterStartupMode(now);
QUICHE teama6ef0a62019-03-07 20:34:33 -0500701 } else {
702 EnterProbeBandwidthMode(now);
703 }
704 }
705 }
706 }
707
708 exiting_quiescence_ = false;
709}
710
711void BbrSender::UpdateRecoveryState(QuicPacketNumber last_acked_packet,
712 bool has_losses,
713 bool is_round_start) {
714 // Exit recovery when there are no losses for a round.
715 if (has_losses) {
716 end_recovery_at_ = last_sent_packet_;
717 }
718
719 switch (recovery_state_) {
720 case NOT_IN_RECOVERY:
721 // Enter conservation on the first loss.
722 if (has_losses) {
723 recovery_state_ = CONSERVATION;
724 // This will cause the |recovery_window_| to be set to the correct
725 // value in CalculateRecoveryWindow().
726 recovery_window_ = 0;
727 // Since the conservation phase is meant to be lasting for a whole
728 // round, extend the current round as if it were started right now.
729 current_round_trip_end_ = last_sent_packet_;
730 if (GetQuicReloadableFlag(quic_bbr_app_limited_recovery) &&
731 last_sample_is_app_limited_) {
732 QUIC_RELOADABLE_FLAG_COUNT(quic_bbr_app_limited_recovery);
733 is_app_limited_recovery_ = true;
734 }
735 }
736 break;
737
738 case CONSERVATION:
739 if (is_round_start) {
740 recovery_state_ = GROWTH;
741 }
742 QUIC_FALLTHROUGH_INTENDED;
743
744 case GROWTH:
745 // Exit recovery if appropriate.
746 if (!has_losses && last_acked_packet > end_recovery_at_) {
747 recovery_state_ = NOT_IN_RECOVERY;
748 is_app_limited_recovery_ = false;
749 }
750
751 break;
752 }
753 if (recovery_state_ != NOT_IN_RECOVERY && is_app_limited_recovery_) {
754 sampler_.OnAppLimited();
755 }
756}
757
758// TODO(ianswett): Move this logic into BandwidthSampler.
759QuicByteCount BbrSender::UpdateAckAggregationBytes(
760 QuicTime ack_time,
761 QuicByteCount newly_acked_bytes) {
762 // Compute how many bytes are expected to be delivered, assuming max bandwidth
763 // is correct.
764 QuicByteCount expected_bytes_acked =
765 max_bandwidth_.GetBest() * (ack_time - aggregation_epoch_start_time_);
766 // Reset the current aggregation epoch as soon as the ack arrival rate is less
767 // than or equal to the max bandwidth.
768 if (aggregation_epoch_bytes_ <= expected_bytes_acked) {
769 // Reset to start measuring a new aggregation epoch.
770 aggregation_epoch_bytes_ = newly_acked_bytes;
771 aggregation_epoch_start_time_ = ack_time;
772 return 0;
773 }
774
775 // Compute how many extra bytes were delivered vs max bandwidth.
776 // Include the bytes most recently acknowledged to account for stretch acks.
777 aggregation_epoch_bytes_ += newly_acked_bytes;
778 max_ack_height_.Update(aggregation_epoch_bytes_ - expected_bytes_acked,
779 round_trip_count_);
780 return aggregation_epoch_bytes_ - expected_bytes_acked;
781}
782
783void BbrSender::CalculatePacingRate() {
784 if (BandwidthEstimate().IsZero()) {
785 return;
786 }
787
788 QuicBandwidth target_rate = pacing_gain_ * BandwidthEstimate();
789 if (is_at_full_bandwidth_) {
790 pacing_rate_ = target_rate;
791 return;
792 }
793
794 // Pace at the rate of initial_window / RTT as soon as RTT measurements are
795 // available.
796 if (pacing_rate_.IsZero() && !rtt_stats_->min_rtt().IsZero()) {
797 pacing_rate_ = QuicBandwidth::FromBytesAndTimeDelta(
798 initial_congestion_window_, rtt_stats_->min_rtt());
799 return;
800 }
801 // Slow the pacing rate in STARTUP once loss has ever been detected.
802 const bool has_ever_detected_loss = end_recovery_at_.IsInitialized();
803 if (slower_startup_ && has_ever_detected_loss &&
804 has_non_app_limited_sample_) {
805 pacing_rate_ = kStartupAfterLossGain * BandwidthEstimate();
806 return;
807 }
808
809 // Slow the pacing rate in STARTUP by the bytes_lost / CWND.
810 if (startup_rate_reduction_multiplier_ != 0 && has_ever_detected_loss &&
811 has_non_app_limited_sample_) {
812 pacing_rate_ =
813 (1 - (startup_bytes_lost_ * startup_rate_reduction_multiplier_ * 1.0f /
814 congestion_window_)) *
815 target_rate;
816 // Ensure the pacing rate doesn't drop below the startup growth target times
817 // the bandwidth estimate.
818 pacing_rate_ =
819 std::max(pacing_rate_, kStartupGrowthTarget * BandwidthEstimate());
820 return;
821 }
822
823 // Do not decrease the pacing rate during startup.
824 pacing_rate_ = std::max(pacing_rate_, target_rate);
825}
826
827void BbrSender::CalculateCongestionWindow(QuicByteCount bytes_acked,
828 QuicByteCount excess_acked) {
829 if (mode_ == PROBE_RTT) {
830 return;
831 }
832
833 QuicByteCount target_window =
834 GetTargetCongestionWindow(congestion_window_gain_);
835 if (is_at_full_bandwidth_) {
836 // Add the max recently measured ack aggregation to CWND.
837 target_window += max_ack_height_.GetBest();
838 } else if (enable_ack_aggregation_during_startup_) {
839 // Add the most recent excess acked. Because CWND never decreases in
840 // STARTUP, this will automatically create a very localized max filter.
841 target_window += excess_acked;
842 }
843
844 // Instead of immediately setting the target CWND as the new one, BBR grows
845 // the CWND towards |target_window| by only increasing it |bytes_acked| at a
846 // time.
847 const bool add_bytes_acked =
848 !GetQuicReloadableFlag(quic_bbr_no_bytes_acked_in_startup_recovery) ||
849 !InRecovery();
850 if (is_at_full_bandwidth_) {
851 congestion_window_ =
852 std::min(target_window, congestion_window_ + bytes_acked);
853 } else if (add_bytes_acked &&
854 (congestion_window_ < target_window ||
855 sampler_.total_bytes_acked() < initial_congestion_window_)) {
856 // If the connection is not yet out of startup phase, do not decrease the
857 // window.
858 congestion_window_ = congestion_window_ + bytes_acked;
859 }
860
861 // Enforce the limits on the congestion window.
862 congestion_window_ = std::max(congestion_window_, min_congestion_window_);
863 congestion_window_ = std::min(congestion_window_, max_congestion_window_);
864}
865
866void BbrSender::CalculateRecoveryWindow(QuicByteCount bytes_acked,
867 QuicByteCount bytes_lost) {
868 if (rate_based_startup_ && mode_ == STARTUP) {
869 return;
870 }
871
872 if (recovery_state_ == NOT_IN_RECOVERY) {
873 return;
874 }
875
876 // Set up the initial recovery window.
877 if (recovery_window_ == 0) {
878 recovery_window_ = unacked_packets_->bytes_in_flight() + bytes_acked;
879 recovery_window_ = std::max(min_congestion_window_, recovery_window_);
880 return;
881 }
882
883 // Remove losses from the recovery window, while accounting for a potential
884 // integer underflow.
885 recovery_window_ = recovery_window_ >= bytes_lost
886 ? recovery_window_ - bytes_lost
887 : kMaxSegmentSize;
888
889 // In CONSERVATION mode, just subtracting losses is sufficient. In GROWTH,
890 // release additional |bytes_acked| to achieve a slow-start-like behavior.
891 if (recovery_state_ == GROWTH) {
892 recovery_window_ += bytes_acked;
893 }
894
895 // Sanity checks. Ensure that we always allow to send at least an MSS or
896 // |bytes_acked| in response, whichever is larger.
897 recovery_window_ = std::max(
898 recovery_window_, unacked_packets_->bytes_in_flight() + bytes_acked);
899 if (GetQuicReloadableFlag(quic_bbr_one_mss_conservation)) {
900 recovery_window_ =
901 std::max(recovery_window_,
902 unacked_packets_->bytes_in_flight() + kMaxSegmentSize);
903 }
904 recovery_window_ = std::max(min_congestion_window_, recovery_window_);
905}
906
vasilvvc48c8712019-03-11 13:38:16 -0700907std::string BbrSender::GetDebugState() const {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500908 std::ostringstream stream;
909 stream << ExportDebugState();
910 return stream.str();
911}
912
913void BbrSender::OnApplicationLimited(QuicByteCount bytes_in_flight) {
914 if (bytes_in_flight >= GetCongestionWindow()) {
915 return;
916 }
917 if (flexible_app_limited_ && IsPipeSufficientlyFull()) {
918 return;
919 }
920
921 app_limited_since_last_probe_rtt_ = true;
922 sampler_.OnAppLimited();
923 QUIC_DVLOG(2) << "Becoming application limited. Last sent packet: "
924 << last_sent_packet_ << ", CWND: " << GetCongestionWindow();
925}
926
927BbrSender::DebugState BbrSender::ExportDebugState() const {
928 return DebugState(*this);
929}
930
vasilvvc48c8712019-03-11 13:38:16 -0700931static std::string ModeToString(BbrSender::Mode mode) {
QUICHE teama6ef0a62019-03-07 20:34:33 -0500932 switch (mode) {
933 case BbrSender::STARTUP:
934 return "STARTUP";
935 case BbrSender::DRAIN:
936 return "DRAIN";
937 case BbrSender::PROBE_BW:
938 return "PROBE_BW";
939 case BbrSender::PROBE_RTT:
940 return "PROBE_RTT";
941 }
942 return "???";
943}
944
945std::ostream& operator<<(std::ostream& os, const BbrSender::Mode& mode) {
946 os << ModeToString(mode);
947 return os;
948}
949
950std::ostream& operator<<(std::ostream& os, const BbrSender::DebugState& state) {
951 os << "Mode: " << ModeToString(state.mode) << std::endl;
952 os << "Maximum bandwidth: " << state.max_bandwidth << std::endl;
953 os << "Round trip counter: " << state.round_trip_count << std::endl;
954 os << "Gain cycle index: " << static_cast<int>(state.gain_cycle_index)
955 << std::endl;
956 os << "Congestion window: " << state.congestion_window << " bytes"
957 << std::endl;
958
959 if (state.mode == BbrSender::STARTUP) {
960 os << "(startup) Bandwidth at last round: " << state.bandwidth_at_last_round
961 << std::endl;
962 os << "(startup) Rounds without gain: "
963 << state.rounds_without_bandwidth_gain << std::endl;
964 }
965
966 os << "Minimum RTT: " << state.min_rtt << std::endl;
967 os << "Minimum RTT timestamp: " << state.min_rtt_timestamp.ToDebuggingValue()
968 << std::endl;
969
970 os << "Last sample is app-limited: "
971 << (state.last_sample_is_app_limited ? "yes" : "no");
972
973 return os;
974}
975
976} // namespace quic