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/quic_ack_notifier_manager.h"
14 #include "net/quic/quic_connection_stats.h"
15 #include "net/quic/quic_flags.h"
16 #include "net/quic/quic_utils_chromium.h"
23 // The length of the recent min rtt window in seconds. Windowing is disabled for
24 // values less than or equal to 0.
25 int32 FLAGS_quic_recent_min_rtt_window_s
= 60;
28 static const int64 kDefaultRetransmissionTimeMs
= 500;
29 // TCP RFC calls for 1 second RTO however Linux differs from this default and
30 // define the minimum RTO to 200ms, we will use the same until we have data to
31 // support a higher or lower value.
32 static const int64 kMinRetransmissionTimeMs
= 200;
33 static const int64 kMaxRetransmissionTimeMs
= 60000;
34 // Maximum number of exponential backoffs used for RTO timeouts.
35 static const size_t kMaxRetransmissions
= 10;
36 // Maximum number of packets retransmitted upon an RTO.
37 static const size_t kMaxRetransmissionsOnTimeout
= 2;
39 // Ensure the handshake timer isnt't faster than 10ms.
40 // This limits the tenth retransmitted packet to 10s after the initial CHLO.
41 static const int64 kMinHandshakeTimeoutMs
= 10;
43 // Sends up to two tail loss probes before firing an RTO,
44 // per draft RFC draft-dukkipati-tcpm-tcp-loss-probe.
45 static const size_t kDefaultMaxTailLossProbes
= 2;
46 static const int64 kMinTailLossProbeTimeoutMs
= 10;
48 // Number of samples before we force a new recent min rtt to be captured.
49 static const size_t kNumMinRttSamplesAfterQuiescence
= 2;
51 // Number of unpaced packets to send after quiescence.
52 static const size_t kInitialUnpacedBurst
= 10;
54 // Fraction of the receive buffer that can be used for encrypted bytes.
55 // Allows a 5% overhead for IP and UDP framing, as well as ack only packets.
56 static const float kUsableRecieveBufferFraction
= 0.95f
;
58 bool HasCryptoHandshake(const TransmissionInfo
& transmission_info
) {
59 if (transmission_info
.retransmittable_frames
== nullptr) {
62 return transmission_info
.retransmittable_frames
->HasCryptoHandshake() ==
68 #define ENDPOINT (is_server_ ? "Server: " : " Client: ")
70 QuicSentPacketManager::QuicSentPacketManager(
72 const QuicClock
* clock
,
73 QuicConnectionStats
* stats
,
74 CongestionControlType congestion_control_type
,
75 LossDetectionType loss_type
,
78 is_server_(is_server
),
81 debug_delegate_(nullptr),
82 network_change_visitor_(nullptr),
83 initial_congestion_window_(is_secure
? kInitialCongestionWindowSecure
84 : kInitialCongestionWindowInsecure
),
86 SendAlgorithmInterface::Create(clock
,
88 congestion_control_type
,
90 initial_congestion_window_
)),
91 loss_algorithm_(LossDetectionInterface::Create(loss_type
)),
92 n_connection_simulation_(false),
93 receive_buffer_bytes_(kDefaultSocketReceiveBuffer
),
94 least_packet_awaited_by_peer_(1),
95 first_rto_transmission_(0),
96 consecutive_rto_count_(0),
97 consecutive_tlp_count_(0),
98 consecutive_crypto_retransmission_count_(0),
99 pending_timer_transmission_count_(0),
100 max_tail_loss_probes_(kDefaultMaxTailLossProbes
),
101 using_pacing_(false),
103 handshake_confirmed_(false) {
106 QuicSentPacketManager::~QuicSentPacketManager() {
109 void QuicSentPacketManager::SetFromConfig(const QuicConfig
& config
) {
110 if (config
.HasReceivedInitialRoundTripTimeUs() &&
111 config
.ReceivedInitialRoundTripTimeUs() > 0) {
112 rtt_stats_
.set_initial_rtt_us(
113 max(kMinInitialRoundTripTimeUs
,
114 min(kMaxInitialRoundTripTimeUs
,
115 config
.ReceivedInitialRoundTripTimeUs())));
116 } else if (config
.HasInitialRoundTripTimeUsToSend() &&
117 config
.GetInitialRoundTripTimeUsToSend() > 0) {
118 rtt_stats_
.set_initial_rtt_us(
119 max(kMinInitialRoundTripTimeUs
,
120 min(kMaxInitialRoundTripTimeUs
,
121 config
.GetInitialRoundTripTimeUsToSend())));
123 // Initial RTT may have changed.
124 if (network_change_visitor_
!= nullptr) {
125 network_change_visitor_
->OnRttChange();
127 // TODO(ianswett): BBR is currently a server only feature.
128 if (FLAGS_quic_allow_bbr
&&
129 config
.HasReceivedConnectionOptions() &&
130 ContainsQuicTag(config
.ReceivedConnectionOptions(), kTBBR
)) {
131 if (FLAGS_quic_recent_min_rtt_window_s
> 0) {
132 rtt_stats_
.set_recent_min_rtt_window(
133 QuicTime::Delta::FromSeconds(FLAGS_quic_recent_min_rtt_window_s
));
135 send_algorithm_
.reset(SendAlgorithmInterface::Create(
136 clock_
, &rtt_stats_
, kBBR
, stats_
, initial_congestion_window_
));
138 if (config
.HasReceivedConnectionOptions() &&
139 ContainsQuicTag(config
.ReceivedConnectionOptions(), kRENO
)) {
140 send_algorithm_
.reset(SendAlgorithmInterface::Create(
141 clock_
, &rtt_stats_
, kReno
, stats_
, initial_congestion_window_
));
143 if (HasClientSentConnectionOption(config
, kPACE
) ||
144 FLAGS_quic_enable_pacing
||
145 (FLAGS_quic_allow_bbr
&& HasClientSentConnectionOption(config
, kTBBR
))) {
148 if (HasClientSentConnectionOption(config
, k1CON
)) {
149 send_algorithm_
->SetNumEmulatedConnections(1);
151 if (HasClientSentConnectionOption(config
, kNCON
)) {
152 n_connection_simulation_
= true;
154 if (HasClientSentConnectionOption(config
, kNTLP
)) {
155 max_tail_loss_probes_
= 0;
157 if (HasClientSentConnectionOption(config
, kNRTO
)) {
160 if (config
.HasReceivedConnectionOptions() &&
161 ContainsQuicTag(config
.ReceivedConnectionOptions(), kTIME
)) {
162 loss_algorithm_
.reset(LossDetectionInterface::Create(kTime
));
164 if (config
.HasReceivedSocketReceiveBuffer()) {
165 receive_buffer_bytes_
=
166 max(kMinSocketReceiveBuffer
,
167 static_cast<QuicByteCount
>(config
.ReceivedSocketReceiveBuffer()));
169 send_algorithm_
->SetFromConfig(config
, is_server_
, using_pacing_
);
171 if (network_change_visitor_
!= nullptr) {
172 network_change_visitor_
->OnCongestionWindowChange();
176 bool QuicSentPacketManager::ResumeConnectionState(
177 const CachedNetworkParameters
& cached_network_params
) {
178 if (cached_network_params
.has_min_rtt_ms()) {
179 uint32 initial_rtt_us
=
180 kNumMicrosPerMilli
* cached_network_params
.min_rtt_ms();
181 rtt_stats_
.set_initial_rtt_us(
182 max(kMinInitialRoundTripTimeUs
,
183 min(kMaxInitialRoundTripTimeUs
, initial_rtt_us
)));
185 return send_algorithm_
->ResumeConnectionState(cached_network_params
);
188 void QuicSentPacketManager::SetNumOpenStreams(size_t num_streams
) {
189 if (n_connection_simulation_
) {
190 // Ensure the number of connections is between 1 and 5.
191 send_algorithm_
->SetNumEmulatedConnections(
192 min
<size_t>(5, max
<size_t>(1, num_streams
)));
196 bool QuicSentPacketManager::HasClientSentConnectionOption(
197 const QuicConfig
& config
, QuicTag tag
) const {
199 if (config
.HasReceivedConnectionOptions() &&
200 ContainsQuicTag(config
.ReceivedConnectionOptions(), tag
)) {
203 } else if (config
.HasSendConnectionOptions() &&
204 ContainsQuicTag(config
.SendConnectionOptions(), tag
)) {
210 void QuicSentPacketManager::OnIncomingAck(const QuicAckFrame
& ack_frame
,
211 QuicTime ack_receive_time
) {
212 QuicByteCount bytes_in_flight
= unacked_packets_
.bytes_in_flight();
214 UpdatePacketInformationReceivedByPeer(ack_frame
);
215 bool rtt_updated
= MaybeUpdateRTT(ack_frame
, ack_receive_time
);
216 DCHECK_GE(ack_frame
.largest_observed
, unacked_packets_
.largest_observed());
217 unacked_packets_
.IncreaseLargestObserved(ack_frame
.largest_observed
);
219 HandleAckForSentPackets(ack_frame
);
220 InvokeLossDetection(ack_receive_time
);
221 // Ignore losses in RTO mode.
222 if (consecutive_rto_count_
> 0 && !use_new_rto_
) {
223 packets_lost_
.clear();
225 MaybeInvokeCongestionEvent(rtt_updated
, bytes_in_flight
);
226 unacked_packets_
.RemoveObsoletePackets();
228 sustained_bandwidth_recorder_
.RecordEstimate(
229 send_algorithm_
->InRecovery(),
230 send_algorithm_
->InSlowStart(),
231 send_algorithm_
->BandwidthEstimate(),
234 rtt_stats_
.smoothed_rtt());
236 // If we have received a truncated ack, then we need to clear out some
237 // previous transmissions to allow the peer to actually ACK new packets.
238 if (ack_frame
.is_truncated
) {
239 unacked_packets_
.ClearAllPreviousRetransmissions();
242 // Anytime we are making forward progress and have a new RTT estimate, reset
243 // the backoff counters.
245 if (consecutive_rto_count_
> 0) {
246 // If the ack acknowledges data sent prior to the RTO,
247 // the RTO was spurious.
248 if (ack_frame
.largest_observed
< first_rto_transmission_
) {
249 // Replace SRTT with latest_rtt and increase the variance to prevent
250 // a spurious RTO from happening again.
251 rtt_stats_
.ExpireSmoothedMetrics();
254 send_algorithm_
->OnRetransmissionTimeout(true);
258 // Reset all retransmit counters any time a new packet is acked.
259 consecutive_rto_count_
= 0;
260 consecutive_tlp_count_
= 0;
261 consecutive_crypto_retransmission_count_
= 0;
264 if (debug_delegate_
!= nullptr) {
265 debug_delegate_
->OnIncomingAck(ack_frame
, ack_receive_time
,
266 unacked_packets_
.largest_observed(),
267 rtt_updated
, GetLeastUnacked());
271 void QuicSentPacketManager::UpdatePacketInformationReceivedByPeer(
272 const QuicAckFrame
& ack_frame
) {
273 if (ack_frame
.missing_packets
.empty()) {
274 least_packet_awaited_by_peer_
= ack_frame
.largest_observed
+ 1;
276 least_packet_awaited_by_peer_
= *(ack_frame
.missing_packets
.begin());
280 void QuicSentPacketManager::MaybeInvokeCongestionEvent(
281 bool rtt_updated
, QuicByteCount bytes_in_flight
) {
282 if (!rtt_updated
&& packets_acked_
.empty() && packets_lost_
.empty()) {
285 send_algorithm_
->OnCongestionEvent(rtt_updated
, bytes_in_flight
,
286 packets_acked_
, packets_lost_
);
287 packets_acked_
.clear();
288 packets_lost_
.clear();
289 if (network_change_visitor_
!= nullptr) {
290 network_change_visitor_
->OnCongestionWindowChange();
294 void QuicSentPacketManager::HandleAckForSentPackets(
295 const QuicAckFrame
& ack_frame
) {
296 // Go through the packets we have not received an ack for and see if this
297 // incoming_ack shows they've been seen by the peer.
298 QuicTime::Delta delta_largest_observed
=
299 ack_frame
.delta_time_largest_observed
;
300 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
301 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
302 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
303 if (sequence_number
> ack_frame
.largest_observed
) {
304 // These packets are still in flight.
308 if (ContainsKey(ack_frame
.missing_packets
, sequence_number
)) {
309 // Don't continue to increase the nack count for packets not in flight.
310 if (!it
->in_flight
) {
313 // Consider it multiple nacks when there is a gap between the missing
314 // packet and the largest observed, since the purpose of a nack
315 // threshold is to tolerate re-ordering. This handles both StretchAcks
317 // The nack count only increases when the largest observed increases.
318 QuicPacketCount min_nacks
= ack_frame
.largest_observed
- sequence_number
;
319 // Truncated acks can nack the largest observed, so use a min of 1.
320 if (min_nacks
== 0) {
323 unacked_packets_
.NackPacket(sequence_number
, min_nacks
);
326 // Packet was acked, so remove it from our unacked packet list.
327 DVLOG(1) << ENDPOINT
<< "Got an ack for packet " << sequence_number
;
328 // If data is associated with the most recent transmission of this
329 // packet, then inform the caller.
331 packets_acked_
.push_back(std::make_pair(sequence_number
, *it
));
333 MarkPacketHandled(sequence_number
, *it
, delta_largest_observed
);
336 // Discard any retransmittable frames associated with revived packets.
337 for (SequenceNumberSet::const_iterator revived_it
=
338 ack_frame
.revived_packets
.begin();
339 revived_it
!= ack_frame
.revived_packets
.end(); ++revived_it
) {
340 MarkPacketRevived(*revived_it
, delta_largest_observed
);
344 bool QuicSentPacketManager::HasRetransmittableFrames(
345 QuicPacketSequenceNumber sequence_number
) const {
346 return unacked_packets_
.HasRetransmittableFrames(sequence_number
);
349 void QuicSentPacketManager::RetransmitUnackedPackets(
350 TransmissionType retransmission_type
) {
351 DCHECK(retransmission_type
== ALL_UNACKED_RETRANSMISSION
||
352 retransmission_type
== ALL_INITIAL_RETRANSMISSION
);
353 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
354 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
355 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
356 const RetransmittableFrames
* frames
= it
->retransmittable_frames
;
357 if (frames
!= nullptr &&
358 (retransmission_type
== ALL_UNACKED_RETRANSMISSION
||
359 frames
->encryption_level() == ENCRYPTION_INITIAL
)) {
360 MarkForRetransmission(sequence_number
, retransmission_type
);
361 } else if (it
->is_fec_packet
) {
362 // Remove FEC packets from the packet map, since we can't retransmit them.
363 unacked_packets_
.RemoveFromInFlight(sequence_number
);
368 void QuicSentPacketManager::NeuterUnencryptedPackets() {
369 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
370 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
371 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
372 const RetransmittableFrames
* frames
= it
->retransmittable_frames
;
373 if (frames
!= nullptr && frames
->encryption_level() == ENCRYPTION_NONE
) {
374 // Once you're forward secure, no unencrypted packets will be sent, crypto
375 // or otherwise. Unencrypted packets are neutered and abandoned, to ensure
376 // they are not retransmitted or considered lost from a congestion control
378 pending_retransmissions_
.erase(sequence_number
);
379 unacked_packets_
.RemoveFromInFlight(sequence_number
);
380 unacked_packets_
.RemoveRetransmittability(sequence_number
);
385 void QuicSentPacketManager::MarkForRetransmission(
386 QuicPacketSequenceNumber sequence_number
,
387 TransmissionType transmission_type
) {
388 const TransmissionInfo
& transmission_info
=
389 unacked_packets_
.GetTransmissionInfo(sequence_number
);
390 LOG_IF(DFATAL
, transmission_info
.retransmittable_frames
== nullptr);
391 // Both TLP and the new RTO leave the packets in flight and let the loss
392 // detection decide if packets are lost.
393 if (transmission_type
!= TLP_RETRANSMISSION
&&
394 transmission_type
!= RTO_RETRANSMISSION
) {
395 unacked_packets_
.RemoveFromInFlight(sequence_number
);
397 // TODO(ianswett): Currently the RTO can fire while there are pending NACK
398 // retransmissions for the same data, which is not ideal.
399 if (ContainsKey(pending_retransmissions_
, sequence_number
)) {
403 pending_retransmissions_
[sequence_number
] = transmission_type
;
406 void QuicSentPacketManager::RecordSpuriousRetransmissions(
407 const SequenceNumberList
& all_transmissions
,
408 QuicPacketSequenceNumber acked_sequence_number
) {
409 for (SequenceNumberList::const_reverse_iterator it
=
410 all_transmissions
.rbegin();
411 it
!= all_transmissions
.rend() && *it
> acked_sequence_number
; ++it
) {
412 const TransmissionInfo
& retransmit_info
=
413 unacked_packets_
.GetTransmissionInfo(*it
);
415 stats_
->bytes_spuriously_retransmitted
+= retransmit_info
.bytes_sent
;
416 ++stats_
->packets_spuriously_retransmitted
;
417 if (debug_delegate_
!= nullptr) {
418 debug_delegate_
->OnSpuriousPacketRetransmission(
419 retransmit_info
.transmission_type
, retransmit_info
.bytes_sent
);
424 bool QuicSentPacketManager::HasPendingRetransmissions() const {
425 return !pending_retransmissions_
.empty();
428 QuicSentPacketManager::PendingRetransmission
429 QuicSentPacketManager::NextPendingRetransmission() {
430 LOG_IF(DFATAL
, pending_retransmissions_
.empty())
431 << "Unexpected call to PendingRetransmissions() with empty pending "
432 << "retransmission list. Corrupted memory usage imminent.";
433 QuicPacketSequenceNumber sequence_number
=
434 pending_retransmissions_
.begin()->first
;
435 TransmissionType transmission_type
= pending_retransmissions_
.begin()->second
;
436 if (unacked_packets_
.HasPendingCryptoPackets()) {
437 // Ensure crypto packets are retransmitted before other packets.
438 for (const auto& pair
: pending_retransmissions_
) {
439 if (HasCryptoHandshake(
440 unacked_packets_
.GetTransmissionInfo(pair
.first
))) {
441 sequence_number
= pair
.first
;
442 transmission_type
= pair
.second
;
447 DCHECK(unacked_packets_
.IsUnacked(sequence_number
)) << sequence_number
;
448 const TransmissionInfo
& transmission_info
=
449 unacked_packets_
.GetTransmissionInfo(sequence_number
);
450 DCHECK(transmission_info
.retransmittable_frames
);
452 return PendingRetransmission(sequence_number
,
454 *transmission_info
.retransmittable_frames
,
455 transmission_info
.sequence_number_length
);
458 void QuicSentPacketManager::MarkPacketRevived(
459 QuicPacketSequenceNumber sequence_number
,
460 QuicTime::Delta delta_largest_observed
) {
461 if (!unacked_packets_
.IsUnacked(sequence_number
)) {
465 const TransmissionInfo
& transmission_info
=
466 unacked_packets_
.GetTransmissionInfo(sequence_number
);
467 QuicPacketSequenceNumber newest_transmission
=
468 transmission_info
.all_transmissions
== nullptr
470 : *transmission_info
.all_transmissions
->rbegin();
471 // This packet has been revived at the receiver. If we were going to
472 // retransmit it, do not retransmit it anymore.
473 pending_retransmissions_
.erase(newest_transmission
);
475 // The AckNotifierManager needs to be notified for revived packets,
476 // since it indicates the packet arrived from the appliction's perspective.
477 ack_notifier_manager_
.OnPacketAcked(newest_transmission
,
478 delta_largest_observed
);
480 unacked_packets_
.RemoveRetransmittability(sequence_number
);
483 void QuicSentPacketManager::MarkPacketHandled(
484 QuicPacketSequenceNumber sequence_number
,
485 const TransmissionInfo
& info
,
486 QuicTime::Delta delta_largest_observed
) {
487 QuicPacketSequenceNumber newest_transmission
=
488 info
.all_transmissions
== nullptr ?
489 sequence_number
: *info
.all_transmissions
->rbegin();
490 // Remove the most recent packet, if it is pending retransmission.
491 pending_retransmissions_
.erase(newest_transmission
);
493 // The AckNotifierManager needs to be notified about the most recent
494 // transmission, since that's the one only one it tracks.
495 ack_notifier_manager_
.OnPacketAcked(newest_transmission
,
496 delta_largest_observed
);
497 if (newest_transmission
!= sequence_number
) {
498 RecordSpuriousRetransmissions(*info
.all_transmissions
, sequence_number
);
499 // Remove the most recent packet from flight if it's a crypto handshake
500 // packet, since they won't be acked now that one has been processed.
501 // Other crypto handshake packets won't be in flight, only the newest
502 // transmission of a crypto packet is in flight at once.
503 // TODO(ianswett): Instead of handling all crypto packets special,
504 // only handle nullptr encrypted packets in a special way.
505 if (HasCryptoHandshake(
506 unacked_packets_
.GetTransmissionInfo(newest_transmission
))) {
507 unacked_packets_
.RemoveFromInFlight(newest_transmission
);
511 unacked_packets_
.RemoveFromInFlight(sequence_number
);
512 unacked_packets_
.RemoveRetransmittability(sequence_number
);
515 bool QuicSentPacketManager::IsUnacked(
516 QuicPacketSequenceNumber sequence_number
) const {
517 return unacked_packets_
.IsUnacked(sequence_number
);
520 bool QuicSentPacketManager::HasUnackedPackets() const {
521 return unacked_packets_
.HasUnackedPackets();
524 QuicPacketSequenceNumber
525 QuicSentPacketManager::GetLeastUnacked() const {
526 return unacked_packets_
.GetLeastUnacked();
529 bool QuicSentPacketManager::OnPacketSent(
530 SerializedPacket
* serialized_packet
,
531 QuicPacketSequenceNumber original_sequence_number
,
534 TransmissionType transmission_type
,
535 HasRetransmittableData has_retransmittable_data
) {
536 QuicPacketSequenceNumber sequence_number
= serialized_packet
->sequence_number
;
537 DCHECK_LT(0u, sequence_number
);
538 DCHECK(!unacked_packets_
.IsUnacked(sequence_number
));
539 LOG_IF(DFATAL
, bytes
== 0) << "Cannot send empty packets.";
541 if (original_sequence_number
!= 0) {
542 PendingRetransmissionMap::iterator it
=
543 pending_retransmissions_
.find(original_sequence_number
);
544 if (it
!= pending_retransmissions_
.end()) {
545 pending_retransmissions_
.erase(it
);
547 DLOG(DFATAL
) << "Expected sequence number to be in "
548 << "pending_retransmissions_. sequence_number: "
549 << original_sequence_number
;
551 // Inform the ack notifier of retransmissions so it can calculate the
553 ack_notifier_manager_
.OnPacketRetransmitted(original_sequence_number
,
554 sequence_number
, bytes
);
557 if (pending_timer_transmission_count_
> 0) {
558 --pending_timer_transmission_count_
;
561 if (unacked_packets_
.bytes_in_flight() == 0) {
562 // TODO(ianswett): Consider being less aggressive to force a new
563 // recent_min_rtt, likely by not discarding a relatively new sample.
564 DVLOG(1) << "Sampling a new recent min rtt within 2 samples. currently:"
565 << rtt_stats_
.recent_min_rtt().ToMilliseconds() << "ms";
566 rtt_stats_
.SampleNewRecentMinRtt(kNumMinRttSamplesAfterQuiescence
);
569 // Only track packets as in flight that the send algorithm wants us to track.
570 // Since FEC packets should also be counted towards the congestion window,
571 // consider them as retransmittable for the purposes of congestion control.
572 HasRetransmittableData has_congestion_controlled_data
=
573 serialized_packet
->is_fec_packet
? HAS_RETRANSMITTABLE_DATA
574 : has_retransmittable_data
;
575 const bool in_flight
=
576 send_algorithm_
->OnPacketSent(sent_time
,
577 unacked_packets_
.bytes_in_flight(),
580 has_congestion_controlled_data
);
582 unacked_packets_
.AddSentPacket(*serialized_packet
,
583 original_sequence_number
,
589 // Take ownership of the retransmittable frames before exiting.
590 serialized_packet
->retransmittable_frames
= nullptr;
591 // Reset the retransmission timer anytime a pending packet is sent.
595 void QuicSentPacketManager::OnRetransmissionTimeout() {
596 DCHECK(unacked_packets_
.HasInFlightPackets());
597 DCHECK_EQ(0u, pending_timer_transmission_count_
);
598 // Handshake retransmission, timer based loss detection, TLP, and RTO are
599 // implemented with a single alarm. The handshake alarm is set when the
600 // handshake has not completed, the loss alarm is set when the loss detection
601 // algorithm says to, and the TLP and RTO alarms are set after that.
602 // The TLP alarm is always set to run for under an RTO.
603 switch (GetRetransmissionMode()) {
605 ++stats_
->crypto_retransmit_count
;
606 RetransmitCryptoPackets();
609 ++stats_
->loss_timeout_count
;
610 QuicByteCount bytes_in_flight
= unacked_packets_
.bytes_in_flight();
611 InvokeLossDetection(clock_
->Now());
612 MaybeInvokeCongestionEvent(false, bytes_in_flight
);
616 // If no tail loss probe can be sent, because there are no retransmittable
617 // packets, execute a conventional RTO to abandon old packets.
619 ++consecutive_tlp_count_
;
620 pending_timer_transmission_count_
= 1;
621 // TLPs prefer sending new data instead of retransmitting data, so
622 // give the connection a chance to write before completing the TLP.
626 RetransmitRtoPackets();
631 void QuicSentPacketManager::RetransmitCryptoPackets() {
632 DCHECK_EQ(HANDSHAKE_MODE
, GetRetransmissionMode());
633 ++consecutive_crypto_retransmission_count_
;
634 bool packet_retransmitted
= false;
635 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
636 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
637 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
638 // Only retransmit frames which are in flight, and therefore have been sent.
639 if (!it
->in_flight
|| it
->retransmittable_frames
== nullptr ||
640 it
->retransmittable_frames
->HasCryptoHandshake() != IS_HANDSHAKE
) {
643 packet_retransmitted
= true;
644 MarkForRetransmission(sequence_number
, HANDSHAKE_RETRANSMISSION
);
645 ++pending_timer_transmission_count_
;
647 DCHECK(packet_retransmitted
) << "No crypto packets found to retransmit.";
650 bool QuicSentPacketManager::MaybeRetransmitTailLossProbe() {
651 if (pending_timer_transmission_count_
== 0) {
654 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
655 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
656 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
657 // Only retransmit frames which are in flight, and therefore have been sent.
658 if (!it
->in_flight
|| it
->retransmittable_frames
== nullptr) {
661 if (!handshake_confirmed_
) {
662 DCHECK_NE(IS_HANDSHAKE
, it
->retransmittable_frames
->HasCryptoHandshake());
664 MarkForRetransmission(sequence_number
, TLP_RETRANSMISSION
);
668 << "No retransmittable packets, so RetransmitOldestPacket failed.";
672 void QuicSentPacketManager::RetransmitRtoPackets() {
673 LOG_IF(DFATAL
, pending_timer_transmission_count_
> 0)
674 << "Retransmissions already queued:" << pending_timer_transmission_count_
;
675 // Mark two packets for retransmission.
676 QuicPacketSequenceNumber sequence_number
= unacked_packets_
.GetLeastUnacked();
677 for (QuicUnackedPacketMap::const_iterator it
= unacked_packets_
.begin();
678 it
!= unacked_packets_
.end(); ++it
, ++sequence_number
) {
679 if (it
->retransmittable_frames
!= nullptr &&
680 pending_timer_transmission_count_
< kMaxRetransmissionsOnTimeout
) {
681 MarkForRetransmission(sequence_number
, RTO_RETRANSMISSION
);
682 ++pending_timer_transmission_count_
;
684 // Abandon non-retransmittable data that's in flight to ensure it doesn't
685 // fill up the congestion window.
686 if (it
->retransmittable_frames
== nullptr && it
->in_flight
&&
687 it
->all_transmissions
== nullptr) {
688 unacked_packets_
.RemoveFromInFlight(sequence_number
);
691 if (pending_timer_transmission_count_
> 0) {
692 if (consecutive_rto_count_
== 0) {
693 first_rto_transmission_
= unacked_packets_
.largest_sent_packet() + 1;
695 ++consecutive_rto_count_
;
699 QuicSentPacketManager::RetransmissionTimeoutMode
700 QuicSentPacketManager::GetRetransmissionMode() const {
701 DCHECK(unacked_packets_
.HasInFlightPackets());
702 if (!handshake_confirmed_
&& unacked_packets_
.HasPendingCryptoPackets()) {
703 return HANDSHAKE_MODE
;
705 if (loss_algorithm_
->GetLossTimeout() != QuicTime::Zero()) {
708 if (consecutive_tlp_count_
< max_tail_loss_probes_
) {
709 if (unacked_packets_
.HasUnackedRetransmittableFrames()) {
716 void QuicSentPacketManager::InvokeLossDetection(QuicTime time
) {
717 SequenceNumberSet lost_packets
=
718 loss_algorithm_
->DetectLostPackets(unacked_packets_
,
720 unacked_packets_
.largest_observed(),
722 for (SequenceNumberSet::const_iterator it
= lost_packets
.begin();
723 it
!= lost_packets
.end(); ++it
) {
724 QuicPacketSequenceNumber sequence_number
= *it
;
725 const TransmissionInfo
& transmission_info
=
726 unacked_packets_
.GetTransmissionInfo(sequence_number
);
727 // TODO(ianswett): If it's expected the FEC packet may repair the loss, it
728 // should be recorded as a loss to the send algorithm, but not retransmitted
729 // until it's known whether the FEC packet arrived.
730 ++stats_
->packets_lost
;
731 packets_lost_
.push_back(std::make_pair(sequence_number
, transmission_info
));
732 DVLOG(1) << ENDPOINT
<< "Lost packet " << sequence_number
;
734 if (transmission_info
.retransmittable_frames
!= nullptr) {
735 MarkForRetransmission(sequence_number
, LOSS_RETRANSMISSION
);
737 // Since we will not retransmit this, we need to remove it from
738 // unacked_packets_. This is either the current transmission of
739 // a packet whose previous transmission has been acked, a packet that has
740 // been TLP retransmitted, or an FEC packet.
741 unacked_packets_
.RemoveFromInFlight(sequence_number
);
746 bool QuicSentPacketManager::MaybeUpdateRTT(
747 const QuicAckFrame
& ack_frame
,
748 const QuicTime
& ack_receive_time
) {
749 // We rely on delta_time_largest_observed to compute an RTT estimate, so we
750 // only update rtt when the largest observed gets acked.
751 // NOTE: If ack is a truncated ack, then the largest observed is in fact
752 // unacked, and may cause an RTT sample to be taken.
753 if (!unacked_packets_
.IsUnacked(ack_frame
.largest_observed
)) {
756 // We calculate the RTT based on the highest ACKed sequence number, the lower
757 // sequence numbers will include the ACK aggregation delay.
758 const TransmissionInfo
& transmission_info
=
759 unacked_packets_
.GetTransmissionInfo(ack_frame
.largest_observed
);
760 // Ensure the packet has a valid sent time.
761 if (transmission_info
.sent_time
== QuicTime::Zero()) {
762 LOG(DFATAL
) << "Acked packet has zero sent time, largest_observed:"
763 << ack_frame
.largest_observed
;
767 QuicTime::Delta send_delta
=
768 ack_receive_time
.Subtract(transmission_info
.sent_time
);
769 rtt_stats_
.UpdateRtt(
770 send_delta
, ack_frame
.delta_time_largest_observed
, ack_receive_time
);
772 if (network_change_visitor_
!= nullptr) {
773 network_change_visitor_
->OnRttChange();
779 QuicTime::Delta
QuicSentPacketManager::TimeUntilSend(
781 HasRetransmittableData retransmittable
) {
782 // The TLP logic is entirely contained within QuicSentPacketManager, so the
783 // send algorithm does not need to be consulted.
784 if (pending_timer_transmission_count_
> 0) {
785 return QuicTime::Delta::Zero();
787 if (unacked_packets_
.bytes_in_flight() >=
788 kUsableRecieveBufferFraction
* receive_buffer_bytes_
) {
789 return QuicTime::Delta::Infinite();
791 return send_algorithm_
->TimeUntilSend(
792 now
, unacked_packets_
.bytes_in_flight(), retransmittable
);
795 // Uses a 25ms delayed ack timer. Also helps with better signaling
796 // in low-bandwidth (< ~384 kbps), where an ack is sent per packet.
797 // Ensures that the Delayed Ack timer is always set to a value lesser
798 // than the retransmission timer's minimum value (MinRTO). We want the
799 // delayed ack to get back to the QUIC peer before the sender's
800 // retransmission timer triggers. Since we do not know the
801 // reverse-path one-way delay, we assume equal delays for forward and
802 // reverse paths, and ensure that the timer is set to less than half
804 // There may be a value in making this delay adaptive with the help of
805 // the sender and a signaling mechanism -- if the sender uses a
806 // different MinRTO, we may get spurious retransmissions. May not have
807 // any benefits, but if the delayed ack becomes a significant source
808 // of (likely, tail) latency, then consider such a mechanism.
809 const QuicTime::Delta
QuicSentPacketManager::DelayedAckTime() const {
810 return QuicTime::Delta::FromMilliseconds(min(kMaxDelayedAckTimeMs
,
811 kMinRetransmissionTimeMs
/ 2));
814 const QuicTime
QuicSentPacketManager::GetRetransmissionTime() const {
815 // Don't set the timer if there are no packets in flight or we've already
816 // queued a tlp transmission and it hasn't been sent yet.
817 if (!unacked_packets_
.HasInFlightPackets() ||
818 pending_timer_transmission_count_
> 0) {
819 return QuicTime::Zero();
821 switch (GetRetransmissionMode()) {
823 return clock_
->ApproximateNow().Add(GetCryptoRetransmissionDelay());
825 return loss_algorithm_
->GetLossTimeout();
827 // TODO(ianswett): When CWND is available, it would be preferable to
828 // set the timer based on the earliest retransmittable packet.
829 // Base the updated timer on the send time of the last packet.
830 const QuicTime sent_time
= unacked_packets_
.GetLastPacketSentTime();
831 const QuicTime tlp_time
= sent_time
.Add(GetTailLossProbeDelay());
832 // Ensure the TLP timer never gets set to a time in the past.
833 return QuicTime::Max(clock_
->ApproximateNow(), tlp_time
);
836 // The RTO is based on the first outstanding packet.
837 const QuicTime sent_time
= unacked_packets_
.GetLastPacketSentTime();
838 QuicTime rto_time
= sent_time
.Add(GetRetransmissionDelay());
839 // Wait for TLP packets to be acked before an RTO fires.
841 unacked_packets_
.GetLastPacketSentTime().Add(GetTailLossProbeDelay());
842 return QuicTime::Max(tlp_time
, rto_time
);
846 return QuicTime::Zero();
849 const QuicTime::Delta
QuicSentPacketManager::GetCryptoRetransmissionDelay()
851 // This is equivalent to the TailLossProbeDelay, but slightly more aggressive
852 // because crypto handshake messages don't incur a delayed ack time.
853 QuicTime::Delta srtt
= rtt_stats_
.smoothed_rtt();
855 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats_
.initial_rtt_us());
857 int64 delay_ms
= max(kMinHandshakeTimeoutMs
,
858 static_cast<int64
>(1.5 * srtt
.ToMilliseconds()));
859 return QuicTime::Delta::FromMilliseconds(
860 delay_ms
<< consecutive_crypto_retransmission_count_
);
863 const QuicTime::Delta
QuicSentPacketManager::GetTailLossProbeDelay() const {
864 QuicTime::Delta srtt
= rtt_stats_
.smoothed_rtt();
866 srtt
= QuicTime::Delta::FromMicroseconds(rtt_stats_
.initial_rtt_us());
868 if (!unacked_packets_
.HasMultipleInFlightPackets()) {
869 return QuicTime::Delta::Max(
870 srtt
.Multiply(2), srtt
.Multiply(1.5).Add(
871 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs
/ 2)));
873 return QuicTime::Delta::FromMilliseconds(
874 max(kMinTailLossProbeTimeoutMs
,
875 static_cast<int64
>(2 * srtt
.ToMilliseconds())));
878 const QuicTime::Delta
QuicSentPacketManager::GetRetransmissionDelay() const {
879 QuicTime::Delta retransmission_delay
= send_algorithm_
->RetransmissionDelay();
880 // TODO(rch): This code should move to |send_algorithm_|.
881 if (retransmission_delay
.IsZero()) {
882 // We are in the initial state, use default timeout values.
883 retransmission_delay
=
884 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs
);
885 } else if (retransmission_delay
.ToMilliseconds() < kMinRetransmissionTimeMs
) {
886 retransmission_delay
=
887 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs
);
890 // Calculate exponential back off.
891 retransmission_delay
= retransmission_delay
.Multiply(
892 1 << min
<size_t>(consecutive_rto_count_
, kMaxRetransmissions
));
894 if (retransmission_delay
.ToMilliseconds() > kMaxRetransmissionTimeMs
) {
895 return QuicTime::Delta::FromMilliseconds(kMaxRetransmissionTimeMs
);
897 return retransmission_delay
;
900 const RttStats
* QuicSentPacketManager::GetRttStats() const {
904 QuicBandwidth
QuicSentPacketManager::BandwidthEstimate() const {
905 // TODO(ianswett): Remove BandwidthEstimate from SendAlgorithmInterface
906 // and implement the logic here.
907 return send_algorithm_
->BandwidthEstimate();
910 bool QuicSentPacketManager::HasReliableBandwidthEstimate() const {
911 return send_algorithm_
->HasReliableBandwidthEstimate();
914 const QuicSustainedBandwidthRecorder
&
915 QuicSentPacketManager::SustainedBandwidthRecorder() const {
916 return sustained_bandwidth_recorder_
;
919 QuicPacketCount
QuicSentPacketManager::EstimateMaxPacketsInFlight(
920 QuicByteCount max_packet_length
) const {
921 return send_algorithm_
->GetCongestionWindow() / max_packet_length
;
924 QuicPacketCount
QuicSentPacketManager::GetCongestionWindowInTcpMss() const {
925 return send_algorithm_
->GetCongestionWindow() / kDefaultTCPMSS
;
928 QuicPacketCount
QuicSentPacketManager::GetSlowStartThresholdInTcpMss() const {
929 return send_algorithm_
->GetSlowStartThreshold() / kDefaultTCPMSS
;
932 void QuicSentPacketManager::OnSerializedPacket(
933 const SerializedPacket
& serialized_packet
) {
934 ack_notifier_manager_
.OnSerializedPacket(serialized_packet
);
937 void QuicSentPacketManager::EnablePacing() {
942 // Set up a pacing sender with a 1 millisecond alarm granularity, the same as
943 // the default granularity of the Linux kernel's FQ qdisc.
944 using_pacing_
= true;
945 send_algorithm_
.reset(
946 new PacingSender(send_algorithm_
.release(),
947 QuicTime::Delta::FromMilliseconds(1),
948 kInitialUnpacedBurst
));