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