1 // Copyright 2013 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 "quiche/quic/core/quic_sent_packet_manager.h"
6
7 #include <algorithm>
8 #include <cstddef>
9 #include <string>
10
11 #include "quiche/quic/core/congestion_control/general_loss_algorithm.h"
12 #include "quiche/quic/core/congestion_control/pacing_sender.h"
13 #include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
14 #include "quiche/quic/core/crypto/crypto_protocol.h"
15 #include "quiche/quic/core/frames/quic_ack_frequency_frame.h"
16 #include "quiche/quic/core/proto/cached_network_parameters_proto.h"
17 #include "quiche/quic/core/quic_connection_stats.h"
18 #include "quiche/quic/core/quic_constants.h"
19 #include "quiche/quic/core/quic_packet_number.h"
20 #include "quiche/quic/core/quic_transmission_info.h"
21 #include "quiche/quic/core/quic_types.h"
22 #include "quiche/quic/core/quic_utils.h"
23 #include "quiche/quic/platform/api/quic_bug_tracker.h"
24 #include "quiche/quic/platform/api/quic_flag_utils.h"
25 #include "quiche/quic/platform/api/quic_flags.h"
26 #include "quiche/quic/platform/api/quic_logging.h"
27 #include "quiche/common/print_elements.h"
28
29 namespace quic {
30
31 namespace {
32 static const int64_t kDefaultRetransmissionTimeMs = 500;
33
34 // Ensure the handshake timer isnt't faster than 10ms.
35 // This limits the tenth retransmitted packet to 10s after the initial CHLO.
36 static const int64_t kMinHandshakeTimeoutMs = 10;
37
38 // Sends up to two tail loss probes before firing an RTO,
39 // per draft RFC draft-dukkipati-tcpm-tcp-loss-probe.
40 static const size_t kDefaultMaxTailLossProbes = 2;
41
42 // The multiplier for calculating PTO timeout before any RTT sample is
43 // available.
44 static const float kPtoMultiplierWithoutRttSamples = 3;
45
46 // Returns true of retransmissions of the specified type should retransmit
47 // the frames directly (as opposed to resulting in a loss notification).
ShouldForceRetransmission(TransmissionType transmission_type)48 inline bool ShouldForceRetransmission(TransmissionType transmission_type) {
49 return transmission_type == HANDSHAKE_RETRANSMISSION ||
50 transmission_type == PTO_RETRANSMISSION;
51 }
52
53 // If pacing rate is accurate, > 2 burst token is not likely to help first ACK
54 // to arrive earlier, and overly large burst token could cause incast packet
55 // losses.
56 static const uint32_t kConservativeUnpacedBurst = 2;
57
58 // The default number of PTOs to trigger path degrading.
59 static const uint32_t kNumProbeTimeoutsForPathDegradingDelay = 4;
60
61 } // namespace
62
63 #define ENDPOINT \
64 (unacked_packets_.perspective() == Perspective::IS_SERVER ? "Server: " \
65 : "Client: ")
66
QuicSentPacketManager(Perspective perspective,const QuicClock * clock,QuicRandom * random,QuicConnectionStats * stats,CongestionControlType congestion_control_type)67 QuicSentPacketManager::QuicSentPacketManager(
68 Perspective perspective, const QuicClock* clock, QuicRandom* random,
69 QuicConnectionStats* stats, CongestionControlType congestion_control_type)
70 : unacked_packets_(perspective),
71 clock_(clock),
72 random_(random),
73 stats_(stats),
74 debug_delegate_(nullptr),
75 network_change_visitor_(nullptr),
76 initial_congestion_window_(kInitialCongestionWindow),
77 loss_algorithm_(&uber_loss_algorithm_),
78 consecutive_crypto_retransmission_count_(0),
79 pending_timer_transmission_count_(0),
80 using_pacing_(false),
81 conservative_handshake_retransmits_(false),
82 largest_mtu_acked_(0),
83 handshake_finished_(false),
84 peer_max_ack_delay_(
85 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs)),
86 rtt_updated_(false),
87 acked_packets_iter_(last_ack_frame_.packets.rbegin()),
88 consecutive_pto_count_(0),
89 handshake_mode_disabled_(false),
90 handshake_packet_acked_(false),
91 zero_rtt_packet_acked_(false),
92 one_rtt_packet_acked_(false),
93 num_ptos_for_path_degrading_(kNumProbeTimeoutsForPathDegradingDelay),
94 ignore_pings_(false),
95 ignore_ack_delay_(false) {
96 SetSendAlgorithm(congestion_control_type);
97 }
98
~QuicSentPacketManager()99 QuicSentPacketManager::~QuicSentPacketManager() {}
100
SetFromConfig(const QuicConfig & config)101 void QuicSentPacketManager::SetFromConfig(const QuicConfig& config) {
102 const Perspective perspective = unacked_packets_.perspective();
103 if (config.HasReceivedInitialRoundTripTimeUs() &&
104 config.ReceivedInitialRoundTripTimeUs() > 0) {
105 if (!config.HasClientSentConnectionOption(kNRTT, perspective)) {
106 SetInitialRtt(QuicTime::Delta::FromMicroseconds(
107 config.ReceivedInitialRoundTripTimeUs()),
108 /*trusted=*/false);
109 }
110 } else if (config.HasInitialRoundTripTimeUsToSend() &&
111 config.GetInitialRoundTripTimeUsToSend() > 0) {
112 SetInitialRtt(QuicTime::Delta::FromMicroseconds(
113 config.GetInitialRoundTripTimeUsToSend()),
114 /*trusted=*/false);
115 }
116 if (config.HasReceivedMaxAckDelayMs()) {
117 peer_max_ack_delay_ =
118 QuicTime::Delta::FromMilliseconds(config.ReceivedMaxAckDelayMs());
119 }
120 if (GetQuicReloadableFlag(quic_can_send_ack_frequency) &&
121 perspective == Perspective::IS_SERVER) {
122 if (config.HasReceivedMinAckDelayMs()) {
123 peer_min_ack_delay_ =
124 QuicTime::Delta::FromMilliseconds(config.ReceivedMinAckDelayMs());
125 }
126 if (config.HasClientSentConnectionOption(kAFF1, perspective)) {
127 use_smoothed_rtt_in_ack_delay_ = true;
128 }
129 }
130 if (config.HasClientSentConnectionOption(kMAD0, perspective)) {
131 ignore_ack_delay_ = true;
132 }
133
134 // Configure congestion control.
135 if (config.HasClientRequestedIndependentOption(kTBBR, perspective)) {
136 SetSendAlgorithm(kBBR);
137 }
138 if (GetQuicReloadableFlag(quic_allow_client_enabled_bbr_v2) &&
139 config.HasClientRequestedIndependentOption(kB2ON, perspective)) {
140 QUIC_RELOADABLE_FLAG_COUNT(quic_allow_client_enabled_bbr_v2);
141 SetSendAlgorithm(kBBRv2);
142 }
143
144 if (config.HasClientRequestedIndependentOption(kRENO, perspective)) {
145 SetSendAlgorithm(kRenoBytes);
146 } else if (config.HasClientRequestedIndependentOption(kBYTE, perspective) ||
147 (GetQuicReloadableFlag(quic_default_to_bbr) &&
148 config.HasClientRequestedIndependentOption(kQBIC, perspective))) {
149 SetSendAlgorithm(kCubicBytes);
150 }
151
152 // Initial window.
153 if (config.HasClientRequestedIndependentOption(kIW03, perspective)) {
154 initial_congestion_window_ = 3;
155 send_algorithm_->SetInitialCongestionWindowInPackets(3);
156 }
157 if (config.HasClientRequestedIndependentOption(kIW10, perspective)) {
158 initial_congestion_window_ = 10;
159 send_algorithm_->SetInitialCongestionWindowInPackets(10);
160 }
161 if (config.HasClientRequestedIndependentOption(kIW20, perspective)) {
162 initial_congestion_window_ = 20;
163 send_algorithm_->SetInitialCongestionWindowInPackets(20);
164 }
165 if (config.HasClientRequestedIndependentOption(kIW50, perspective)) {
166 initial_congestion_window_ = 50;
167 send_algorithm_->SetInitialCongestionWindowInPackets(50);
168 }
169 if (config.HasClientRequestedIndependentOption(kBWS5, perspective)) {
170 initial_congestion_window_ = 10;
171 send_algorithm_->SetInitialCongestionWindowInPackets(10);
172 }
173
174 if (config.HasClientRequestedIndependentOption(kIGNP, perspective)) {
175 ignore_pings_ = true;
176 }
177
178 using_pacing_ = !GetQuicFlag(quic_disable_pacing_for_perf_tests);
179 // Configure loss detection.
180 if (config.HasClientRequestedIndependentOption(kILD0, perspective)) {
181 uber_loss_algorithm_.SetReorderingShift(kDefaultIetfLossDelayShift);
182 uber_loss_algorithm_.DisableAdaptiveReorderingThreshold();
183 }
184 if (config.HasClientRequestedIndependentOption(kILD1, perspective)) {
185 uber_loss_algorithm_.SetReorderingShift(kDefaultLossDelayShift);
186 uber_loss_algorithm_.DisableAdaptiveReorderingThreshold();
187 }
188 if (config.HasClientRequestedIndependentOption(kILD2, perspective)) {
189 uber_loss_algorithm_.EnableAdaptiveReorderingThreshold();
190 uber_loss_algorithm_.SetReorderingShift(kDefaultIetfLossDelayShift);
191 }
192 if (config.HasClientRequestedIndependentOption(kILD3, perspective)) {
193 uber_loss_algorithm_.SetReorderingShift(kDefaultLossDelayShift);
194 uber_loss_algorithm_.EnableAdaptiveReorderingThreshold();
195 }
196 if (config.HasClientRequestedIndependentOption(kILD4, perspective)) {
197 uber_loss_algorithm_.SetReorderingShift(kDefaultLossDelayShift);
198 uber_loss_algorithm_.EnableAdaptiveReorderingThreshold();
199 uber_loss_algorithm_.EnableAdaptiveTimeThreshold();
200 }
201 if (config.HasClientRequestedIndependentOption(kRUNT, perspective)) {
202 uber_loss_algorithm_.DisablePacketThresholdForRuntPackets();
203 }
204 if (config.HasClientSentConnectionOption(kCONH, perspective)) {
205 conservative_handshake_retransmits_ = true;
206 }
207 send_algorithm_->SetFromConfig(config, perspective);
208 loss_algorithm_->SetFromConfig(config, perspective);
209
210 if (network_change_visitor_ != nullptr) {
211 network_change_visitor_->OnCongestionChange();
212 }
213
214 if (debug_delegate_ != nullptr) {
215 DebugDelegate::SendParameters parameters;
216 parameters.congestion_control_type =
217 send_algorithm_->GetCongestionControlType();
218 parameters.use_pacing = using_pacing_;
219 parameters.initial_congestion_window = initial_congestion_window_;
220 debug_delegate_->OnConfigProcessed(parameters);
221 }
222 }
223
ApplyConnectionOptions(const QuicTagVector & connection_options)224 void QuicSentPacketManager::ApplyConnectionOptions(
225 const QuicTagVector& connection_options) {
226 std::optional<CongestionControlType> cc_type;
227 if (ContainsQuicTag(connection_options, kB2ON)) {
228 cc_type = kBBRv2;
229 } else if (ContainsQuicTag(connection_options, kTBBR)) {
230 cc_type = kBBR;
231 } else if (ContainsQuicTag(connection_options, kRENO)) {
232 cc_type = kRenoBytes;
233 } else if (ContainsQuicTag(connection_options, kQBIC)) {
234 cc_type = kCubicBytes;
235 }
236
237 if (cc_type.has_value()) {
238 SetSendAlgorithm(*cc_type);
239 }
240
241 send_algorithm_->ApplyConnectionOptions(connection_options);
242 }
243
ResumeConnectionState(const CachedNetworkParameters & cached_network_params,bool max_bandwidth_resumption)244 void QuicSentPacketManager::ResumeConnectionState(
245 const CachedNetworkParameters& cached_network_params,
246 bool max_bandwidth_resumption) {
247 QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(
248 max_bandwidth_resumption
249 ? cached_network_params.max_bandwidth_estimate_bytes_per_second()
250 : cached_network_params.bandwidth_estimate_bytes_per_second());
251 QuicTime::Delta rtt =
252 QuicTime::Delta::FromMilliseconds(cached_network_params.min_rtt_ms());
253 // This calls the old AdjustNetworkParameters interface, and fills certain
254 // fields in SendAlgorithmInterface::NetworkParams
255 // (e.g., quic_bbr_fix_pacing_rate) using GFE flags.
256 SendAlgorithmInterface::NetworkParams params(
257 bandwidth, rtt, /*allow_cwnd_to_decrease = */ false);
258 // The rtt is trusted because it's a min_rtt measured from a previous
259 // connection with the same network path between client and server.
260 params.is_rtt_trusted = true;
261 AdjustNetworkParameters(params);
262 }
263
AdjustNetworkParameters(const SendAlgorithmInterface::NetworkParams & params)264 void QuicSentPacketManager::AdjustNetworkParameters(
265 const SendAlgorithmInterface::NetworkParams& params) {
266 const QuicBandwidth& bandwidth = params.bandwidth;
267 const QuicTime::Delta& rtt = params.rtt;
268
269 if (!rtt.IsZero()) {
270 if (params.is_rtt_trusted) {
271 // Always set initial rtt if it's trusted.
272 SetInitialRtt(rtt, /*trusted=*/true);
273 } else if (rtt_stats_.initial_rtt() ==
274 QuicTime::Delta::FromMilliseconds(kInitialRttMs)) {
275 // Only set initial rtt if we are using the default. This avoids
276 // overwriting a trusted initial rtt by an untrusted one.
277 SetInitialRtt(rtt, /*trusted=*/false);
278 }
279 }
280
281 const QuicByteCount old_cwnd = send_algorithm_->GetCongestionWindow();
282 if (GetQuicReloadableFlag(quic_conservative_bursts) && using_pacing_ &&
283 !bandwidth.IsZero()) {
284 QUIC_RELOADABLE_FLAG_COUNT(quic_conservative_bursts);
285 pacing_sender_.SetBurstTokens(kConservativeUnpacedBurst);
286 }
287 send_algorithm_->AdjustNetworkParameters(params);
288 if (debug_delegate_ != nullptr) {
289 debug_delegate_->OnAdjustNetworkParameters(
290 bandwidth, rtt.IsZero() ? rtt_stats_.MinOrInitialRtt() : rtt, old_cwnd,
291 send_algorithm_->GetCongestionWindow());
292 }
293 }
294
SetLossDetectionTuner(std::unique_ptr<LossDetectionTunerInterface> tuner)295 void QuicSentPacketManager::SetLossDetectionTuner(
296 std::unique_ptr<LossDetectionTunerInterface> tuner) {
297 uber_loss_algorithm_.SetLossDetectionTuner(std::move(tuner));
298 }
299
OnConfigNegotiated()300 void QuicSentPacketManager::OnConfigNegotiated() {
301 loss_algorithm_->OnConfigNegotiated();
302 }
303
OnConnectionClosed()304 void QuicSentPacketManager::OnConnectionClosed() {
305 loss_algorithm_->OnConnectionClosed();
306 }
307
SetHandshakeConfirmed()308 void QuicSentPacketManager::SetHandshakeConfirmed() {
309 if (!handshake_finished_) {
310 handshake_finished_ = true;
311 NeuterHandshakePackets();
312 }
313 }
314
PostProcessNewlyAckedPackets(QuicPacketNumber ack_packet_number,EncryptionLevel ack_decrypted_level,const QuicAckFrame & ack_frame,QuicTime ack_receive_time,bool rtt_updated,QuicByteCount prior_bytes_in_flight,std::optional<QuicEcnCounts> ecn_counts)315 void QuicSentPacketManager::PostProcessNewlyAckedPackets(
316 QuicPacketNumber ack_packet_number, EncryptionLevel ack_decrypted_level,
317 const QuicAckFrame& ack_frame, QuicTime ack_receive_time, bool rtt_updated,
318 QuicByteCount prior_bytes_in_flight,
319 std::optional<QuicEcnCounts> ecn_counts) {
320 unacked_packets_.NotifyAggregatedStreamFrameAcked(
321 last_ack_frame_.ack_delay_time);
322 InvokeLossDetection(ack_receive_time);
323 MaybeInvokeCongestionEvent(
324 rtt_updated, prior_bytes_in_flight, ack_receive_time, ecn_counts,
325 peer_ack_ecn_counts_[QuicUtils::GetPacketNumberSpace(
326 ack_decrypted_level)]);
327 unacked_packets_.RemoveObsoletePackets();
328
329 sustained_bandwidth_recorder_.RecordEstimate(
330 send_algorithm_->InRecovery(), send_algorithm_->InSlowStart(),
331 send_algorithm_->BandwidthEstimate(), ack_receive_time, clock_->WallNow(),
332 rtt_stats_.smoothed_rtt());
333
334 // Anytime we are making forward progress and have a new RTT estimate, reset
335 // the backoff counters.
336 if (rtt_updated) {
337 // Records the max consecutive PTO before forward progress has been made.
338 if (consecutive_pto_count_ >
339 stats_->max_consecutive_rto_with_forward_progress) {
340 stats_->max_consecutive_rto_with_forward_progress =
341 consecutive_pto_count_;
342 }
343 // Reset all retransmit counters any time a new packet is acked.
344 consecutive_pto_count_ = 0;
345 consecutive_crypto_retransmission_count_ = 0;
346 }
347
348 if (debug_delegate_ != nullptr) {
349 debug_delegate_->OnIncomingAck(
350 ack_packet_number, ack_decrypted_level, ack_frame, ack_receive_time,
351 LargestAcked(ack_frame), rtt_updated, GetLeastUnacked());
352 }
353 // Remove packets below least unacked from all_packets_acked_ and
354 // last_ack_frame_.
355 last_ack_frame_.packets.RemoveUpTo(unacked_packets_.GetLeastUnacked());
356 last_ack_frame_.received_packet_times.clear();
357 }
358
MaybeInvokeCongestionEvent(bool rtt_updated,QuicByteCount prior_in_flight,QuicTime event_time,std::optional<QuicEcnCounts> ecn_counts,const QuicEcnCounts & previous_counts)359 void QuicSentPacketManager::MaybeInvokeCongestionEvent(
360 bool rtt_updated, QuicByteCount prior_in_flight, QuicTime event_time,
361 std::optional<QuicEcnCounts> ecn_counts,
362 const QuicEcnCounts& previous_counts) {
363 if (!rtt_updated && packets_acked_.empty() && packets_lost_.empty()) {
364 return;
365 }
366 const bool overshooting_detected =
367 stats_->overshooting_detected_with_network_parameters_adjusted;
368 // A connection should send at most one flavor of ECT, so only one variable
369 // is necessary.
370 QuicPacketCount newly_acked_ect = 0, newly_acked_ce = 0;
371 if (ecn_counts.has_value()) {
372 QUICHE_DCHECK(GetQuicReloadableFlag(quic_send_ect1));
373 newly_acked_ect = ecn_counts->ect1 - previous_counts.ect1;
374 if (newly_acked_ect == 0) {
375 newly_acked_ect = ecn_counts->ect0 - previous_counts.ect0;
376 } else {
377 QUIC_BUG_IF(quic_bug_518619343_04,
378 ecn_counts->ect0 - previous_counts.ect0)
379 << "Sent ECT(0) and ECT(1) newly acked in the same ACK.";
380 }
381 newly_acked_ce = ecn_counts->ce - previous_counts.ce;
382 }
383 if (using_pacing_) {
384 pacing_sender_.OnCongestionEvent(rtt_updated, prior_in_flight, event_time,
385 packets_acked_, packets_lost_,
386 newly_acked_ect, newly_acked_ce);
387 } else {
388 send_algorithm_->OnCongestionEvent(rtt_updated, prior_in_flight, event_time,
389 packets_acked_, packets_lost_,
390 newly_acked_ect, newly_acked_ce);
391 }
392 if (debug_delegate_ != nullptr && !overshooting_detected &&
393 stats_->overshooting_detected_with_network_parameters_adjusted) {
394 debug_delegate_->OnOvershootingDetected();
395 }
396 packets_acked_.clear();
397 packets_lost_.clear();
398 if (network_change_visitor_ != nullptr) {
399 network_change_visitor_->OnCongestionChange();
400 }
401 }
402
MarkInitialPacketsForRetransmission()403 void QuicSentPacketManager::MarkInitialPacketsForRetransmission() {
404 if (unacked_packets_.empty()) {
405 return;
406 }
407 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
408 QuicPacketNumber largest_sent_packet = unacked_packets_.largest_sent_packet();
409 for (; packet_number <= largest_sent_packet; ++packet_number) {
410 QuicTransmissionInfo* transmission_info =
411 unacked_packets_.GetMutableTransmissionInfo(packet_number);
412 if (transmission_info->encryption_level == ENCRYPTION_INITIAL) {
413 if (transmission_info->in_flight) {
414 unacked_packets_.RemoveFromInFlight(transmission_info);
415 }
416 if (unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
417 MarkForRetransmission(packet_number, ALL_INITIAL_RETRANSMISSION);
418 }
419 }
420 }
421 }
422
MarkZeroRttPacketsForRetransmission()423 void QuicSentPacketManager::MarkZeroRttPacketsForRetransmission() {
424 if (unacked_packets_.empty()) {
425 return;
426 }
427 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
428 QuicPacketNumber largest_sent_packet = unacked_packets_.largest_sent_packet();
429 for (; packet_number <= largest_sent_packet; ++packet_number) {
430 QuicTransmissionInfo* transmission_info =
431 unacked_packets_.GetMutableTransmissionInfo(packet_number);
432 if (transmission_info->encryption_level == ENCRYPTION_ZERO_RTT) {
433 if (transmission_info->in_flight) {
434 // Remove 0-RTT packets and packets of the wrong version from flight,
435 // because neither can be processed by the peer.
436 unacked_packets_.RemoveFromInFlight(transmission_info);
437 }
438 if (unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
439 MarkForRetransmission(packet_number, ALL_ZERO_RTT_RETRANSMISSION);
440 }
441 }
442 }
443 }
444
NeuterUnencryptedPackets()445 void QuicSentPacketManager::NeuterUnencryptedPackets() {
446 for (QuicPacketNumber packet_number :
447 unacked_packets_.NeuterUnencryptedPackets()) {
448 send_algorithm_->OnPacketNeutered(packet_number);
449 }
450 if (handshake_mode_disabled_) {
451 consecutive_pto_count_ = 0;
452 uber_loss_algorithm_.ResetLossDetection(INITIAL_DATA);
453 }
454 }
455
NeuterHandshakePackets()456 void QuicSentPacketManager::NeuterHandshakePackets() {
457 for (QuicPacketNumber packet_number :
458 unacked_packets_.NeuterHandshakePackets()) {
459 send_algorithm_->OnPacketNeutered(packet_number);
460 }
461 if (handshake_mode_disabled_) {
462 consecutive_pto_count_ = 0;
463 uber_loss_algorithm_.ResetLossDetection(HANDSHAKE_DATA);
464 }
465 }
466
ShouldAddMaxAckDelay(PacketNumberSpace space) const467 bool QuicSentPacketManager::ShouldAddMaxAckDelay(
468 PacketNumberSpace space) const {
469 // Do not include max_ack_delay when PTO is armed for Initial or Handshake
470 // packet number spaces.
471 return !supports_multiple_packet_number_spaces() || space == APPLICATION_DATA;
472 }
473
GetEarliestPacketSentTimeForPto(PacketNumberSpace * packet_number_space) const474 QuicTime QuicSentPacketManager::GetEarliestPacketSentTimeForPto(
475 PacketNumberSpace* packet_number_space) const {
476 QUICHE_DCHECK(supports_multiple_packet_number_spaces());
477 QuicTime earliest_sent_time = QuicTime::Zero();
478 for (int8_t i = 0; i < NUM_PACKET_NUMBER_SPACES; ++i) {
479 const QuicTime sent_time = unacked_packets_.GetLastInFlightPacketSentTime(
480 static_cast<PacketNumberSpace>(i));
481 if (!handshake_finished_ && i == APPLICATION_DATA) {
482 // Do not arm PTO for application data until handshake gets confirmed.
483 continue;
484 }
485 if (!sent_time.IsInitialized() || (earliest_sent_time.IsInitialized() &&
486 earliest_sent_time <= sent_time)) {
487 continue;
488 }
489 earliest_sent_time = sent_time;
490 *packet_number_space = static_cast<PacketNumberSpace>(i);
491 }
492
493 return earliest_sent_time;
494 }
495
MarkForRetransmission(QuicPacketNumber packet_number,TransmissionType transmission_type)496 void QuicSentPacketManager::MarkForRetransmission(
497 QuicPacketNumber packet_number, TransmissionType transmission_type) {
498 QuicTransmissionInfo* transmission_info =
499 unacked_packets_.GetMutableTransmissionInfo(packet_number);
500 // Packets without retransmittable frames can only be marked for loss
501 // retransmission.
502 QUIC_BUG_IF(quic_bug_12552_2, transmission_type != LOSS_RETRANSMISSION &&
503 !unacked_packets_.HasRetransmittableFrames(
504 *transmission_info))
505 << "packet number " << packet_number
506 << " transmission_type: " << transmission_type << " transmission_info "
507 << transmission_info->DebugString();
508 if (ShouldForceRetransmission(transmission_type)) {
509 if (!unacked_packets_.RetransmitFrames(
510 QuicFrames(transmission_info->retransmittable_frames),
511 transmission_type)) {
512 // Do not set packet state if the data is not fully retransmitted.
513 // This should only happen if packet payload size decreases which can be
514 // caused by:
515 // 1) connection tries to opportunistically retransmit data
516 // when sending a packet of a different packet number space, or
517 // 2) path MTU decreases, or
518 // 3) packet header size increases (e.g., packet number length
519 // increases).
520 QUIC_CODE_COUNT(quic_retransmit_frames_failed);
521 return;
522 }
523 QUIC_CODE_COUNT(quic_retransmit_frames_succeeded);
524 } else {
525 unacked_packets_.NotifyFramesLost(*transmission_info, transmission_type);
526
527 if (!transmission_info->retransmittable_frames.empty()) {
528 if (transmission_type == LOSS_RETRANSMISSION) {
529 // Record the first packet sent after loss, which allows to wait 1
530 // more RTT before giving up on this lost packet.
531 transmission_info->first_sent_after_loss =
532 unacked_packets_.largest_sent_packet() + 1;
533 } else {
534 // Clear the recorded first packet sent after loss when version or
535 // encryption changes.
536 transmission_info->first_sent_after_loss.Clear();
537 }
538 }
539 }
540
541 // Get the latest transmission_info here as it can be invalidated after
542 // HandleRetransmission adding new sent packets into unacked_packets_.
543 transmission_info =
544 unacked_packets_.GetMutableTransmissionInfo(packet_number);
545
546 // Update packet state according to transmission type.
547 transmission_info->state =
548 QuicUtils::RetransmissionTypeToPacketState(transmission_type);
549 }
550
RecordOneSpuriousRetransmission(const QuicTransmissionInfo & info)551 void QuicSentPacketManager::RecordOneSpuriousRetransmission(
552 const QuicTransmissionInfo& info) {
553 stats_->bytes_spuriously_retransmitted += info.bytes_sent;
554 ++stats_->packets_spuriously_retransmitted;
555 if (debug_delegate_ != nullptr) {
556 debug_delegate_->OnSpuriousPacketRetransmission(info.transmission_type,
557 info.bytes_sent);
558 }
559 }
560
MarkPacketHandled(QuicPacketNumber packet_number,QuicTransmissionInfo * info,QuicTime ack_receive_time,QuicTime::Delta ack_delay_time,QuicTime receive_timestamp)561 void QuicSentPacketManager::MarkPacketHandled(QuicPacketNumber packet_number,
562 QuicTransmissionInfo* info,
563 QuicTime ack_receive_time,
564 QuicTime::Delta ack_delay_time,
565 QuicTime receive_timestamp) {
566 if (info->has_ack_frequency) {
567 for (const auto& frame : info->retransmittable_frames) {
568 if (frame.type == ACK_FREQUENCY_FRAME) {
569 OnAckFrequencyFrameAcked(*frame.ack_frequency_frame);
570 }
571 }
572 }
573 // Try to aggregate acked stream frames if acked packet is not a
574 // retransmission.
575 if (info->transmission_type == NOT_RETRANSMISSION) {
576 unacked_packets_.MaybeAggregateAckedStreamFrame(*info, ack_delay_time,
577 receive_timestamp);
578 } else {
579 unacked_packets_.NotifyAggregatedStreamFrameAcked(ack_delay_time);
580 const bool new_data_acked = unacked_packets_.NotifyFramesAcked(
581 *info, ack_delay_time, receive_timestamp);
582 if (!new_data_acked && info->transmission_type != NOT_RETRANSMISSION) {
583 // Record as a spurious retransmission if this packet is a
584 // retransmission and no new data gets acked.
585 QUIC_DVLOG(1) << "Detect spurious retransmitted packet " << packet_number
586 << " transmission type: " << info->transmission_type;
587 RecordOneSpuriousRetransmission(*info);
588 }
589 }
590 if (info->state == LOST) {
591 // Record as a spurious loss as a packet previously declared lost gets
592 // acked.
593 const PacketNumberSpace packet_number_space =
594 unacked_packets_.GetPacketNumberSpace(info->encryption_level);
595 const QuicPacketNumber previous_largest_acked =
596 supports_multiple_packet_number_spaces()
597 ? unacked_packets_.GetLargestAckedOfPacketNumberSpace(
598 packet_number_space)
599 : unacked_packets_.largest_acked();
600 QUIC_DVLOG(1) << "Packet " << packet_number
601 << " was detected lost spuriously, "
602 "previous_largest_acked: "
603 << previous_largest_acked;
604 loss_algorithm_->SpuriousLossDetected(unacked_packets_, rtt_stats_,
605 ack_receive_time, packet_number,
606 previous_largest_acked);
607 ++stats_->packet_spuriously_detected_lost;
608 }
609
610 if (network_change_visitor_ != nullptr &&
611 info->bytes_sent > largest_mtu_acked_) {
612 largest_mtu_acked_ = info->bytes_sent;
613 network_change_visitor_->OnPathMtuIncreased(largest_mtu_acked_);
614 }
615 unacked_packets_.RemoveFromInFlight(info);
616 unacked_packets_.RemoveRetransmittability(info);
617 info->state = ACKED;
618 }
619
CanSendAckFrequency() const620 bool QuicSentPacketManager::CanSendAckFrequency() const {
621 return !peer_min_ack_delay_.IsInfinite() && handshake_finished_;
622 }
623
GetUpdatedAckFrequencyFrame() const624 QuicAckFrequencyFrame QuicSentPacketManager::GetUpdatedAckFrequencyFrame()
625 const {
626 QuicAckFrequencyFrame frame;
627 if (!CanSendAckFrequency()) {
628 QUIC_BUG(quic_bug_10750_1)
629 << "New AckFrequencyFrame is created while it shouldn't.";
630 return frame;
631 }
632
633 QUIC_RELOADABLE_FLAG_COUNT_N(quic_can_send_ack_frequency, 1, 3);
634 frame.packet_tolerance = kMaxRetransmittablePacketsBeforeAck;
635 auto rtt = use_smoothed_rtt_in_ack_delay_ ? rtt_stats_.SmoothedOrInitialRtt()
636 : rtt_stats_.MinOrInitialRtt();
637 frame.max_ack_delay = rtt * kAckDecimationDelay;
638 frame.max_ack_delay = std::max(frame.max_ack_delay, peer_min_ack_delay_);
639 // TODO(haoyuewang) Remove this once kDefaultMinAckDelayTimeMs is updated to
640 // 5 ms on the client side.
641 frame.max_ack_delay =
642 std::max(frame.max_ack_delay,
643 QuicTime::Delta::FromMilliseconds(kDefaultMinAckDelayTimeMs));
644 return frame;
645 }
646
RecordEcnMarkingSent(QuicEcnCodepoint ecn_codepoint,EncryptionLevel level)647 void QuicSentPacketManager::RecordEcnMarkingSent(QuicEcnCodepoint ecn_codepoint,
648 EncryptionLevel level) {
649 PacketNumberSpace space = QuicUtils::GetPacketNumberSpace(level);
650 switch (ecn_codepoint) {
651 case ECN_NOT_ECT:
652 break;
653 case ECN_ECT0:
654 ++ect0_packets_sent_[space];
655 break;
656 case ECN_ECT1:
657 ++ect1_packets_sent_[space];
658 break;
659 case ECN_CE:
660 // Test only: endpoints MUST NOT send CE. As CE reports will have to
661 // correspond to either an ECT(0) or an ECT(1) packet to be valid, just
662 // increment both to avoid validation failure.
663 ++ect0_packets_sent_[space];
664 ++ect1_packets_sent_[space];
665 break;
666 }
667 }
668
OnPacketSent(SerializedPacket * mutable_packet,QuicTime sent_time,TransmissionType transmission_type,HasRetransmittableData has_retransmittable_data,bool measure_rtt,QuicEcnCodepoint ecn_codepoint)669 bool QuicSentPacketManager::OnPacketSent(
670 SerializedPacket* mutable_packet, QuicTime sent_time,
671 TransmissionType transmission_type,
672 HasRetransmittableData has_retransmittable_data, bool measure_rtt,
673 QuicEcnCodepoint ecn_codepoint) {
674 const SerializedPacket& packet = *mutable_packet;
675 QuicPacketNumber packet_number = packet.packet_number;
676 QUICHE_DCHECK_LE(FirstSendingPacketNumber(), packet_number);
677 QUICHE_DCHECK(!unacked_packets_.IsUnacked(packet_number));
678 QUIC_BUG_IF(quic_bug_10750_2, packet.encrypted_length == 0)
679 << "Cannot send empty packets.";
680 if (pending_timer_transmission_count_ > 0) {
681 --pending_timer_transmission_count_;
682 }
683
684 bool in_flight = has_retransmittable_data == HAS_RETRANSMITTABLE_DATA;
685 if (ignore_pings_ && mutable_packet->retransmittable_frames.size() == 1 &&
686 mutable_packet->retransmittable_frames[0].type == PING_FRAME) {
687 // Dot not use PING only packet for RTT measure or congestion control.
688 in_flight = false;
689 measure_rtt = false;
690 }
691 if (using_pacing_) {
692 pacing_sender_.OnPacketSent(sent_time, unacked_packets_.bytes_in_flight(),
693 packet_number, packet.encrypted_length,
694 has_retransmittable_data);
695 } else {
696 send_algorithm_->OnPacketSent(sent_time, unacked_packets_.bytes_in_flight(),
697 packet_number, packet.encrypted_length,
698 has_retransmittable_data);
699 }
700
701 // Deallocate message data in QuicMessageFrame immediately after packet
702 // sent.
703 if (packet.has_message) {
704 for (auto& frame : mutable_packet->retransmittable_frames) {
705 if (frame.type == MESSAGE_FRAME) {
706 frame.message_frame->message_data.clear();
707 frame.message_frame->message_length = 0;
708 }
709 }
710 }
711
712 if (packet.has_ack_frequency) {
713 for (const auto& frame : packet.retransmittable_frames) {
714 if (frame.type == ACK_FREQUENCY_FRAME) {
715 OnAckFrequencyFrameSent(*frame.ack_frequency_frame);
716 }
717 }
718 }
719 RecordEcnMarkingSent(ecn_codepoint, packet.encryption_level);
720 unacked_packets_.AddSentPacket(mutable_packet, transmission_type, sent_time,
721 in_flight, measure_rtt, ecn_codepoint);
722 // Reset the retransmission timer anytime a pending packet is sent.
723 return in_flight;
724 }
725
726 QuicSentPacketManager::RetransmissionTimeoutMode
OnRetransmissionTimeout()727 QuicSentPacketManager::OnRetransmissionTimeout() {
728 QUICHE_DCHECK(unacked_packets_.HasInFlightPackets() ||
729 (handshake_mode_disabled_ && !handshake_finished_));
730 QUICHE_DCHECK_EQ(0u, pending_timer_transmission_count_);
731 // Handshake retransmission, timer based loss detection, TLP, and RTO are
732 // implemented with a single alarm. The handshake alarm is set when the
733 // handshake has not completed, the loss alarm is set when the loss detection
734 // algorithm says to, and the TLP and RTO alarms are set after that.
735 // The TLP alarm is always set to run for under an RTO.
736 switch (GetRetransmissionMode()) {
737 case HANDSHAKE_MODE:
738 QUICHE_DCHECK(!handshake_mode_disabled_);
739 ++stats_->crypto_retransmit_count;
740 RetransmitCryptoPackets();
741 return HANDSHAKE_MODE;
742 case LOSS_MODE: {
743 ++stats_->loss_timeout_count;
744 QuicByteCount prior_in_flight = unacked_packets_.bytes_in_flight();
745 const QuicTime now = clock_->Now();
746 InvokeLossDetection(now);
747 MaybeInvokeCongestionEvent(false, prior_in_flight, now,
748 std::optional<QuicEcnCounts>(),
749 peer_ack_ecn_counts_[APPLICATION_DATA]);
750 return LOSS_MODE;
751 }
752 case PTO_MODE:
753 QUIC_DVLOG(1) << ENDPOINT << "PTO mode";
754 ++stats_->pto_count;
755 if (handshake_mode_disabled_ && !handshake_finished_) {
756 ++stats_->crypto_retransmit_count;
757 }
758 ++consecutive_pto_count_;
759 pending_timer_transmission_count_ = 1;
760 return PTO_MODE;
761 }
762 QUIC_BUG(quic_bug_10750_3)
763 << "Unknown retransmission mode " << GetRetransmissionMode();
764 return GetRetransmissionMode();
765 }
766
RetransmitCryptoPackets()767 void QuicSentPacketManager::RetransmitCryptoPackets() {
768 QUICHE_DCHECK_EQ(HANDSHAKE_MODE, GetRetransmissionMode());
769 ++consecutive_crypto_retransmission_count_;
770 bool packet_retransmitted = false;
771 std::vector<QuicPacketNumber> crypto_retransmissions;
772 if (!unacked_packets_.empty()) {
773 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
774 QuicPacketNumber largest_sent_packet =
775 unacked_packets_.largest_sent_packet();
776 for (; packet_number <= largest_sent_packet; ++packet_number) {
777 QuicTransmissionInfo* transmission_info =
778 unacked_packets_.GetMutableTransmissionInfo(packet_number);
779 // Only retransmit frames which are in flight, and therefore have been
780 // sent.
781 if (!transmission_info->in_flight ||
782 transmission_info->state != OUTSTANDING ||
783 !transmission_info->has_crypto_handshake ||
784 !unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
785 continue;
786 }
787 packet_retransmitted = true;
788 crypto_retransmissions.push_back(packet_number);
789 ++pending_timer_transmission_count_;
790 }
791 }
792 QUICHE_DCHECK(packet_retransmitted)
793 << "No crypto packets found to retransmit.";
794 for (QuicPacketNumber retransmission : crypto_retransmissions) {
795 MarkForRetransmission(retransmission, HANDSHAKE_RETRANSMISSION);
796 }
797 }
798
MaybeRetransmitOldestPacket(TransmissionType type)799 bool QuicSentPacketManager::MaybeRetransmitOldestPacket(TransmissionType type) {
800 if (!unacked_packets_.empty()) {
801 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
802 QuicPacketNumber largest_sent_packet =
803 unacked_packets_.largest_sent_packet();
804 for (; packet_number <= largest_sent_packet; ++packet_number) {
805 QuicTransmissionInfo* transmission_info =
806 unacked_packets_.GetMutableTransmissionInfo(packet_number);
807 // Only retransmit frames which are in flight, and therefore have been
808 // sent.
809 if (!transmission_info->in_flight ||
810 transmission_info->state != OUTSTANDING ||
811 !unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
812 continue;
813 }
814 MarkForRetransmission(packet_number, type);
815 return true;
816 }
817 }
818 QUIC_DVLOG(1)
819 << "No retransmittable packets, so RetransmitOldestPacket failed.";
820 return false;
821 }
822
MaybeSendProbePacket()823 void QuicSentPacketManager::MaybeSendProbePacket() {
824 if (pending_timer_transmission_count_ == 0) {
825 return;
826 }
827 PacketNumberSpace packet_number_space;
828 if (supports_multiple_packet_number_spaces()) {
829 // Find out the packet number space to send probe packets.
830 if (!GetEarliestPacketSentTimeForPto(&packet_number_space)
831 .IsInitialized()) {
832 QUIC_BUG_IF(quic_earliest_sent_time_not_initialized,
833 unacked_packets_.perspective() == Perspective::IS_SERVER)
834 << "earliest_sent_time not initialized when trying to send PTO "
835 "retransmissions";
836 return;
837 }
838 }
839 std::vector<QuicPacketNumber> probing_packets;
840 if (!unacked_packets_.empty()) {
841 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
842 QuicPacketNumber largest_sent_packet =
843 unacked_packets_.largest_sent_packet();
844 for (; packet_number <= largest_sent_packet; ++packet_number) {
845 QuicTransmissionInfo* transmission_info =
846 unacked_packets_.GetMutableTransmissionInfo(packet_number);
847 if (transmission_info->state == OUTSTANDING &&
848 unacked_packets_.HasRetransmittableFrames(*transmission_info) &&
849 (!supports_multiple_packet_number_spaces() ||
850 unacked_packets_.GetPacketNumberSpace(
851 transmission_info->encryption_level) == packet_number_space)) {
852 QUICHE_DCHECK(transmission_info->in_flight);
853 probing_packets.push_back(packet_number);
854 if (probing_packets.size() == pending_timer_transmission_count_) {
855 break;
856 }
857 }
858 }
859 }
860
861 for (QuicPacketNumber retransmission : probing_packets) {
862 QUIC_DVLOG(1) << ENDPOINT << "Marking " << retransmission
863 << " for probing retransmission";
864 MarkForRetransmission(retransmission, PTO_RETRANSMISSION);
865 }
866 // It is possible that there is not enough outstanding data for probing.
867 }
868
EnableIetfPtoAndLossDetection()869 void QuicSentPacketManager::EnableIetfPtoAndLossDetection() {
870 // Disable handshake mode.
871 handshake_mode_disabled_ = true;
872 }
873
RetransmitDataOfSpaceIfAny(PacketNumberSpace space)874 void QuicSentPacketManager::RetransmitDataOfSpaceIfAny(
875 PacketNumberSpace space) {
876 QUICHE_DCHECK(supports_multiple_packet_number_spaces());
877 if (!unacked_packets_.GetLastInFlightPacketSentTime(space).IsInitialized()) {
878 // No in flight data of space.
879 return;
880 }
881 if (unacked_packets_.empty()) {
882 return;
883 }
884 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
885 QuicPacketNumber largest_sent_packet = unacked_packets_.largest_sent_packet();
886 for (; packet_number <= largest_sent_packet; ++packet_number) {
887 QuicTransmissionInfo* transmission_info =
888 unacked_packets_.GetMutableTransmissionInfo(packet_number);
889 if (transmission_info->state == OUTSTANDING &&
890 unacked_packets_.HasRetransmittableFrames(*transmission_info) &&
891 unacked_packets_.GetPacketNumberSpace(
892 transmission_info->encryption_level) == space) {
893 QUICHE_DCHECK(transmission_info->in_flight);
894 if (pending_timer_transmission_count_ == 0) {
895 pending_timer_transmission_count_ = 1;
896 }
897 MarkForRetransmission(packet_number, PTO_RETRANSMISSION);
898 return;
899 }
900 }
901 }
902
903 QuicSentPacketManager::RetransmissionTimeoutMode
GetRetransmissionMode() const904 QuicSentPacketManager::GetRetransmissionMode() const {
905 QUICHE_DCHECK(unacked_packets_.HasInFlightPackets() ||
906 (handshake_mode_disabled_ && !handshake_finished_));
907 if (!handshake_mode_disabled_ && !handshake_finished_ &&
908 unacked_packets_.HasPendingCryptoPackets()) {
909 return HANDSHAKE_MODE;
910 }
911 if (loss_algorithm_->GetLossTimeout() != QuicTime::Zero()) {
912 return LOSS_MODE;
913 }
914 return PTO_MODE;
915 }
916
InvokeLossDetection(QuicTime time)917 void QuicSentPacketManager::InvokeLossDetection(QuicTime time) {
918 if (!packets_acked_.empty()) {
919 QUICHE_DCHECK_LE(packets_acked_.front().packet_number,
920 packets_acked_.back().packet_number);
921 largest_newly_acked_ = packets_acked_.back().packet_number;
922 }
923 LossDetectionInterface::DetectionStats detection_stats =
924 loss_algorithm_->DetectLosses(unacked_packets_, time, rtt_stats_,
925 largest_newly_acked_, packets_acked_,
926 &packets_lost_);
927
928 if (detection_stats.sent_packets_max_sequence_reordering >
929 stats_->sent_packets_max_sequence_reordering) {
930 stats_->sent_packets_max_sequence_reordering =
931 detection_stats.sent_packets_max_sequence_reordering;
932 }
933
934 stats_->sent_packets_num_borderline_time_reorderings +=
935 detection_stats.sent_packets_num_borderline_time_reorderings;
936
937 stats_->total_loss_detection_response_time +=
938 detection_stats.total_loss_detection_response_time;
939
940 for (const LostPacket& packet : packets_lost_) {
941 QuicTransmissionInfo* info =
942 unacked_packets_.GetMutableTransmissionInfo(packet.packet_number);
943 ++stats_->packets_lost;
944 if (debug_delegate_ != nullptr) {
945 debug_delegate_->OnPacketLoss(packet.packet_number,
946 info->encryption_level, LOSS_RETRANSMISSION,
947 time);
948 }
949 unacked_packets_.RemoveFromInFlight(info);
950
951 MarkForRetransmission(packet.packet_number, LOSS_RETRANSMISSION);
952 }
953 }
954
MaybeUpdateRTT(QuicPacketNumber largest_acked,QuicTime::Delta ack_delay_time,QuicTime ack_receive_time)955 bool QuicSentPacketManager::MaybeUpdateRTT(QuicPacketNumber largest_acked,
956 QuicTime::Delta ack_delay_time,
957 QuicTime ack_receive_time) {
958 // We rely on ack_delay_time to compute an RTT estimate, so we
959 // only update rtt when the largest observed gets acked and the acked packet
960 // is not useless.
961 if (!unacked_packets_.IsUnacked(largest_acked)) {
962 return false;
963 }
964 // We calculate the RTT based on the highest ACKed packet number, the lower
965 // packet numbers will include the ACK aggregation delay.
966 const QuicTransmissionInfo& transmission_info =
967 unacked_packets_.GetTransmissionInfo(largest_acked);
968 // Ensure the packet has a valid sent time.
969 if (transmission_info.sent_time == QuicTime::Zero()) {
970 QUIC_BUG(quic_bug_10750_4)
971 << "Acked packet has zero sent time, largest_acked:" << largest_acked;
972 return false;
973 }
974 if (transmission_info.state == NOT_CONTRIBUTING_RTT) {
975 return false;
976 }
977 if (transmission_info.sent_time > ack_receive_time) {
978 QUIC_CODE_COUNT(quic_receive_acked_before_sending);
979 }
980
981 QuicTime::Delta send_delta = ack_receive_time - transmission_info.sent_time;
982 const bool min_rtt_available = !rtt_stats_.min_rtt().IsZero();
983 rtt_stats_.UpdateRtt(send_delta, ack_delay_time, ack_receive_time);
984
985 if (!min_rtt_available && !rtt_stats_.min_rtt().IsZero()) {
986 loss_algorithm_->OnMinRttAvailable();
987 }
988
989 return true;
990 }
991
TimeUntilSend(QuicTime now) const992 QuicTime::Delta QuicSentPacketManager::TimeUntilSend(QuicTime now) const {
993 // The TLP logic is entirely contained within QuicSentPacketManager, so the
994 // send algorithm does not need to be consulted.
995 if (pending_timer_transmission_count_ > 0) {
996 return QuicTime::Delta::Zero();
997 }
998
999 if (using_pacing_) {
1000 return pacing_sender_.TimeUntilSend(now,
1001 unacked_packets_.bytes_in_flight());
1002 }
1003
1004 return send_algorithm_->CanSend(unacked_packets_.bytes_in_flight())
1005 ? QuicTime::Delta::Zero()
1006 : QuicTime::Delta::Infinite();
1007 }
1008
GetRetransmissionTime() const1009 const QuicTime QuicSentPacketManager::GetRetransmissionTime() const {
1010 if (!unacked_packets_.HasInFlightPackets() &&
1011 PeerCompletedAddressValidation()) {
1012 return QuicTime::Zero();
1013 }
1014 if (pending_timer_transmission_count_ > 0) {
1015 // Do not set the timer if there is any credit left.
1016 return QuicTime::Zero();
1017 }
1018 switch (GetRetransmissionMode()) {
1019 case HANDSHAKE_MODE:
1020 return unacked_packets_.GetLastCryptoPacketSentTime() +
1021 GetCryptoRetransmissionDelay();
1022 case LOSS_MODE:
1023 return loss_algorithm_->GetLossTimeout();
1024 case PTO_MODE: {
1025 if (!supports_multiple_packet_number_spaces()) {
1026 if (unacked_packets_.HasInFlightPackets() &&
1027 consecutive_pto_count_ == 0) {
1028 // Arm 1st PTO with earliest in flight sent time, and make sure at
1029 // least kFirstPtoSrttMultiplier * RTT has been passed since last
1030 // in flight packet.
1031 return std::max(
1032 clock_->ApproximateNow(),
1033 std::max(unacked_packets_.GetFirstInFlightTransmissionInfo()
1034 ->sent_time +
1035 GetProbeTimeoutDelay(NUM_PACKET_NUMBER_SPACES),
1036 unacked_packets_.GetLastInFlightPacketSentTime() +
1037 kFirstPtoSrttMultiplier *
1038 rtt_stats_.SmoothedOrInitialRtt()));
1039 }
1040 // Ensure PTO never gets set to a time in the past.
1041 return std::max(clock_->ApproximateNow(),
1042 unacked_packets_.GetLastInFlightPacketSentTime() +
1043 GetProbeTimeoutDelay(NUM_PACKET_NUMBER_SPACES));
1044 }
1045
1046 PacketNumberSpace packet_number_space = NUM_PACKET_NUMBER_SPACES;
1047 // earliest_right_edge is the earliest sent time of the last in flight
1048 // packet of all packet number spaces.
1049 QuicTime earliest_right_edge =
1050 GetEarliestPacketSentTimeForPto(&packet_number_space);
1051 if (!earliest_right_edge.IsInitialized()) {
1052 // Arm PTO from now if there is no in flight packets.
1053 earliest_right_edge = clock_->ApproximateNow();
1054 }
1055 if (packet_number_space == APPLICATION_DATA &&
1056 consecutive_pto_count_ == 0) {
1057 const QuicTransmissionInfo* first_application_info =
1058 unacked_packets_.GetFirstInFlightTransmissionInfoOfSpace(
1059 APPLICATION_DATA);
1060 if (first_application_info != nullptr) {
1061 // Arm 1st PTO with earliest in flight sent time, and make sure at
1062 // least kFirstPtoSrttMultiplier * RTT has been passed since last
1063 // in flight packet. Only do this for application data.
1064 return std::max(
1065 clock_->ApproximateNow(),
1066 std::max(
1067 first_application_info->sent_time +
1068 GetProbeTimeoutDelay(packet_number_space),
1069 earliest_right_edge + kFirstPtoSrttMultiplier *
1070 rtt_stats_.SmoothedOrInitialRtt()));
1071 }
1072 }
1073 return std::max(
1074 clock_->ApproximateNow(),
1075 earliest_right_edge + GetProbeTimeoutDelay(packet_number_space));
1076 }
1077 }
1078 QUICHE_DCHECK(false);
1079 return QuicTime::Zero();
1080 }
1081
GetPathDegradingDelay() const1082 const QuicTime::Delta QuicSentPacketManager::GetPathDegradingDelay() const {
1083 QUICHE_DCHECK_GT(num_ptos_for_path_degrading_, 0);
1084 return num_ptos_for_path_degrading_ * GetPtoDelay();
1085 }
1086
GetNetworkBlackholeDelay(int8_t num_rtos_for_blackhole_detection) const1087 const QuicTime::Delta QuicSentPacketManager::GetNetworkBlackholeDelay(
1088 int8_t num_rtos_for_blackhole_detection) const {
1089 return GetNConsecutiveRetransmissionTimeoutDelay(
1090 kDefaultMaxTailLossProbes + num_rtos_for_blackhole_detection);
1091 }
1092
GetMtuReductionDelay(int8_t num_rtos_for_blackhole_detection) const1093 QuicTime::Delta QuicSentPacketManager::GetMtuReductionDelay(
1094 int8_t num_rtos_for_blackhole_detection) const {
1095 return GetNetworkBlackholeDelay(num_rtos_for_blackhole_detection / 2);
1096 }
1097
GetCryptoRetransmissionDelay() const1098 const QuicTime::Delta QuicSentPacketManager::GetCryptoRetransmissionDelay()
1099 const {
1100 // This is equivalent to the TailLossProbeDelay, but slightly more aggressive
1101 // because crypto handshake messages don't incur a delayed ack time.
1102 QuicTime::Delta srtt = rtt_stats_.SmoothedOrInitialRtt();
1103 int64_t delay_ms;
1104 if (conservative_handshake_retransmits_) {
1105 // Using the delayed ack time directly could cause conservative handshake
1106 // retransmissions to actually be more aggressive than the default.
1107 delay_ms = std::max(peer_max_ack_delay_.ToMilliseconds(),
1108 static_cast<int64_t>(2 * srtt.ToMilliseconds()));
1109 } else {
1110 delay_ms = std::max(kMinHandshakeTimeoutMs,
1111 static_cast<int64_t>(1.5 * srtt.ToMilliseconds()));
1112 }
1113 return QuicTime::Delta::FromMilliseconds(
1114 delay_ms << consecutive_crypto_retransmission_count_);
1115 }
1116
GetProbeTimeoutDelay(PacketNumberSpace space) const1117 const QuicTime::Delta QuicSentPacketManager::GetProbeTimeoutDelay(
1118 PacketNumberSpace space) const {
1119 if (rtt_stats_.smoothed_rtt().IsZero()) {
1120 // Respect kMinHandshakeTimeoutMs to avoid a potential amplification attack.
1121 QUIC_BUG_IF(quic_bug_12552_6, rtt_stats_.initial_rtt().IsZero());
1122 return std::max(kPtoMultiplierWithoutRttSamples * rtt_stats_.initial_rtt(),
1123 QuicTime::Delta::FromMilliseconds(kMinHandshakeTimeoutMs)) *
1124 (1 << consecutive_pto_count_);
1125 }
1126 QuicTime::Delta pto_delay =
1127 rtt_stats_.smoothed_rtt() +
1128 std::max(kPtoRttvarMultiplier * rtt_stats_.mean_deviation(),
1129 kAlarmGranularity) +
1130 (ShouldAddMaxAckDelay(space) ? peer_max_ack_delay_
1131 : QuicTime::Delta::Zero());
1132 return pto_delay * (1 << consecutive_pto_count_);
1133 }
1134
GetSlowStartDuration() const1135 QuicTime::Delta QuicSentPacketManager::GetSlowStartDuration() const {
1136 if (send_algorithm_->GetCongestionControlType() == kBBR ||
1137 send_algorithm_->GetCongestionControlType() == kBBRv2) {
1138 return stats_->slowstart_duration.GetTotalElapsedTime(
1139 clock_->ApproximateNow());
1140 }
1141 return QuicTime::Delta::Infinite();
1142 }
1143
GetAvailableCongestionWindowInBytes() const1144 QuicByteCount QuicSentPacketManager::GetAvailableCongestionWindowInBytes()
1145 const {
1146 QuicByteCount congestion_window = GetCongestionWindowInBytes();
1147 QuicByteCount bytes_in_flight = GetBytesInFlight();
1148 return congestion_window - std::min(congestion_window, bytes_in_flight);
1149 }
1150
GetDebugState() const1151 std::string QuicSentPacketManager::GetDebugState() const {
1152 return send_algorithm_->GetDebugState();
1153 }
1154
SetSendAlgorithm(CongestionControlType congestion_control_type)1155 void QuicSentPacketManager::SetSendAlgorithm(
1156 CongestionControlType congestion_control_type) {
1157 if (send_algorithm_ &&
1158 send_algorithm_->GetCongestionControlType() == congestion_control_type) {
1159 return;
1160 }
1161
1162 SetSendAlgorithm(SendAlgorithmInterface::Create(
1163 clock_, &rtt_stats_, &unacked_packets_, congestion_control_type, random_,
1164 stats_, initial_congestion_window_, send_algorithm_.get()));
1165 }
1166
SetSendAlgorithm(SendAlgorithmInterface * send_algorithm)1167 void QuicSentPacketManager::SetSendAlgorithm(
1168 SendAlgorithmInterface* send_algorithm) {
1169 if (debug_delegate_ != nullptr && send_algorithm != nullptr) {
1170 debug_delegate_->OnSendAlgorithmChanged(
1171 send_algorithm->GetCongestionControlType());
1172 }
1173 send_algorithm_.reset(send_algorithm);
1174 pacing_sender_.set_sender(send_algorithm);
1175 }
1176
1177 std::unique_ptr<SendAlgorithmInterface>
OnConnectionMigration(bool reset_send_algorithm)1178 QuicSentPacketManager::OnConnectionMigration(bool reset_send_algorithm) {
1179 consecutive_pto_count_ = 0;
1180 rtt_stats_.OnConnectionMigration();
1181 if (!reset_send_algorithm) {
1182 send_algorithm_->OnConnectionMigration();
1183 return nullptr;
1184 }
1185
1186 std::unique_ptr<SendAlgorithmInterface> old_send_algorithm =
1187 std::move(send_algorithm_);
1188 SetSendAlgorithm(old_send_algorithm->GetCongestionControlType());
1189 // Treat all in flight packets sent to the old peer address as lost and
1190 // retransmit them.
1191 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
1192 for (auto it = unacked_packets_.begin(); it != unacked_packets_.end();
1193 ++it, ++packet_number) {
1194 if (it->in_flight) {
1195 // Proactively retransmit any packet which is in flight on the old path.
1196 // As a result, these packets will not contribute to congestion control.
1197 unacked_packets_.RemoveFromInFlight(packet_number);
1198 // Retransmitting these packets with PATH_CHANGE_RETRANSMISSION will mark
1199 // them as useless, thus not contributing to RTT stats.
1200 if (unacked_packets_.HasRetransmittableFrames(packet_number)) {
1201 MarkForRetransmission(packet_number, PATH_RETRANSMISSION);
1202 QUICHE_DCHECK_EQ(it->state, NOT_CONTRIBUTING_RTT);
1203 }
1204 }
1205 it->state = NOT_CONTRIBUTING_RTT;
1206 }
1207 return old_send_algorithm;
1208 }
1209
OnAckFrameStart(QuicPacketNumber largest_acked,QuicTime::Delta ack_delay_time,QuicTime ack_receive_time)1210 void QuicSentPacketManager::OnAckFrameStart(QuicPacketNumber largest_acked,
1211 QuicTime::Delta ack_delay_time,
1212 QuicTime ack_receive_time) {
1213 QUICHE_DCHECK(packets_acked_.empty());
1214 QUICHE_DCHECK_LE(largest_acked, unacked_packets_.largest_sent_packet());
1215 // Ignore peer_max_ack_delay and use received ack_delay during
1216 // handshake when supporting multiple packet number spaces.
1217 if (!supports_multiple_packet_number_spaces() || handshake_finished_) {
1218 if (ack_delay_time > peer_max_ack_delay()) {
1219 ack_delay_time = peer_max_ack_delay();
1220 }
1221 if (ignore_ack_delay_) {
1222 ack_delay_time = QuicTime::Delta::Zero();
1223 }
1224 }
1225 rtt_updated_ =
1226 MaybeUpdateRTT(largest_acked, ack_delay_time, ack_receive_time);
1227 last_ack_frame_.ack_delay_time = ack_delay_time;
1228 acked_packets_iter_ = last_ack_frame_.packets.rbegin();
1229 }
1230
OnAckRange(QuicPacketNumber start,QuicPacketNumber end)1231 void QuicSentPacketManager::OnAckRange(QuicPacketNumber start,
1232 QuicPacketNumber end) {
1233 if (!last_ack_frame_.largest_acked.IsInitialized() ||
1234 end > last_ack_frame_.largest_acked + 1) {
1235 // Largest acked increases.
1236 unacked_packets_.IncreaseLargestAcked(end - 1);
1237 last_ack_frame_.largest_acked = end - 1;
1238 }
1239 // Drop ack ranges which ack packets below least_unacked.
1240 QuicPacketNumber least_unacked = unacked_packets_.GetLeastUnacked();
1241 if (least_unacked.IsInitialized() && end <= least_unacked) {
1242 return;
1243 }
1244 start = std::max(start, least_unacked);
1245 do {
1246 QuicPacketNumber newly_acked_start = start;
1247 if (acked_packets_iter_ != last_ack_frame_.packets.rend()) {
1248 newly_acked_start = std::max(start, acked_packets_iter_->max());
1249 }
1250 for (QuicPacketNumber acked = end - 1; acked >= newly_acked_start;
1251 --acked) {
1252 // Check if end is above the current range. If so add newly acked packets
1253 // in descending order.
1254 packets_acked_.push_back(AckedPacket(acked, 0, QuicTime::Zero()));
1255 if (acked == FirstSendingPacketNumber()) {
1256 break;
1257 }
1258 }
1259 if (acked_packets_iter_ == last_ack_frame_.packets.rend() ||
1260 start > acked_packets_iter_->min()) {
1261 // Finish adding all newly acked packets.
1262 return;
1263 }
1264 end = std::min(end, acked_packets_iter_->min());
1265 ++acked_packets_iter_;
1266 } while (start < end);
1267 }
1268
OnAckTimestamp(QuicPacketNumber packet_number,QuicTime timestamp)1269 void QuicSentPacketManager::OnAckTimestamp(QuicPacketNumber packet_number,
1270 QuicTime timestamp) {
1271 last_ack_frame_.received_packet_times.push_back({packet_number, timestamp});
1272 for (AckedPacket& packet : packets_acked_) {
1273 if (packet.packet_number == packet_number) {
1274 packet.receive_timestamp = timestamp;
1275 return;
1276 }
1277 }
1278 }
1279
IsEcnFeedbackValid(PacketNumberSpace space,const std::optional<QuicEcnCounts> & ecn_counts,QuicPacketCount newly_acked_ect0,QuicPacketCount newly_acked_ect1)1280 bool QuicSentPacketManager::IsEcnFeedbackValid(
1281 PacketNumberSpace space, const std::optional<QuicEcnCounts>& ecn_counts,
1282 QuicPacketCount newly_acked_ect0, QuicPacketCount newly_acked_ect1) {
1283 if (!ecn_counts.has_value()) {
1284 if (newly_acked_ect0 > 0 || newly_acked_ect1 > 0) {
1285 QUIC_DVLOG(1) << ENDPOINT
1286 << "ECN packets acknowledged, no counts reported.";
1287 return false;
1288 }
1289 return true;
1290 }
1291 if (ecn_counts->ect0 < peer_ack_ecn_counts_[space].ect0 ||
1292 ecn_counts->ect1 < peer_ack_ecn_counts_[space].ect1 ||
1293 ecn_counts->ce < peer_ack_ecn_counts_[space].ce) {
1294 QUIC_DVLOG(1) << ENDPOINT << "Reported ECN count declined.";
1295 return false;
1296 }
1297 if (ecn_counts->ect0 > ect0_packets_sent_[space] ||
1298 ecn_counts->ect1 > ect1_packets_sent_[space] ||
1299 (ecn_counts->ect0 + ecn_counts->ect1 + ecn_counts->ce >
1300 ect0_packets_sent_[space] + ect1_packets_sent_[space])) {
1301 QUIC_DVLOG(1) << ENDPOINT << "Reported ECT + CE exceeds packets sent:"
1302 << " reported " << ecn_counts->ToString() << " , ECT(0) sent "
1303 << ect0_packets_sent_[space] << " , ECT(1) sent "
1304 << ect1_packets_sent_[space];
1305 return false;
1306 }
1307 if ((newly_acked_ect0 >
1308 (ecn_counts->ect0 + ecn_counts->ce - peer_ack_ecn_counts_[space].ect0 +
1309 peer_ack_ecn_counts_[space].ce)) ||
1310 (newly_acked_ect1 >
1311 (ecn_counts->ect1 + ecn_counts->ce - peer_ack_ecn_counts_[space].ect1 +
1312 peer_ack_ecn_counts_[space].ce))) {
1313 QUIC_DVLOG(1) << ENDPOINT
1314 << "Peer acked packet but did not report the ECN mark: "
1315 << " New ECN counts: " << ecn_counts->ToString()
1316 << " Old ECN counts: "
1317 << peer_ack_ecn_counts_[space].ToString()
1318 << " Newly acked ECT(0) : " << newly_acked_ect0
1319 << " Newly acked ECT(1) : " << newly_acked_ect1;
1320 return false;
1321 }
1322 return true;
1323 }
1324
OnAckFrameEnd(QuicTime ack_receive_time,QuicPacketNumber ack_packet_number,EncryptionLevel ack_decrypted_level,const std::optional<QuicEcnCounts> & ecn_counts)1325 AckResult QuicSentPacketManager::OnAckFrameEnd(
1326 QuicTime ack_receive_time, QuicPacketNumber ack_packet_number,
1327 EncryptionLevel ack_decrypted_level,
1328 const std::optional<QuicEcnCounts>& ecn_counts) {
1329 QuicByteCount prior_bytes_in_flight = unacked_packets_.bytes_in_flight();
1330 QuicPacketCount newly_acked_ect0 = 0;
1331 QuicPacketCount newly_acked_ect1 = 0;
1332 PacketNumberSpace acked_packet_number_space =
1333 QuicUtils::GetPacketNumberSpace(ack_decrypted_level);
1334 QuicPacketNumber old_largest_acked =
1335 unacked_packets_.GetLargestAckedOfPacketNumberSpace(
1336 acked_packet_number_space);
1337 // Reverse packets_acked_ so that it is in ascending order.
1338 std::reverse(packets_acked_.begin(), packets_acked_.end());
1339 for (AckedPacket& acked_packet : packets_acked_) {
1340 QuicTransmissionInfo* info =
1341 unacked_packets_.GetMutableTransmissionInfo(acked_packet.packet_number);
1342 if (!QuicUtils::IsAckable(info->state)) {
1343 if (info->state == ACKED) {
1344 QUIC_BUG(quic_bug_10750_5)
1345 << "Trying to ack an already acked packet: "
1346 << acked_packet.packet_number
1347 << ", last_ack_frame_: " << last_ack_frame_
1348 << ", least_unacked: " << unacked_packets_.GetLeastUnacked()
1349 << ", packets_acked_: " << quiche::PrintElements(packets_acked_);
1350 } else {
1351 QUIC_PEER_BUG(quic_peer_bug_10750_6)
1352 << "Received " << ack_decrypted_level
1353 << " ack for unackable packet: " << acked_packet.packet_number
1354 << " with state: "
1355 << QuicUtils::SentPacketStateToString(info->state);
1356 if (supports_multiple_packet_number_spaces()) {
1357 if (info->state == NEVER_SENT) {
1358 return UNSENT_PACKETS_ACKED;
1359 }
1360 return UNACKABLE_PACKETS_ACKED;
1361 }
1362 }
1363 continue;
1364 }
1365 QUIC_DVLOG(1) << ENDPOINT << "Got an " << ack_decrypted_level
1366 << " ack for packet " << acked_packet.packet_number
1367 << " , state: "
1368 << QuicUtils::SentPacketStateToString(info->state);
1369 const PacketNumberSpace packet_number_space =
1370 unacked_packets_.GetPacketNumberSpace(info->encryption_level);
1371 if (supports_multiple_packet_number_spaces() &&
1372 QuicUtils::GetPacketNumberSpace(ack_decrypted_level) !=
1373 packet_number_space) {
1374 return PACKETS_ACKED_IN_WRONG_PACKET_NUMBER_SPACE;
1375 }
1376 last_ack_frame_.packets.Add(acked_packet.packet_number);
1377 if (info->encryption_level == ENCRYPTION_HANDSHAKE) {
1378 handshake_packet_acked_ = true;
1379 } else if (info->encryption_level == ENCRYPTION_ZERO_RTT) {
1380 zero_rtt_packet_acked_ = true;
1381 } else if (info->encryption_level == ENCRYPTION_FORWARD_SECURE) {
1382 one_rtt_packet_acked_ = true;
1383 }
1384 largest_packet_peer_knows_is_acked_.UpdateMax(info->largest_acked);
1385 if (supports_multiple_packet_number_spaces()) {
1386 largest_packets_peer_knows_is_acked_[packet_number_space].UpdateMax(
1387 info->largest_acked);
1388 }
1389 // If data is associated with the most recent transmission of this
1390 // packet, then inform the caller.
1391 if (info->in_flight) {
1392 acked_packet.bytes_acked = info->bytes_sent;
1393 } else {
1394 // Unackable packets are skipped earlier.
1395 largest_newly_acked_ = acked_packet.packet_number;
1396 }
1397 switch (info->ecn_codepoint) {
1398 case ECN_NOT_ECT:
1399 break;
1400 case ECN_CE:
1401 // ECN_CE should only happen in tests. Feedback validation doesn't track
1402 // newly acked CEs, and if newly_acked_ect0 and newly_acked_ect1 are
1403 // lower than expected that won't fail validation. So when it's CE don't
1404 // increment anything.
1405 break;
1406 case ECN_ECT0:
1407 ++newly_acked_ect0;
1408 if (info->in_flight) {
1409 network_change_visitor_->OnInFlightEcnPacketAcked();
1410 }
1411 break;
1412 case ECN_ECT1:
1413 ++newly_acked_ect1;
1414 if (info->in_flight) {
1415 network_change_visitor_->OnInFlightEcnPacketAcked();
1416 }
1417 break;
1418 }
1419 unacked_packets_.MaybeUpdateLargestAckedOfPacketNumberSpace(
1420 packet_number_space, acked_packet.packet_number);
1421 MarkPacketHandled(acked_packet.packet_number, info, ack_receive_time,
1422 last_ack_frame_.ack_delay_time,
1423 acked_packet.receive_timestamp);
1424 }
1425 // Validate ECN feedback.
1426 std::optional<QuicEcnCounts> valid_ecn_counts;
1427 if (GetQuicReloadableFlag(quic_send_ect1)) {
1428 QUIC_RELOADABLE_FLAG_COUNT_N(quic_send_ect1, 1, 8);
1429 if (IsEcnFeedbackValid(acked_packet_number_space, ecn_counts,
1430 newly_acked_ect0, newly_acked_ect1)) {
1431 valid_ecn_counts = ecn_counts;
1432 } else if (!old_largest_acked.IsInitialized() ||
1433 old_largest_acked <
1434 unacked_packets_.GetLargestAckedOfPacketNumberSpace(
1435 acked_packet_number_space)) {
1436 // RFC 9000 S13.4.2.1: "An endpoint MUST NOT fail ECN validation as a
1437 // result of processing an ACK frame that does not increase the largest
1438 // acknowledged packet number."
1439 network_change_visitor_->OnInvalidEcnFeedback();
1440 }
1441 }
1442 const bool acked_new_packet = !packets_acked_.empty();
1443 PostProcessNewlyAckedPackets(ack_packet_number, ack_decrypted_level,
1444 last_ack_frame_, ack_receive_time, rtt_updated_,
1445 prior_bytes_in_flight, valid_ecn_counts);
1446 if (valid_ecn_counts.has_value()) {
1447 peer_ack_ecn_counts_[acked_packet_number_space] = *valid_ecn_counts;
1448 }
1449 return acked_new_packet ? PACKETS_NEWLY_ACKED : NO_PACKETS_NEWLY_ACKED;
1450 }
1451
SetDebugDelegate(DebugDelegate * debug_delegate)1452 void QuicSentPacketManager::SetDebugDelegate(DebugDelegate* debug_delegate) {
1453 debug_delegate_ = debug_delegate;
1454 }
1455
OnApplicationLimited()1456 void QuicSentPacketManager::OnApplicationLimited() {
1457 if (using_pacing_) {
1458 pacing_sender_.OnApplicationLimited();
1459 }
1460 send_algorithm_->OnApplicationLimited(unacked_packets_.bytes_in_flight());
1461 if (debug_delegate_ != nullptr) {
1462 debug_delegate_->OnApplicationLimited();
1463 }
1464 }
1465
GetNextReleaseTime() const1466 NextReleaseTimeResult QuicSentPacketManager::GetNextReleaseTime() const {
1467 if (!using_pacing_) {
1468 return {QuicTime::Zero(), false};
1469 }
1470
1471 return pacing_sender_.GetNextReleaseTime();
1472 }
1473
SetInitialRtt(QuicTime::Delta rtt,bool trusted)1474 void QuicSentPacketManager::SetInitialRtt(QuicTime::Delta rtt, bool trusted) {
1475 const QuicTime::Delta min_rtt = QuicTime::Delta::FromMicroseconds(
1476 trusted ? kMinTrustedInitialRoundTripTimeUs
1477 : kMinUntrustedInitialRoundTripTimeUs);
1478 QuicTime::Delta max_rtt =
1479 QuicTime::Delta::FromMicroseconds(kMaxInitialRoundTripTimeUs);
1480 rtt_stats_.set_initial_rtt(std::max(min_rtt, std::min(max_rtt, rtt)));
1481 }
1482
EnableMultiplePacketNumberSpacesSupport()1483 void QuicSentPacketManager::EnableMultiplePacketNumberSpacesSupport() {
1484 EnableIetfPtoAndLossDetection();
1485 unacked_packets_.EnableMultiplePacketNumberSpacesSupport();
1486 }
1487
GetLargestAckedPacket(EncryptionLevel decrypted_packet_level) const1488 QuicPacketNumber QuicSentPacketManager::GetLargestAckedPacket(
1489 EncryptionLevel decrypted_packet_level) const {
1490 QUICHE_DCHECK(supports_multiple_packet_number_spaces());
1491 return unacked_packets_.GetLargestAckedOfPacketNumberSpace(
1492 QuicUtils::GetPacketNumberSpace(decrypted_packet_level));
1493 }
1494
GetLeastPacketAwaitedByPeer(EncryptionLevel encryption_level) const1495 QuicPacketNumber QuicSentPacketManager::GetLeastPacketAwaitedByPeer(
1496 EncryptionLevel encryption_level) const {
1497 QuicPacketNumber largest_acked;
1498 if (supports_multiple_packet_number_spaces()) {
1499 largest_acked = GetLargestAckedPacket(encryption_level);
1500 } else {
1501 largest_acked = GetLargestObserved();
1502 }
1503 if (!largest_acked.IsInitialized()) {
1504 // If no packets have been acked, return the first sent packet to ensure
1505 // we use a large enough packet number length.
1506 return FirstSendingPacketNumber();
1507 }
1508 QuicPacketNumber least_awaited = largest_acked + 1;
1509 QuicPacketNumber least_unacked = GetLeastUnacked();
1510 if (least_unacked.IsInitialized() && least_unacked < least_awaited) {
1511 least_awaited = least_unacked;
1512 }
1513 return least_awaited;
1514 }
1515
GetLargestPacketPeerKnowsIsAcked(EncryptionLevel decrypted_packet_level) const1516 QuicPacketNumber QuicSentPacketManager::GetLargestPacketPeerKnowsIsAcked(
1517 EncryptionLevel decrypted_packet_level) const {
1518 QUICHE_DCHECK(supports_multiple_packet_number_spaces());
1519 return largest_packets_peer_knows_is_acked_[QuicUtils::GetPacketNumberSpace(
1520 decrypted_packet_level)];
1521 }
1522
1523 QuicTime::Delta
GetNConsecutiveRetransmissionTimeoutDelay(int num_timeouts) const1524 QuicSentPacketManager::GetNConsecutiveRetransmissionTimeoutDelay(
1525 int num_timeouts) const {
1526 QuicTime::Delta total_delay = QuicTime::Delta::Zero();
1527 const QuicTime::Delta srtt = rtt_stats_.SmoothedOrInitialRtt();
1528 int num_tlps =
1529 std::min(num_timeouts, static_cast<int>(kDefaultMaxTailLossProbes));
1530 num_timeouts -= num_tlps;
1531 if (num_tlps > 0) {
1532 const QuicTime::Delta tlp_delay = std::max(
1533 2 * srtt,
1534 unacked_packets_.HasMultipleInFlightPackets()
1535 ? QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs)
1536 : (1.5 * srtt +
1537 (QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs) *
1538 0.5)));
1539 total_delay = total_delay + num_tlps * tlp_delay;
1540 }
1541 if (num_timeouts == 0) {
1542 return total_delay;
1543 }
1544
1545 const QuicTime::Delta retransmission_delay =
1546 rtt_stats_.smoothed_rtt().IsZero()
1547 ? QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs)
1548 : std::max(
1549 srtt + 4 * rtt_stats_.mean_deviation(),
1550 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs));
1551 total_delay = total_delay + ((1 << num_timeouts) - 1) * retransmission_delay;
1552 return total_delay;
1553 }
1554
PeerCompletedAddressValidation() const1555 bool QuicSentPacketManager::PeerCompletedAddressValidation() const {
1556 if (unacked_packets_.perspective() == Perspective::IS_SERVER ||
1557 !handshake_mode_disabled_) {
1558 return true;
1559 }
1560
1561 // To avoid handshake deadlock due to anti-amplification limit, client needs
1562 // to set PTO timer until server successfully processed any HANDSHAKE packet.
1563 return handshake_finished_ || handshake_packet_acked_;
1564 }
1565
IsLessThanThreePTOs(QuicTime::Delta timeout) const1566 bool QuicSentPacketManager::IsLessThanThreePTOs(QuicTime::Delta timeout) const {
1567 return timeout < 3 * GetPtoDelay();
1568 }
1569
GetPtoDelay() const1570 QuicTime::Delta QuicSentPacketManager::GetPtoDelay() const {
1571 return GetProbeTimeoutDelay(APPLICATION_DATA);
1572 }
1573
OnAckFrequencyFrameSent(const QuicAckFrequencyFrame & ack_frequency_frame)1574 void QuicSentPacketManager::OnAckFrequencyFrameSent(
1575 const QuicAckFrequencyFrame& ack_frequency_frame) {
1576 in_use_sent_ack_delays_.emplace_back(ack_frequency_frame.max_ack_delay,
1577 ack_frequency_frame.sequence_number);
1578 if (ack_frequency_frame.max_ack_delay > peer_max_ack_delay_) {
1579 peer_max_ack_delay_ = ack_frequency_frame.max_ack_delay;
1580 }
1581 }
1582
OnAckFrequencyFrameAcked(const QuicAckFrequencyFrame & ack_frequency_frame)1583 void QuicSentPacketManager::OnAckFrequencyFrameAcked(
1584 const QuicAckFrequencyFrame& ack_frequency_frame) {
1585 int stale_entry_count = 0;
1586 for (auto it = in_use_sent_ack_delays_.cbegin();
1587 it != in_use_sent_ack_delays_.cend(); ++it) {
1588 if (it->second < ack_frequency_frame.sequence_number) {
1589 ++stale_entry_count;
1590 } else {
1591 break;
1592 }
1593 }
1594 if (stale_entry_count > 0) {
1595 in_use_sent_ack_delays_.pop_front_n(stale_entry_count);
1596 }
1597 if (in_use_sent_ack_delays_.empty()) {
1598 QUIC_BUG(quic_bug_10750_7) << "in_use_sent_ack_delays_ is empty.";
1599 return;
1600 }
1601 peer_max_ack_delay_ = std::max_element(in_use_sent_ack_delays_.cbegin(),
1602 in_use_sent_ack_delays_.cend())
1603 ->first;
1604 }
1605
1606 #undef ENDPOINT // undef for jumbo builds
1607 } // namespace quic
1608