Update broken references to image assets
[chromium-blink-merge.git] / net / quic / quic_sent_packet_manager.cc
blobaa3423a0fa5e90fdeb2f308baed99cf738a44a6f
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"
7 #include <algorithm>
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"
19 using std::max;
20 using std::min;
22 namespace net {
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;
28 namespace {
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) {
54 return false;
56 return transmission_info.retransmittable_frames->HasCryptoHandshake() ==
57 IS_HANDSHAKE;
60 } // namespace
62 #define ENDPOINT \
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,
71 bool is_secure)
72 : unacked_packets_(&ack_notifier_manager_),
73 perspective_(perspective),
74 clock_(clock),
75 stats_(stats),
76 debug_delegate_(nullptr),
77 network_change_visitor_(nullptr),
78 initial_congestion_window_(is_secure ? kInitialCongestionWindowSecure
79 : kInitialCongestionWindowInsecure),
80 send_algorithm_(
81 SendAlgorithmInterface::Create(clock,
82 &rtt_stats_,
83 congestion_control_type,
84 stats,
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),
96 using_pacing_(false),
97 use_new_rto_(false),
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_));
138 } else {
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_));
147 EnablePacing();
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_)) {
159 use_new_rto_ = true;
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) {
174 max_cwnd_bytes =
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(),
230 ack_receive_time,
231 clock_->WallNow(),
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 && !FLAGS_quic_disable_truncated_ack_handling) {
237 unacked_packets_.ClearAllPreviousRetransmissions();
240 // Anytime we are making forward progress and have a new RTT estimate, reset
241 // the backoff counters.
242 if (rtt_updated) {
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();
250 } else {
251 if (!use_new_rto_) {
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;
273 } else {
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()) {
281 return;
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.
303 break;
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) {
309 continue;
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
314 // and Forward Acks.
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) {
319 min_nacks = 1;
321 unacked_packets_.NackPacket(sequence_number, min_nacks);
322 continue;
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.
328 if (it->in_flight) {
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
375 // perspective.
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)) {
398 return;
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 // ianswett: Prevents crash in b/20552846.
411 if (*it < unacked_packets_.GetLeastUnacked() ||
412 *it > unacked_packets_.largest_sent_packet()) {
413 LOG(DFATAL) << "Retransmission out of range:" << *it
414 << " least unacked:" << unacked_packets_.GetLeastUnacked()
415 << " largest sent:" << unacked_packets_.largest_sent_packet();
416 return;
418 const TransmissionInfo& retransmit_info =
419 unacked_packets_.GetTransmissionInfo(*it);
421 stats_->bytes_spuriously_retransmitted += retransmit_info.bytes_sent;
422 ++stats_->packets_spuriously_retransmitted;
423 if (debug_delegate_ != nullptr) {
424 debug_delegate_->OnSpuriousPacketRetransmission(
425 retransmit_info.transmission_type, retransmit_info.bytes_sent);
430 bool QuicSentPacketManager::HasPendingRetransmissions() const {
431 return !pending_retransmissions_.empty();
434 QuicSentPacketManager::PendingRetransmission
435 QuicSentPacketManager::NextPendingRetransmission() {
436 LOG_IF(DFATAL, pending_retransmissions_.empty())
437 << "Unexpected call to PendingRetransmissions() with empty pending "
438 << "retransmission list. Corrupted memory usage imminent.";
439 QuicPacketSequenceNumber sequence_number =
440 pending_retransmissions_.begin()->first;
441 TransmissionType transmission_type = pending_retransmissions_.begin()->second;
442 if (unacked_packets_.HasPendingCryptoPackets()) {
443 // Ensure crypto packets are retransmitted before other packets.
444 for (const auto& pair : pending_retransmissions_) {
445 if (HasCryptoHandshake(
446 unacked_packets_.GetTransmissionInfo(pair.first))) {
447 sequence_number = pair.first;
448 transmission_type = pair.second;
449 break;
453 DCHECK(unacked_packets_.IsUnacked(sequence_number)) << sequence_number;
454 const TransmissionInfo& transmission_info =
455 unacked_packets_.GetTransmissionInfo(sequence_number);
456 DCHECK(transmission_info.retransmittable_frames);
458 return PendingRetransmission(sequence_number,
459 transmission_type,
460 *transmission_info.retransmittable_frames,
461 transmission_info.sequence_number_length);
464 void QuicSentPacketManager::MarkPacketRevived(
465 QuicPacketSequenceNumber sequence_number,
466 QuicTime::Delta delta_largest_observed) {
467 if (!unacked_packets_.IsUnacked(sequence_number)) {
468 return;
471 const TransmissionInfo& transmission_info =
472 unacked_packets_.GetTransmissionInfo(sequence_number);
473 QuicPacketSequenceNumber newest_transmission =
474 transmission_info.all_transmissions == nullptr
475 ? sequence_number
476 : *transmission_info.all_transmissions->rbegin();
477 // This packet has been revived at the receiver. If we were going to
478 // retransmit it, do not retransmit it anymore.
479 pending_retransmissions_.erase(newest_transmission);
481 // The AckNotifierManager needs to be notified for revived packets,
482 // since it indicates the packet arrived from the appliction's perspective.
483 ack_notifier_manager_.OnPacketAcked(newest_transmission,
484 delta_largest_observed);
486 unacked_packets_.RemoveRetransmittability(sequence_number);
489 void QuicSentPacketManager::MarkPacketHandled(
490 QuicPacketSequenceNumber sequence_number,
491 const TransmissionInfo& info,
492 QuicTime::Delta delta_largest_observed) {
493 QuicPacketSequenceNumber newest_transmission =
494 info.all_transmissions == nullptr ?
495 sequence_number : *info.all_transmissions->rbegin();
496 // Remove the most recent packet, if it is pending retransmission.
497 pending_retransmissions_.erase(newest_transmission);
499 // The AckNotifierManager needs to be notified about the most recent
500 // transmission, since that's the one only one it tracks.
501 ack_notifier_manager_.OnPacketAcked(newest_transmission,
502 delta_largest_observed);
503 if (newest_transmission != sequence_number) {
504 RecordSpuriousRetransmissions(*info.all_transmissions, sequence_number);
505 // Remove the most recent packet from flight if it's a crypto handshake
506 // packet, since they won't be acked now that one has been processed.
507 // Other crypto handshake packets won't be in flight, only the newest
508 // transmission of a crypto packet is in flight at once.
509 // TODO(ianswett): Instead of handling all crypto packets special,
510 // only handle nullptr encrypted packets in a special way.
511 if (HasCryptoHandshake(
512 unacked_packets_.GetTransmissionInfo(newest_transmission))) {
513 unacked_packets_.RemoveFromInFlight(newest_transmission);
517 unacked_packets_.RemoveFromInFlight(sequence_number);
518 unacked_packets_.RemoveRetransmittability(sequence_number);
521 bool QuicSentPacketManager::IsUnacked(
522 QuicPacketSequenceNumber sequence_number) const {
523 return unacked_packets_.IsUnacked(sequence_number);
526 bool QuicSentPacketManager::HasUnackedPackets() const {
527 return unacked_packets_.HasUnackedPackets();
530 QuicPacketSequenceNumber
531 QuicSentPacketManager::GetLeastUnacked() const {
532 return unacked_packets_.GetLeastUnacked();
535 bool QuicSentPacketManager::OnPacketSent(
536 SerializedPacket* serialized_packet,
537 QuicPacketSequenceNumber original_sequence_number,
538 QuicTime sent_time,
539 QuicByteCount bytes,
540 TransmissionType transmission_type,
541 HasRetransmittableData has_retransmittable_data) {
542 QuicPacketSequenceNumber sequence_number = serialized_packet->sequence_number;
543 DCHECK_LT(0u, sequence_number);
544 DCHECK(!unacked_packets_.IsUnacked(sequence_number));
545 LOG_IF(DFATAL, bytes == 0) << "Cannot send empty packets.";
547 if (original_sequence_number != 0) {
548 PendingRetransmissionMap::iterator it =
549 pending_retransmissions_.find(original_sequence_number);
550 if (it != pending_retransmissions_.end()) {
551 pending_retransmissions_.erase(it);
552 } else {
553 DLOG(DFATAL) << "Expected sequence number to be in "
554 << "pending_retransmissions_. sequence_number: "
555 << original_sequence_number;
557 // Inform the ack notifier of retransmissions so it can calculate the
558 // retransmit rate.
559 ack_notifier_manager_.OnPacketRetransmitted(original_sequence_number,
560 sequence_number, bytes);
563 if (pending_timer_transmission_count_ > 0) {
564 --pending_timer_transmission_count_;
567 // Only track packets as in flight that the send algorithm wants us to track.
568 // Since FEC packets should also be counted towards the congestion window,
569 // consider them as retransmittable for the purposes of congestion control.
570 HasRetransmittableData has_congestion_controlled_data =
571 serialized_packet->is_fec_packet ? HAS_RETRANSMITTABLE_DATA
572 : has_retransmittable_data;
573 const bool in_flight =
574 send_algorithm_->OnPacketSent(sent_time,
575 unacked_packets_.bytes_in_flight(),
576 sequence_number,
577 bytes,
578 has_congestion_controlled_data);
580 unacked_packets_.AddSentPacket(*serialized_packet,
581 original_sequence_number,
582 transmission_type,
583 sent_time,
584 bytes,
585 in_flight);
587 // Take ownership of the retransmittable frames before exiting.
588 serialized_packet->retransmittable_frames = nullptr;
589 // Reset the retransmission timer anytime a pending packet is sent.
590 return in_flight;
593 void QuicSentPacketManager::OnRetransmissionTimeout() {
594 DCHECK(unacked_packets_.HasInFlightPackets());
595 DCHECK_EQ(0u, pending_timer_transmission_count_);
596 // Handshake retransmission, timer based loss detection, TLP, and RTO are
597 // implemented with a single alarm. The handshake alarm is set when the
598 // handshake has not completed, the loss alarm is set when the loss detection
599 // algorithm says to, and the TLP and RTO alarms are set after that.
600 // The TLP alarm is always set to run for under an RTO.
601 switch (GetRetransmissionMode()) {
602 case HANDSHAKE_MODE:
603 ++stats_->crypto_retransmit_count;
604 RetransmitCryptoPackets();
605 return;
606 case LOSS_MODE: {
607 ++stats_->loss_timeout_count;
608 QuicByteCount bytes_in_flight = unacked_packets_.bytes_in_flight();
609 InvokeLossDetection(clock_->Now());
610 MaybeInvokeCongestionEvent(false, bytes_in_flight);
611 return;
613 case TLP_MODE:
614 // If no tail loss probe can be sent, because there are no retransmittable
615 // packets, execute a conventional RTO to abandon old packets.
616 ++stats_->tlp_count;
617 ++consecutive_tlp_count_;
618 pending_timer_transmission_count_ = 1;
619 // TLPs prefer sending new data instead of retransmitting data, so
620 // give the connection a chance to write before completing the TLP.
621 return;
622 case RTO_MODE:
623 ++stats_->rto_count;
624 RetransmitRtoPackets();
625 return;
629 void QuicSentPacketManager::RetransmitCryptoPackets() {
630 DCHECK_EQ(HANDSHAKE_MODE, GetRetransmissionMode());
631 ++consecutive_crypto_retransmission_count_;
632 bool packet_retransmitted = false;
633 QuicPacketSequenceNumber sequence_number = unacked_packets_.GetLeastUnacked();
634 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
635 it != unacked_packets_.end(); ++it, ++sequence_number) {
636 // Only retransmit frames which are in flight, and therefore have been sent.
637 if (!it->in_flight || it->retransmittable_frames == nullptr ||
638 it->retransmittable_frames->HasCryptoHandshake() != IS_HANDSHAKE) {
639 continue;
641 packet_retransmitted = true;
642 MarkForRetransmission(sequence_number, HANDSHAKE_RETRANSMISSION);
643 ++pending_timer_transmission_count_;
645 DCHECK(packet_retransmitted) << "No crypto packets found to retransmit.";
648 bool QuicSentPacketManager::MaybeRetransmitTailLossProbe() {
649 if (pending_timer_transmission_count_ == 0) {
650 return false;
652 QuicPacketSequenceNumber sequence_number = unacked_packets_.GetLeastUnacked();
653 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
654 it != unacked_packets_.end(); ++it, ++sequence_number) {
655 // Only retransmit frames which are in flight, and therefore have been sent.
656 if (!it->in_flight || it->retransmittable_frames == nullptr) {
657 continue;
659 if (!handshake_confirmed_) {
660 DCHECK_NE(IS_HANDSHAKE, it->retransmittable_frames->HasCryptoHandshake());
662 MarkForRetransmission(sequence_number, TLP_RETRANSMISSION);
663 return true;
665 DLOG(FATAL)
666 << "No retransmittable packets, so RetransmitOldestPacket failed.";
667 return false;
670 void QuicSentPacketManager::RetransmitRtoPackets() {
671 LOG_IF(DFATAL, pending_timer_transmission_count_ > 0)
672 << "Retransmissions already queued:" << pending_timer_transmission_count_;
673 // Mark two packets for retransmission.
674 QuicPacketSequenceNumber sequence_number = unacked_packets_.GetLeastUnacked();
675 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
676 it != unacked_packets_.end(); ++it, ++sequence_number) {
677 if (it->retransmittable_frames != nullptr &&
678 pending_timer_transmission_count_ < kMaxRetransmissionsOnTimeout) {
679 MarkForRetransmission(sequence_number, RTO_RETRANSMISSION);
680 ++pending_timer_transmission_count_;
682 // Abandon non-retransmittable data that's in flight to ensure it doesn't
683 // fill up the congestion window.
684 if (it->retransmittable_frames == nullptr && it->in_flight &&
685 it->all_transmissions == nullptr) {
686 unacked_packets_.RemoveFromInFlight(sequence_number);
689 if (pending_timer_transmission_count_ > 0) {
690 if (consecutive_rto_count_ == 0) {
691 first_rto_transmission_ = unacked_packets_.largest_sent_packet() + 1;
693 ++consecutive_rto_count_;
697 QuicSentPacketManager::RetransmissionTimeoutMode
698 QuicSentPacketManager::GetRetransmissionMode() const {
699 DCHECK(unacked_packets_.HasInFlightPackets());
700 if (!handshake_confirmed_ && unacked_packets_.HasPendingCryptoPackets()) {
701 return HANDSHAKE_MODE;
703 if (loss_algorithm_->GetLossTimeout() != QuicTime::Zero()) {
704 return LOSS_MODE;
706 if (consecutive_tlp_count_ < max_tail_loss_probes_) {
707 if (unacked_packets_.HasUnackedRetransmittableFrames()) {
708 return TLP_MODE;
711 return RTO_MODE;
714 void QuicSentPacketManager::InvokeLossDetection(QuicTime time) {
715 SequenceNumberSet lost_packets =
716 loss_algorithm_->DetectLostPackets(unacked_packets_,
717 time,
718 unacked_packets_.largest_observed(),
719 rtt_stats_);
720 for (SequenceNumberSet::const_iterator it = lost_packets.begin();
721 it != lost_packets.end(); ++it) {
722 QuicPacketSequenceNumber sequence_number = *it;
723 const TransmissionInfo& transmission_info =
724 unacked_packets_.GetTransmissionInfo(sequence_number);
725 // TODO(ianswett): If it's expected the FEC packet may repair the loss, it
726 // should be recorded as a loss to the send algorithm, but not retransmitted
727 // until it's known whether the FEC packet arrived.
728 ++stats_->packets_lost;
729 packets_lost_.push_back(std::make_pair(sequence_number, transmission_info));
730 DVLOG(1) << ENDPOINT << "Lost packet " << sequence_number;
732 if (transmission_info.retransmittable_frames != nullptr) {
733 MarkForRetransmission(sequence_number, LOSS_RETRANSMISSION);
734 } else {
735 // Since we will not retransmit this, we need to remove it from
736 // unacked_packets_. This is either the current transmission of
737 // a packet whose previous transmission has been acked, a packet that has
738 // been TLP retransmitted, or an FEC packet.
739 unacked_packets_.RemoveFromInFlight(sequence_number);
744 bool QuicSentPacketManager::MaybeUpdateRTT(
745 const QuicAckFrame& ack_frame,
746 const QuicTime& ack_receive_time) {
747 // We rely on delta_time_largest_observed to compute an RTT estimate, so we
748 // only update rtt when the largest observed gets acked.
749 // NOTE: If ack is a truncated ack, then the largest observed is in fact
750 // unacked, and may cause an RTT sample to be taken.
751 if (!unacked_packets_.IsUnacked(ack_frame.largest_observed)) {
752 return false;
754 // We calculate the RTT based on the highest ACKed sequence number, the lower
755 // sequence numbers will include the ACK aggregation delay.
756 const TransmissionInfo& transmission_info =
757 unacked_packets_.GetTransmissionInfo(ack_frame.largest_observed);
758 // Ensure the packet has a valid sent time.
759 if (transmission_info.sent_time == QuicTime::Zero()) {
760 LOG(DFATAL) << "Acked packet has zero sent time, largest_observed:"
761 << ack_frame.largest_observed;
762 return false;
765 QuicTime::Delta send_delta =
766 ack_receive_time.Subtract(transmission_info.sent_time);
767 rtt_stats_.UpdateRtt(
768 send_delta, ack_frame.delta_time_largest_observed, ack_receive_time);
770 if (network_change_visitor_ != nullptr) {
771 network_change_visitor_->OnRttChange();
774 return true;
777 QuicTime::Delta QuicSentPacketManager::TimeUntilSend(
778 QuicTime now,
779 HasRetransmittableData retransmittable) {
780 // The TLP logic is entirely contained within QuicSentPacketManager, so the
781 // send algorithm does not need to be consulted.
782 if (pending_timer_transmission_count_ > 0) {
783 return QuicTime::Delta::Zero();
785 return send_algorithm_->TimeUntilSend(
786 now, unacked_packets_.bytes_in_flight(), retransmittable);
789 // Uses a 25ms delayed ack timer. Also helps with better signaling
790 // in low-bandwidth (< ~384 kbps), where an ack is sent per packet.
791 // Ensures that the Delayed Ack timer is always set to a value lesser
792 // than the retransmission timer's minimum value (MinRTO). We want the
793 // delayed ack to get back to the QUIC peer before the sender's
794 // retransmission timer triggers. Since we do not know the
795 // reverse-path one-way delay, we assume equal delays for forward and
796 // reverse paths, and ensure that the timer is set to less than half
797 // of the MinRTO.
798 // There may be a value in making this delay adaptive with the help of
799 // the sender and a signaling mechanism -- if the sender uses a
800 // different MinRTO, we may get spurious retransmissions. May not have
801 // any benefits, but if the delayed ack becomes a significant source
802 // of (likely, tail) latency, then consider such a mechanism.
803 const QuicTime::Delta QuicSentPacketManager::DelayedAckTime() const {
804 return QuicTime::Delta::FromMilliseconds(min(kMaxDelayedAckTimeMs,
805 kMinRetransmissionTimeMs / 2));
808 const QuicTime QuicSentPacketManager::GetRetransmissionTime() const {
809 // Don't set the timer if there are no packets in flight or we've already
810 // queued a tlp transmission and it hasn't been sent yet.
811 if (!unacked_packets_.HasInFlightPackets() ||
812 pending_timer_transmission_count_ > 0) {
813 return QuicTime::Zero();
815 switch (GetRetransmissionMode()) {
816 case HANDSHAKE_MODE:
817 return clock_->ApproximateNow().Add(GetCryptoRetransmissionDelay());
818 case LOSS_MODE:
819 return loss_algorithm_->GetLossTimeout();
820 case TLP_MODE: {
821 // TODO(ianswett): When CWND is available, it would be preferable to
822 // set the timer based on the earliest retransmittable packet.
823 // Base the updated timer on the send time of the last packet.
824 const QuicTime sent_time = unacked_packets_.GetLastPacketSentTime();
825 const QuicTime tlp_time = sent_time.Add(GetTailLossProbeDelay());
826 // Ensure the TLP timer never gets set to a time in the past.
827 return QuicTime::Max(clock_->ApproximateNow(), tlp_time);
829 case RTO_MODE: {
830 // The RTO is based on the first outstanding packet.
831 const QuicTime sent_time = unacked_packets_.GetLastPacketSentTime();
832 QuicTime rto_time = sent_time.Add(GetRetransmissionDelay());
833 // Wait for TLP packets to be acked before an RTO fires.
834 QuicTime tlp_time =
835 unacked_packets_.GetLastPacketSentTime().Add(GetTailLossProbeDelay());
836 return QuicTime::Max(tlp_time, rto_time);
839 DCHECK(false);
840 return QuicTime::Zero();
843 const QuicTime::Delta QuicSentPacketManager::GetCryptoRetransmissionDelay()
844 const {
845 // This is equivalent to the TailLossProbeDelay, but slightly more aggressive
846 // because crypto handshake messages don't incur a delayed ack time.
847 QuicTime::Delta srtt = rtt_stats_.smoothed_rtt();
848 if (srtt.IsZero()) {
849 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats_.initial_rtt_us());
851 int64 delay_ms = max(kMinHandshakeTimeoutMs,
852 static_cast<int64>(1.5 * srtt.ToMilliseconds()));
853 return QuicTime::Delta::FromMilliseconds(
854 delay_ms << consecutive_crypto_retransmission_count_);
857 const QuicTime::Delta QuicSentPacketManager::GetTailLossProbeDelay() const {
858 QuicTime::Delta srtt = rtt_stats_.smoothed_rtt();
859 if (srtt.IsZero()) {
860 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats_.initial_rtt_us());
862 if (!unacked_packets_.HasMultipleInFlightPackets()) {
863 return QuicTime::Delta::Max(
864 srtt.Multiply(2), srtt.Multiply(1.5).Add(
865 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs / 2)));
867 return QuicTime::Delta::FromMilliseconds(
868 max(kMinTailLossProbeTimeoutMs,
869 static_cast<int64>(2 * srtt.ToMilliseconds())));
872 const QuicTime::Delta QuicSentPacketManager::GetRetransmissionDelay() const {
873 QuicTime::Delta retransmission_delay = send_algorithm_->RetransmissionDelay();
874 // TODO(rch): This code should move to |send_algorithm_|.
875 if (retransmission_delay.IsZero()) {
876 // We are in the initial state, use default timeout values.
877 retransmission_delay =
878 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
879 } else if (retransmission_delay.ToMilliseconds() < kMinRetransmissionTimeMs) {
880 retransmission_delay =
881 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
884 // Calculate exponential back off.
885 retransmission_delay = retransmission_delay.Multiply(
886 1 << min<size_t>(consecutive_rto_count_, kMaxRetransmissions));
888 if (retransmission_delay.ToMilliseconds() > kMaxRetransmissionTimeMs) {
889 return QuicTime::Delta::FromMilliseconds(kMaxRetransmissionTimeMs);
891 return retransmission_delay;
894 const RttStats* QuicSentPacketManager::GetRttStats() const {
895 return &rtt_stats_;
898 QuicBandwidth QuicSentPacketManager::BandwidthEstimate() const {
899 // TODO(ianswett): Remove BandwidthEstimate from SendAlgorithmInterface
900 // and implement the logic here.
901 return send_algorithm_->BandwidthEstimate();
904 const QuicSustainedBandwidthRecorder&
905 QuicSentPacketManager::SustainedBandwidthRecorder() const {
906 return sustained_bandwidth_recorder_;
909 QuicPacketCount QuicSentPacketManager::EstimateMaxPacketsInFlight(
910 QuicByteCount max_packet_length) const {
911 return send_algorithm_->GetCongestionWindow() / max_packet_length;
914 QuicPacketCount QuicSentPacketManager::GetCongestionWindowInTcpMss() const {
915 return send_algorithm_->GetCongestionWindow() / kDefaultTCPMSS;
918 QuicByteCount QuicSentPacketManager::GetCongestionWindowInBytes() const {
919 return send_algorithm_->GetCongestionWindow();
922 QuicPacketCount QuicSentPacketManager::GetSlowStartThresholdInTcpMss() const {
923 return send_algorithm_->GetSlowStartThreshold() / kDefaultTCPMSS;
926 void QuicSentPacketManager::OnSerializedPacket(
927 const SerializedPacket& serialized_packet) {
928 ack_notifier_manager_.OnSerializedPacket(serialized_packet);
931 void QuicSentPacketManager::CancelRetransmissionsForStream(
932 QuicStreamId stream_id) {
933 unacked_packets_.CancelRetransmissionsForStream(stream_id);
934 PendingRetransmissionMap::iterator it = pending_retransmissions_.begin();
935 while (it != pending_retransmissions_.end()) {
936 if (HasRetransmittableFrames(it->first)) {
937 ++it;
938 continue;
940 it = pending_retransmissions_.erase(it);
944 void QuicSentPacketManager::EnablePacing() {
945 // TODO(ianswett): Replace with a method which wraps the send algorithm in a
946 // pacer every time a new algorithm is set.
947 if (using_pacing_) {
948 return;
951 // Set up a pacing sender with a 1 millisecond alarm granularity, the same as
952 // the default granularity of the Linux kernel's FQ qdisc.
953 using_pacing_ = true;
954 send_algorithm_.reset(
955 new PacingSender(send_algorithm_.release(),
956 QuicTime::Delta::FromMilliseconds(1),
957 kInitialUnpacedBurst));
960 } // namespace net