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.
5 #include "net/quic/quic_sent_packet_manager.h"
9 #include "base/logging.h"
10 #include "base/stl_util.h"
11 #include "net/quic/congestion_control/pacing_sender.h"
12 #include "net/quic/crypto/crypto_protocol.h"
13 #include "net/quic/proto/cached_network_parameters.pb.h"
14 #include "net/quic/quic_ack_notifier_manager.h"
15 #include "net/quic/quic_connection_stats.h"
16 #include "net/quic/quic_flags.h"
17 #include "net/quic/quic_utils_chromium.h"
24 // The length of the recent min rtt window in seconds. Windowing is disabled for
25 // values less than or equal to 0.
26 int32 FLAGS_quic_recent_min_rtt_window_s
= 60;
29 static const int64 kDefaultRetransmissionTimeMs
= 500;
30 // TCP RFC calls for 1 second RTO however Linux differs from this default and
31 // define the minimum RTO to 200ms, we will use the same until we have data to
32 // support a higher or lower value.
33 static const int64 kMinRetransmissionTimeMs
= 200;
34 static const int64 kMaxRetransmissionTimeMs
= 60000;
35 // Maximum number of exponential backoffs used for RTO timeouts.
36 static const size_t kMaxRetransmissions
= 10;
37 // Maximum number of packets retransmitted upon an RTO.
38 static const size_t kMaxRetransmissionsOnTimeout
= 2;
40 // Ensure the handshake timer isnt't faster than 10ms.
41 // This limits the tenth retransmitted packet to 10s after the initial CHLO.
42 static const int64 kMinHandshakeTimeoutMs
= 10;
44 // Sends up to two tail loss probes before firing an RTO,
45 // per draft RFC draft-dukkipati-tcpm-tcp-loss-probe.
46 static const size_t kDefaultMaxTailLossProbes
= 2;
47 static const int64 kMinTailLossProbeTimeoutMs
= 10;
49 // Number of unpaced packets to send after quiescence.
50 static const size_t kInitialUnpacedBurst
= 10;
52 bool HasCryptoHandshake(const TransmissionInfo
& transmission_info
) {
53 if (transmission_info
.retransmittable_frames
== nullptr) {
56 return transmission_info
.retransmittable_frames
->HasCryptoHandshake() ==
63 (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ")
65 QuicSentPacketManager::QuicSentPacketManager(
66 Perspective perspective
,
67 const QuicClock
* clock
,
68 QuicConnectionStats
* stats
,
69 CongestionControlType congestion_control_type
,
70 LossDetectionType loss_type
,
72 : unacked_packets_(&ack_notifier_manager_
),
73 perspective_(perspective
),
76 debug_delegate_(nullptr),
77 network_change_visitor_(nullptr),
78 initial_congestion_window_(is_secure
? kInitialCongestionWindowSecure
79 : kInitialCongestionWindowInsecure
),
81 SendAlgorithmInterface::Create(clock
,
83 congestion_control_type
,
85 initial_congestion_window_
)),
86 loss_algorithm_(LossDetectionInterface::Create(loss_type
)),
87 n_connection_simulation_(false),
88 receive_buffer_bytes_(kDefaultSocketReceiveBuffer
),
89 least_packet_awaited_by_peer_(1),
90 first_rto_transmission_(0),
91 consecutive_rto_count_(0),
92 consecutive_tlp_count_(0),
93 consecutive_crypto_retransmission_count_(0),
94 pending_timer_transmission_count_(0),
95 max_tail_loss_probes_(kDefaultMaxTailLossProbes
),
98 handshake_confirmed_(false) {
101 QuicSentPacketManager::~QuicSentPacketManager() {
104 void QuicSentPacketManager::SetFromConfig(const QuicConfig
& config
) {
105 if (config
.HasReceivedInitialRoundTripTimeUs() &&
106 config
.ReceivedInitialRoundTripTimeUs() > 0) {
107 rtt_stats_
.set_initial_rtt_us(
108 max(kMinInitialRoundTripTimeUs
,
109 min(kMaxInitialRoundTripTimeUs
,
110 config
.ReceivedInitialRoundTripTimeUs())));
111 } else if (config
.HasInitialRoundTripTimeUsToSend() &&
112 config
.GetInitialRoundTripTimeUsToSend() > 0) {
113 rtt_stats_
.set_initial_rtt_us(
114 max(kMinInitialRoundTripTimeUs
,
115 min(kMaxInitialRoundTripTimeUs
,
116 config
.GetInitialRoundTripTimeUsToSend())));
118 // Initial RTT may have changed.
119 if (network_change_visitor_
!= nullptr) {
120 network_change_visitor_
->OnRttChange();
122 // TODO(ianswett): BBR is currently a server only feature.
123 if (FLAGS_quic_allow_bbr
&&
124 config
.HasReceivedConnectionOptions() &&
125 ContainsQuicTag(config
.ReceivedConnectionOptions(), kTBBR
)) {
126 if (FLAGS_quic_recent_min_rtt_window_s
> 0) {
127 rtt_stats_
.set_recent_min_rtt_window(
128 QuicTime::Delta::FromSeconds(FLAGS_quic_recent_min_rtt_window_s
));
130 send_algorithm_
.reset(SendAlgorithmInterface::Create(
131 clock_
, &rtt_stats_
, kBBR
, stats_
, initial_congestion_window_
));
133 if (config
.HasReceivedConnectionOptions() &&
134 ContainsQuicTag(config
.ReceivedConnectionOptions(), kRENO
)) {
135 if (ContainsQuicTag(config
.ReceivedConnectionOptions(), kBYTE
)) {
136 send_algorithm_
.reset(SendAlgorithmInterface::Create(
137 clock_
, &rtt_stats_
, kRenoBytes
, stats_
, initial_congestion_window_
));
139 send_algorithm_
.reset(SendAlgorithmInterface::Create(
140 clock_
, &rtt_stats_
, kReno
, stats_
, initial_congestion_window_
));
142 } else if (config
.HasReceivedConnectionOptions() &&
143 ContainsQuicTag(config
.ReceivedConnectionOptions(), kBYTE
)) {
144 send_algorithm_
.reset(SendAlgorithmInterface::Create(
145 clock_
, &rtt_stats_
, kCubicBytes
, stats_
, initial_congestion_window_
));
149 if (config
.HasClientSentConnectionOption(k1CON
, perspective_
)) {
150 send_algorithm_
->SetNumEmulatedConnections(1);
152 if (config
.HasClientSentConnectionOption(kNCON
, perspective_
)) {
153 n_connection_simulation_
= true;
155 if (config
.HasClientSentConnectionOption(kNTLP
, perspective_
)) {
156 max_tail_loss_probes_
= 0;
158 if (config
.HasClientSentConnectionOption(kNRTO
, perspective_
)) {
161 if (config
.HasReceivedConnectionOptions() &&
162 ContainsQuicTag(config
.ReceivedConnectionOptions(), kTIME
)) {
163 loss_algorithm_
.reset(LossDetectionInterface::Create(kTime
));
165 if (config
.HasReceivedSocketReceiveBuffer()) {
166 receive_buffer_bytes_
=
167 max(kMinSocketReceiveBuffer
,
168 static_cast<QuicByteCount
>(config
.ReceivedSocketReceiveBuffer()));
169 QuicByteCount max_cwnd_bytes
= static_cast<QuicByteCount
>(
170 receive_buffer_bytes_
* (FLAGS_quic_use_conservative_receive_buffer
171 ? kConservativeReceiveBufferFraction
172 : kUsableRecieveBufferFraction
));
173 if (FLAGS_quic_limit_max_cwnd
) {
175 min(max_cwnd_bytes
, kMaxCongestionWindow
* kDefaultTCPMSS
);
177 send_algorithm_
->SetMaxCongestionWindow(max_cwnd_bytes
);
179 send_algorithm_
->SetFromConfig(config
, perspective_
);
181 if (network_change_visitor_
!= nullptr) {
182 network_change_visitor_
->OnCongestionWindowChange();
186 void QuicSentPacketManager::ResumeConnectionState(
187 const CachedNetworkParameters
& cached_network_params
,
188 bool max_bandwidth_resumption
) {
189 if (cached_network_params
.has_min_rtt_ms()) {
190 uint32 initial_rtt_us
=
191 kNumMicrosPerMilli
* cached_network_params
.min_rtt_ms();
192 rtt_stats_
.set_initial_rtt_us(
193 max(kMinInitialRoundTripTimeUs
,
194 min(kMaxInitialRoundTripTimeUs
, initial_rtt_us
)));
196 send_algorithm_
->ResumeConnectionState(cached_network_params
,
197 max_bandwidth_resumption
);
200 void QuicSentPacketManager::SetNumOpenStreams(size_t num_streams
) {
201 if (n_connection_simulation_
) {
202 // Ensure the number of connections is between 1 and 5.
203 send_algorithm_
->SetNumEmulatedConnections(
204 min
<size_t>(5, max
<size_t>(1, num_streams
)));
208 void QuicSentPacketManager::OnIncomingAck(const QuicAckFrame
& ack_frame
,
209 QuicTime ack_receive_time
) {
210 QuicByteCount bytes_in_flight
= unacked_packets_
.bytes_in_flight();
212 UpdatePacketInformationReceivedByPeer(ack_frame
);
213 bool rtt_updated
= MaybeUpdateRTT(ack_frame
, ack_receive_time
);
214 DCHECK_GE(ack_frame
.largest_observed
, unacked_packets_
.largest_observed());
215 unacked_packets_
.IncreaseLargestObserved(ack_frame
.largest_observed
);
217 HandleAckForSentPackets(ack_frame
);
218 InvokeLossDetection(ack_receive_time
);
219 // Ignore losses in RTO mode.
220 if (consecutive_rto_count_
> 0 && !use_new_rto_
) {
221 packets_lost_
.clear();
223 MaybeInvokeCongestionEvent(rtt_updated
, bytes_in_flight
);
224 unacked_packets_
.RemoveObsoletePackets();
226 sustained_bandwidth_recorder_
.RecordEstimate(
227 send_algorithm_
->InRecovery(),
228 send_algorithm_
->InSlowStart(),
229 send_algorithm_
->BandwidthEstimate(),
232 rtt_stats_
.smoothed_rtt());
234 // If we have received a truncated ack, then we need to clear out some
235 // previous transmissions to allow the peer to actually ACK new packets.
236 if (ack_frame
.is_truncated
) {
237 unacked_packets_
.ClearAllPreviousRetransmissions();
240 // Anytime we are making forward progress and have a new RTT estimate, reset
241 // the backoff counters.
243 if (consecutive_rto_count_
> 0) {
244 // If the ack acknowledges data sent prior to the RTO,
245 // the RTO was spurious.
246 if (ack_frame
.largest_observed
< first_rto_transmission_
) {
247 // Replace SRTT with latest_rtt and increase the variance to prevent
248 // a spurious RTO from happening again.
249 rtt_stats_
.ExpireSmoothedMetrics();
252 send_algorithm_
->OnRetransmissionTimeout(true);
256 // Reset all retransmit counters any time a new packet is acked.
257 consecutive_rto_count_
= 0;
258 consecutive_tlp_count_
= 0;
259 consecutive_crypto_retransmission_count_
= 0;
262 if (debug_delegate_
!= nullptr) {
263 debug_delegate_
->OnIncomingAck(ack_frame
, ack_receive_time
,
264 unacked_packets_
.largest_observed(),
265 rtt_updated
, GetLeastUnacked());
269 void QuicSentPacketManager::UpdatePacketInformationReceivedByPeer(
270 const QuicAckFrame
& ack_frame
) {
271 if (ack_frame
.missing_packets
.empty()) {
272 least_packet_awaited_by_peer_
= ack_frame
.largest_observed
+ 1;
274 least_packet_awaited_by_peer_
= *(ack_frame
.missing_packets
.begin());
278 void QuicSentPacketManager::MaybeInvokeCongestionEvent(
279 bool rtt_updated
, QuicByteCount bytes_in_flight
) {
280 if (!rtt_updated
&& packets_acked_
.empty() && packets_lost_
.empty()) {
283 send_algorithm_
->OnCongestionEvent(rtt_updated
, bytes_in_flight
,
284 packets_acked_
, packets_lost_
);
285 packets_acked_
.clear();
286 packets_lost_
.clear();
287 if (network_change_visitor_
!= nullptr) {
288 network_change_visitor_
->OnCongestionWindowChange();
292 void QuicSentPacketManager::HandleAckForSentPackets(
293 const QuicAckFrame
& ack_frame
) {
294 // Go through the packets we have not received an ack for and see if this
295 // incoming_ack shows they've been seen by the peer.
296 QuicTime::Delta delta_largest_observed
=
297 ack_frame
.delta_time_largest_observed
;
298 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
299 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
300 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
301 if (sequence_number
> ack_frame
.largest_observed
) {
302 // These packets are still in flight.
306 if (ContainsKey(ack_frame
.missing_packets
, sequence_number
)) {
307 // Don't continue to increase the nack count for packets not in flight.
308 if (!it
->in_flight
) {
311 // Consider it multiple nacks when there is a gap between the missing
312 // packet and the largest observed, since the purpose of a nack
313 // threshold is to tolerate re-ordering. This handles both StretchAcks
315 // The nack count only increases when the largest observed increases.
316 QuicPacketCount min_nacks
= ack_frame
.largest_observed
- sequence_number
;
317 // Truncated acks can nack the largest observed, so use a min of 1.
318 if (min_nacks
== 0) {
321 unacked_packets_
.NackPacket(sequence_number
, min_nacks
);
324 // Packet was acked, so remove it from our unacked packet list.
325 DVLOG(1) << ENDPOINT
<< "Got an ack for packet " << sequence_number
;
326 // If data is associated with the most recent transmission of this
327 // packet, then inform the caller.
329 packets_acked_
.push_back(std::make_pair(sequence_number
, *it
));
331 MarkPacketHandled(sequence_number
, *it
, delta_largest_observed
);
334 // Discard any retransmittable frames associated with revived packets.
335 for (SequenceNumberSet::const_iterator revived_it
=
336 ack_frame
.revived_packets
.begin();
337 revived_it
!= ack_frame
.revived_packets
.end(); ++revived_it
) {
338 MarkPacketRevived(*revived_it
, delta_largest_observed
);
342 bool QuicSentPacketManager::HasRetransmittableFrames(
343 QuicPacketSequenceNumber sequence_number
) const {
344 return unacked_packets_
.HasRetransmittableFrames(sequence_number
);
347 void QuicSentPacketManager::RetransmitUnackedPackets(
348 TransmissionType retransmission_type
) {
349 DCHECK(retransmission_type
== ALL_UNACKED_RETRANSMISSION
||
350 retransmission_type
== ALL_INITIAL_RETRANSMISSION
);
351 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
352 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
353 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
354 const RetransmittableFrames
* frames
= it
->retransmittable_frames
;
355 if (frames
!= nullptr &&
356 (retransmission_type
== ALL_UNACKED_RETRANSMISSION
||
357 frames
->encryption_level() == ENCRYPTION_INITIAL
)) {
358 MarkForRetransmission(sequence_number
, retransmission_type
);
359 } else if (it
->is_fec_packet
) {
360 // Remove FEC packets from the packet map, since we can't retransmit them.
361 unacked_packets_
.RemoveFromInFlight(sequence_number
);
366 void QuicSentPacketManager::NeuterUnencryptedPackets() {
367 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
368 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
369 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
370 const RetransmittableFrames
* frames
= it
->retransmittable_frames
;
371 if (frames
!= nullptr && frames
->encryption_level() == ENCRYPTION_NONE
) {
372 // Once you're forward secure, no unencrypted packets will be sent, crypto
373 // or otherwise. Unencrypted packets are neutered and abandoned, to ensure
374 // they are not retransmitted or considered lost from a congestion control
376 pending_retransmissions_
.erase(sequence_number
);
377 unacked_packets_
.RemoveFromInFlight(sequence_number
);
378 unacked_packets_
.RemoveRetransmittability(sequence_number
);
383 void QuicSentPacketManager::MarkForRetransmission(
384 QuicPacketSequenceNumber sequence_number
,
385 TransmissionType transmission_type
) {
386 const TransmissionInfo
& transmission_info
=
387 unacked_packets_
.GetTransmissionInfo(sequence_number
);
388 LOG_IF(DFATAL
, transmission_info
.retransmittable_frames
== nullptr);
389 // Both TLP and the new RTO leave the packets in flight and let the loss
390 // detection decide if packets are lost.
391 if (transmission_type
!= TLP_RETRANSMISSION
&&
392 transmission_type
!= RTO_RETRANSMISSION
) {
393 unacked_packets_
.RemoveFromInFlight(sequence_number
);
395 // TODO(ianswett): Currently the RTO can fire while there are pending NACK
396 // retransmissions for the same data, which is not ideal.
397 if (ContainsKey(pending_retransmissions_
, sequence_number
)) {
401 pending_retransmissions_
[sequence_number
] = transmission_type
;
404 void QuicSentPacketManager::RecordSpuriousRetransmissions(
405 const SequenceNumberList
& all_transmissions
,
406 QuicPacketSequenceNumber acked_sequence_number
) {
407 for (SequenceNumberList::const_reverse_iterator it
=
408 all_transmissions
.rbegin();
409 it
!= all_transmissions
.rend() && *it
> acked_sequence_number
; ++it
) {
410 const TransmissionInfo
& retransmit_info
=
411 unacked_packets_
.GetTransmissionInfo(*it
);
413 stats_
->bytes_spuriously_retransmitted
+= retransmit_info
.bytes_sent
;
414 ++stats_
->packets_spuriously_retransmitted
;
415 if (debug_delegate_
!= nullptr) {
416 debug_delegate_
->OnSpuriousPacketRetransmission(
417 retransmit_info
.transmission_type
, retransmit_info
.bytes_sent
);
422 bool QuicSentPacketManager::HasPendingRetransmissions() const {
423 return !pending_retransmissions_
.empty();
426 QuicSentPacketManager::PendingRetransmission
427 QuicSentPacketManager::NextPendingRetransmission() {
428 LOG_IF(DFATAL
, pending_retransmissions_
.empty())
429 << "Unexpected call to PendingRetransmissions() with empty pending "
430 << "retransmission list. Corrupted memory usage imminent.";
431 QuicPacketSequenceNumber sequence_number
=
432 pending_retransmissions_
.begin()->first
;
433 TransmissionType transmission_type
= pending_retransmissions_
.begin()->second
;
434 if (unacked_packets_
.HasPendingCryptoPackets()) {
435 // Ensure crypto packets are retransmitted before other packets.
436 for (const auto& pair
: pending_retransmissions_
) {
437 if (HasCryptoHandshake(
438 unacked_packets_
.GetTransmissionInfo(pair
.first
))) {
439 sequence_number
= pair
.first
;
440 transmission_type
= pair
.second
;
445 DCHECK(unacked_packets_
.IsUnacked(sequence_number
)) << sequence_number
;
446 const TransmissionInfo
& transmission_info
=
447 unacked_packets_
.GetTransmissionInfo(sequence_number
);
448 DCHECK(transmission_info
.retransmittable_frames
);
450 return PendingRetransmission(sequence_number
,
452 *transmission_info
.retransmittable_frames
,
453 transmission_info
.sequence_number_length
);
456 void QuicSentPacketManager::MarkPacketRevived(
457 QuicPacketSequenceNumber sequence_number
,
458 QuicTime::Delta delta_largest_observed
) {
459 if (!unacked_packets_
.IsUnacked(sequence_number
)) {
463 const TransmissionInfo
& transmission_info
=
464 unacked_packets_
.GetTransmissionInfo(sequence_number
);
465 QuicPacketSequenceNumber newest_transmission
=
466 transmission_info
.all_transmissions
== nullptr
468 : *transmission_info
.all_transmissions
->rbegin();
469 // This packet has been revived at the receiver. If we were going to
470 // retransmit it, do not retransmit it anymore.
471 pending_retransmissions_
.erase(newest_transmission
);
473 // The AckNotifierManager needs to be notified for revived packets,
474 // since it indicates the packet arrived from the appliction's perspective.
475 ack_notifier_manager_
.OnPacketAcked(newest_transmission
,
476 delta_largest_observed
);
478 unacked_packets_
.RemoveRetransmittability(sequence_number
);
481 void QuicSentPacketManager::MarkPacketHandled(
482 QuicPacketSequenceNumber sequence_number
,
483 const TransmissionInfo
& info
,
484 QuicTime::Delta delta_largest_observed
) {
485 QuicPacketSequenceNumber newest_transmission
=
486 info
.all_transmissions
== nullptr ?
487 sequence_number
: *info
.all_transmissions
->rbegin();
488 // Remove the most recent packet, if it is pending retransmission.
489 pending_retransmissions_
.erase(newest_transmission
);
491 // The AckNotifierManager needs to be notified about the most recent
492 // transmission, since that's the one only one it tracks.
493 ack_notifier_manager_
.OnPacketAcked(newest_transmission
,
494 delta_largest_observed
);
495 if (newest_transmission
!= sequence_number
) {
496 RecordSpuriousRetransmissions(*info
.all_transmissions
, sequence_number
);
497 // Remove the most recent packet from flight if it's a crypto handshake
498 // packet, since they won't be acked now that one has been processed.
499 // Other crypto handshake packets won't be in flight, only the newest
500 // transmission of a crypto packet is in flight at once.
501 // TODO(ianswett): Instead of handling all crypto packets special,
502 // only handle nullptr encrypted packets in a special way.
503 if (HasCryptoHandshake(
504 unacked_packets_
.GetTransmissionInfo(newest_transmission
))) {
505 unacked_packets_
.RemoveFromInFlight(newest_transmission
);
509 unacked_packets_
.RemoveFromInFlight(sequence_number
);
510 unacked_packets_
.RemoveRetransmittability(sequence_number
);
513 bool QuicSentPacketManager::IsUnacked(
514 QuicPacketSequenceNumber sequence_number
) const {
515 return unacked_packets_
.IsUnacked(sequence_number
);
518 bool QuicSentPacketManager::HasUnackedPackets() const {
519 return unacked_packets_
.HasUnackedPackets();
522 QuicPacketSequenceNumber
523 QuicSentPacketManager::GetLeastUnacked() const {
524 return unacked_packets_
.GetLeastUnacked();
527 bool QuicSentPacketManager::OnPacketSent(
528 SerializedPacket
* serialized_packet
,
529 QuicPacketSequenceNumber original_sequence_number
,
532 TransmissionType transmission_type
,
533 HasRetransmittableData has_retransmittable_data
) {
534 QuicPacketSequenceNumber sequence_number
= serialized_packet
->sequence_number
;
535 DCHECK_LT(0u, sequence_number
);
536 DCHECK(!unacked_packets_
.IsUnacked(sequence_number
));
537 LOG_IF(DFATAL
, bytes
== 0) << "Cannot send empty packets.";
539 if (original_sequence_number
!= 0) {
540 PendingRetransmissionMap::iterator it
=
541 pending_retransmissions_
.find(original_sequence_number
);
542 if (it
!= pending_retransmissions_
.end()) {
543 pending_retransmissions_
.erase(it
);
545 DLOG(DFATAL
) << "Expected sequence number to be in "
546 << "pending_retransmissions_. sequence_number: "
547 << original_sequence_number
;
549 // Inform the ack notifier of retransmissions so it can calculate the
551 ack_notifier_manager_
.OnPacketRetransmitted(original_sequence_number
,
552 sequence_number
, bytes
);
555 if (pending_timer_transmission_count_
> 0) {
556 --pending_timer_transmission_count_
;
559 // Only track packets as in flight that the send algorithm wants us to track.
560 // Since FEC packets should also be counted towards the congestion window,
561 // consider them as retransmittable for the purposes of congestion control.
562 HasRetransmittableData has_congestion_controlled_data
=
563 serialized_packet
->is_fec_packet
? HAS_RETRANSMITTABLE_DATA
564 : has_retransmittable_data
;
565 const bool in_flight
=
566 send_algorithm_
->OnPacketSent(sent_time
,
567 unacked_packets_
.bytes_in_flight(),
570 has_congestion_controlled_data
);
572 unacked_packets_
.AddSentPacket(*serialized_packet
,
573 original_sequence_number
,
579 // Take ownership of the retransmittable frames before exiting.
580 serialized_packet
->retransmittable_frames
= nullptr;
581 // Reset the retransmission timer anytime a pending packet is sent.
585 void QuicSentPacketManager::OnRetransmissionTimeout() {
586 DCHECK(unacked_packets_
.HasInFlightPackets());
587 DCHECK_EQ(0u, pending_timer_transmission_count_
);
588 // Handshake retransmission, timer based loss detection, TLP, and RTO are
589 // implemented with a single alarm. The handshake alarm is set when the
590 // handshake has not completed, the loss alarm is set when the loss detection
591 // algorithm says to, and the TLP and RTO alarms are set after that.
592 // The TLP alarm is always set to run for under an RTO.
593 switch (GetRetransmissionMode()) {
595 ++stats_
->crypto_retransmit_count
;
596 RetransmitCryptoPackets();
599 ++stats_
->loss_timeout_count
;
600 QuicByteCount bytes_in_flight
= unacked_packets_
.bytes_in_flight();
601 InvokeLossDetection(clock_
->Now());
602 MaybeInvokeCongestionEvent(false, bytes_in_flight
);
606 // If no tail loss probe can be sent, because there are no retransmittable
607 // packets, execute a conventional RTO to abandon old packets.
609 ++consecutive_tlp_count_
;
610 pending_timer_transmission_count_
= 1;
611 // TLPs prefer sending new data instead of retransmitting data, so
612 // give the connection a chance to write before completing the TLP.
616 RetransmitRtoPackets();
621 void QuicSentPacketManager::RetransmitCryptoPackets() {
622 DCHECK_EQ(HANDSHAKE_MODE
, GetRetransmissionMode());
623 ++consecutive_crypto_retransmission_count_
;
624 bool packet_retransmitted
= false;
625 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
626 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
627 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
628 // Only retransmit frames which are in flight, and therefore have been sent.
629 if (!it
->in_flight
|| it
->retransmittable_frames
== nullptr ||
630 it
->retransmittable_frames
->HasCryptoHandshake() != IS_HANDSHAKE
) {
633 packet_retransmitted
= true;
634 MarkForRetransmission(sequence_number
, HANDSHAKE_RETRANSMISSION
);
635 ++pending_timer_transmission_count_
;
637 DCHECK(packet_retransmitted
) << "No crypto packets found to retransmit.";
640 bool QuicSentPacketManager::MaybeRetransmitTailLossProbe() {
641 if (pending_timer_transmission_count_
== 0) {
644 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
645 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
646 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
647 // Only retransmit frames which are in flight, and therefore have been sent.
648 if (!it
->in_flight
|| it
->retransmittable_frames
== nullptr) {
651 if (!handshake_confirmed_
) {
652 DCHECK_NE(IS_HANDSHAKE
, it
->retransmittable_frames
->HasCryptoHandshake());
654 MarkForRetransmission(sequence_number
, TLP_RETRANSMISSION
);
658 << "No retransmittable packets, so RetransmitOldestPacket failed.";
662 void QuicSentPacketManager::RetransmitRtoPackets() {
663 LOG_IF(DFATAL
, pending_timer_transmission_count_
> 0)
664 << "Retransmissions already queued:" << pending_timer_transmission_count_
;
665 // Mark two packets for retransmission.
666 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
667 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
668 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
669 if (it
->retransmittable_frames
!= nullptr &&
670 pending_timer_transmission_count_
< kMaxRetransmissionsOnTimeout
) {
671 MarkForRetransmission(sequence_number
, RTO_RETRANSMISSION
);
672 ++pending_timer_transmission_count_
;
674 // Abandon non-retransmittable data that's in flight to ensure it doesn't
675 // fill up the congestion window.
676 if (it
->retransmittable_frames
== nullptr && it
->in_flight
&&
677 it
->all_transmissions
== nullptr) {
678 unacked_packets_
.RemoveFromInFlight(sequence_number
);
681 if (pending_timer_transmission_count_
> 0) {
682 if (consecutive_rto_count_
== 0) {
683 first_rto_transmission_
= unacked_packets_
.largest_sent_packet() + 1;
685 ++consecutive_rto_count_
;
689 QuicSentPacketManager::RetransmissionTimeoutMode
690 QuicSentPacketManager::GetRetransmissionMode() const {
691 DCHECK(unacked_packets_
.HasInFlightPackets());
692 if (!handshake_confirmed_
&& unacked_packets_
.HasPendingCryptoPackets()) {
693 return HANDSHAKE_MODE
;
695 if (loss_algorithm_
->GetLossTimeout() != QuicTime::Zero()) {
698 if (consecutive_tlp_count_
< max_tail_loss_probes_
) {
699 if (unacked_packets_
.HasUnackedRetransmittableFrames()) {
706 void QuicSentPacketManager::InvokeLossDetection(QuicTime time
) {
707 SequenceNumberSet lost_packets
=
708 loss_algorithm_
->DetectLostPackets(unacked_packets_
,
710 unacked_packets_
.largest_observed(),
712 for (SequenceNumberSet::const_iterator it
= lost_packets
.begin();
713 it
!= lost_packets
.end(); ++it
) {
714 QuicPacketSequenceNumber sequence_number
= *it
;
715 const TransmissionInfo
& transmission_info
=
716 unacked_packets_
.GetTransmissionInfo(sequence_number
);
717 // TODO(ianswett): If it's expected the FEC packet may repair the loss, it
718 // should be recorded as a loss to the send algorithm, but not retransmitted
719 // until it's known whether the FEC packet arrived.
720 ++stats_
->packets_lost
;
721 packets_lost_
.push_back(std::make_pair(sequence_number
, transmission_info
));
722 DVLOG(1) << ENDPOINT
<< "Lost packet " << sequence_number
;
724 if (transmission_info
.retransmittable_frames
!= nullptr) {
725 MarkForRetransmission(sequence_number
, LOSS_RETRANSMISSION
);
727 // Since we will not retransmit this, we need to remove it from
728 // unacked_packets_. This is either the current transmission of
729 // a packet whose previous transmission has been acked, a packet that has
730 // been TLP retransmitted, or an FEC packet.
731 unacked_packets_
.RemoveFromInFlight(sequence_number
);
736 bool QuicSentPacketManager::MaybeUpdateRTT(
737 const QuicAckFrame
& ack_frame
,
738 const QuicTime
& ack_receive_time
) {
739 // We rely on delta_time_largest_observed to compute an RTT estimate, so we
740 // only update rtt when the largest observed gets acked.
741 // NOTE: If ack is a truncated ack, then the largest observed is in fact
742 // unacked, and may cause an RTT sample to be taken.
743 if (!unacked_packets_
.IsUnacked(ack_frame
.largest_observed
)) {
746 // We calculate the RTT based on the highest ACKed sequence number, the lower
747 // sequence numbers will include the ACK aggregation delay.
748 const TransmissionInfo
& transmission_info
=
749 unacked_packets_
.GetTransmissionInfo(ack_frame
.largest_observed
);
750 // Ensure the packet has a valid sent time.
751 if (transmission_info
.sent_time
== QuicTime::Zero()) {
752 LOG(DFATAL
) << "Acked packet has zero sent time, largest_observed:"
753 << ack_frame
.largest_observed
;
757 QuicTime::Delta send_delta
=
758 ack_receive_time
.Subtract(transmission_info
.sent_time
);
759 rtt_stats_
.UpdateRtt(
760 send_delta
, ack_frame
.delta_time_largest_observed
, ack_receive_time
);
762 if (network_change_visitor_
!= nullptr) {
763 network_change_visitor_
->OnRttChange();
769 QuicTime::Delta
QuicSentPacketManager::TimeUntilSend(
771 HasRetransmittableData retransmittable
) {
772 // The TLP logic is entirely contained within QuicSentPacketManager, so the
773 // send algorithm does not need to be consulted.
774 if (pending_timer_transmission_count_
> 0) {
775 return QuicTime::Delta::Zero();
777 return send_algorithm_
->TimeUntilSend(
778 now
, unacked_packets_
.bytes_in_flight(), retransmittable
);
781 // Uses a 25ms delayed ack timer. Also helps with better signaling
782 // in low-bandwidth (< ~384 kbps), where an ack is sent per packet.
783 // Ensures that the Delayed Ack timer is always set to a value lesser
784 // than the retransmission timer's minimum value (MinRTO). We want the
785 // delayed ack to get back to the QUIC peer before the sender's
786 // retransmission timer triggers. Since we do not know the
787 // reverse-path one-way delay, we assume equal delays for forward and
788 // reverse paths, and ensure that the timer is set to less than half
790 // There may be a value in making this delay adaptive with the help of
791 // the sender and a signaling mechanism -- if the sender uses a
792 // different MinRTO, we may get spurious retransmissions. May not have
793 // any benefits, but if the delayed ack becomes a significant source
794 // of (likely, tail) latency, then consider such a mechanism.
795 const QuicTime::Delta
QuicSentPacketManager::DelayedAckTime() const {
796 return QuicTime::Delta::FromMilliseconds(min(kMaxDelayedAckTimeMs
,
797 kMinRetransmissionTimeMs
/ 2));
800 const QuicTime
QuicSentPacketManager::GetRetransmissionTime() const {
801 // Don't set the timer if there are no packets in flight or we've already
802 // queued a tlp transmission and it hasn't been sent yet.
803 if (!unacked_packets_
.HasInFlightPackets() ||
804 pending_timer_transmission_count_
> 0) {
805 return QuicTime::Zero();
807 switch (GetRetransmissionMode()) {
809 return clock_
->ApproximateNow().Add(GetCryptoRetransmissionDelay());
811 return loss_algorithm_
->GetLossTimeout();
813 // TODO(ianswett): When CWND is available, it would be preferable to
814 // set the timer based on the earliest retransmittable packet.
815 // Base the updated timer on the send time of the last packet.
816 const QuicTime sent_time
= unacked_packets_
.GetLastPacketSentTime();
817 const QuicTime tlp_time
= sent_time
.Add(GetTailLossProbeDelay());
818 // Ensure the TLP timer never gets set to a time in the past.
819 return QuicTime::Max(clock_
->ApproximateNow(), tlp_time
);
822 // The RTO is based on the first outstanding packet.
823 const QuicTime sent_time
= unacked_packets_
.GetLastPacketSentTime();
824 QuicTime rto_time
= sent_time
.Add(GetRetransmissionDelay());
825 // Wait for TLP packets to be acked before an RTO fires.
827 unacked_packets_
.GetLastPacketSentTime().Add(GetTailLossProbeDelay());
828 return QuicTime::Max(tlp_time
, rto_time
);
832 return QuicTime::Zero();
835 const QuicTime::Delta
QuicSentPacketManager::GetCryptoRetransmissionDelay()
837 // This is equivalent to the TailLossProbeDelay, but slightly more aggressive
838 // because crypto handshake messages don't incur a delayed ack time.
839 QuicTime::Delta srtt
= rtt_stats_
.smoothed_rtt();
841 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats_
.initial_rtt_us());
843 int64 delay_ms
= max(kMinHandshakeTimeoutMs
,
844 static_cast<int64
>(1.5 * srtt
.ToMilliseconds()));
845 return QuicTime::Delta::FromMilliseconds(
846 delay_ms
<< consecutive_crypto_retransmission_count_
);
849 const QuicTime::Delta
QuicSentPacketManager::GetTailLossProbeDelay() const {
850 QuicTime::Delta srtt
= rtt_stats_
.smoothed_rtt();
852 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats_
.initial_rtt_us());
854 if (!unacked_packets_
.HasMultipleInFlightPackets()) {
855 return QuicTime::Delta::Max(
856 srtt
.Multiply(2), srtt
.Multiply(1.5).Add(
857 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs
/ 2)));
859 return QuicTime::Delta::FromMilliseconds(
860 max(kMinTailLossProbeTimeoutMs
,
861 static_cast<int64
>(2 * srtt
.ToMilliseconds())));
864 const QuicTime::Delta
QuicSentPacketManager::GetRetransmissionDelay() const {
865 QuicTime::Delta retransmission_delay
= send_algorithm_
->RetransmissionDelay();
866 // TODO(rch): This code should move to |send_algorithm_|.
867 if (retransmission_delay
.IsZero()) {
868 // We are in the initial state, use default timeout values.
869 retransmission_delay
=
870 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs
);
871 } else if (retransmission_delay
.ToMilliseconds() < kMinRetransmissionTimeMs
) {
872 retransmission_delay
=
873 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs
);
876 // Calculate exponential back off.
877 retransmission_delay
= retransmission_delay
.Multiply(
878 1 << min
<size_t>(consecutive_rto_count_
, kMaxRetransmissions
));
880 if (retransmission_delay
.ToMilliseconds() > kMaxRetransmissionTimeMs
) {
881 return QuicTime::Delta::FromMilliseconds(kMaxRetransmissionTimeMs
);
883 return retransmission_delay
;
886 const RttStats
* QuicSentPacketManager::GetRttStats() const {
890 QuicBandwidth
QuicSentPacketManager::BandwidthEstimate() const {
891 // TODO(ianswett): Remove BandwidthEstimate from SendAlgorithmInterface
892 // and implement the logic here.
893 return send_algorithm_
->BandwidthEstimate();
896 const QuicSustainedBandwidthRecorder
&
897 QuicSentPacketManager::SustainedBandwidthRecorder() const {
898 return sustained_bandwidth_recorder_
;
901 QuicPacketCount
QuicSentPacketManager::EstimateMaxPacketsInFlight(
902 QuicByteCount max_packet_length
) const {
903 return send_algorithm_
->GetCongestionWindow() / max_packet_length
;
906 QuicPacketCount
QuicSentPacketManager::GetCongestionWindowInTcpMss() const {
907 return send_algorithm_
->GetCongestionWindow() / kDefaultTCPMSS
;
910 QuicPacketCount
QuicSentPacketManager::GetSlowStartThresholdInTcpMss() const {
911 return send_algorithm_
->GetSlowStartThreshold() / kDefaultTCPMSS
;
914 void QuicSentPacketManager::OnSerializedPacket(
915 const SerializedPacket
& serialized_packet
) {
916 ack_notifier_manager_
.OnSerializedPacket(serialized_packet
);
919 void QuicSentPacketManager::CancelRetransmissionsForStream(
920 QuicStreamId stream_id
) {
921 unacked_packets_
.CancelRetransmissionsForStream(stream_id
);
922 PendingRetransmissionMap::iterator it
= pending_retransmissions_
.begin();
923 while (it
!= pending_retransmissions_
.end()) {
924 if (HasRetransmittableFrames(it
->first
)) {
928 it
= pending_retransmissions_
.erase(it
);
932 void QuicSentPacketManager::EnablePacing() {
933 // TODO(ianswett): Replace with a method which wraps the send algorithm in a
934 // pacer every time a new algorithm is set.
939 // Set up a pacing sender with a 1 millisecond alarm granularity, the same as
940 // the default granularity of the Linux kernel's FQ qdisc.
941 using_pacing_
= true;
942 send_algorithm_
.reset(
943 new PacingSender(send_algorithm_
.release(),
944 QuicTime::Delta::FromMilliseconds(1),
945 kInitialUnpacedBurst
));