Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / net / quic / quic_sent_packet_manager.cc
blob4984f7064dffa742d87813975ebb3ebc4f1026c5
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 enable_half_rtt_tail_loss_probe_(false),
97 using_pacing_(false),
98 use_new_rto_(false),
99 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(kTLPR, perspective_)) {
159 enable_half_rtt_tail_loss_probe_ = true;
161 if (config.HasClientSentConnectionOption(kNRTO, perspective_)) {
162 use_new_rto_ = true;
164 if (config.HasReceivedConnectionOptions() &&
165 ContainsQuicTag(config.ReceivedConnectionOptions(), kTIME)) {
166 loss_algorithm_.reset(LossDetectionInterface::Create(kTime));
168 if (config.HasReceivedSocketReceiveBuffer()) {
169 receive_buffer_bytes_ =
170 max(kMinSocketReceiveBuffer,
171 static_cast<QuicByteCount>(config.ReceivedSocketReceiveBuffer()));
172 QuicByteCount max_cwnd_bytes = static_cast<QuicByteCount>(
173 receive_buffer_bytes_ * kConservativeReceiveBufferFraction);
174 if (FLAGS_quic_limit_max_cwnd) {
175 max_cwnd_bytes =
176 min(max_cwnd_bytes, kMaxCongestionWindow * kDefaultTCPMSS);
178 send_algorithm_->SetMaxCongestionWindow(max_cwnd_bytes);
180 send_algorithm_->SetFromConfig(config, perspective_);
182 if (network_change_visitor_ != nullptr) {
183 network_change_visitor_->OnCongestionWindowChange();
187 void QuicSentPacketManager::ResumeConnectionState(
188 const CachedNetworkParameters& cached_network_params,
189 bool max_bandwidth_resumption) {
190 if (cached_network_params.has_min_rtt_ms()) {
191 uint32 initial_rtt_us =
192 kNumMicrosPerMilli * cached_network_params.min_rtt_ms();
193 rtt_stats_.set_initial_rtt_us(
194 max(kMinInitialRoundTripTimeUs,
195 min(kMaxInitialRoundTripTimeUs, initial_rtt_us)));
197 send_algorithm_->ResumeConnectionState(cached_network_params,
198 max_bandwidth_resumption);
201 void QuicSentPacketManager::SetNumOpenStreams(size_t num_streams) {
202 if (n_connection_simulation_) {
203 // Ensure the number of connections is between 1 and 5.
204 send_algorithm_->SetNumEmulatedConnections(
205 min<size_t>(5, max<size_t>(1, num_streams)));
209 void QuicSentPacketManager::OnIncomingAck(const QuicAckFrame& ack_frame,
210 QuicTime ack_receive_time) {
211 QuicByteCount bytes_in_flight = unacked_packets_.bytes_in_flight();
213 UpdatePacketInformationReceivedByPeer(ack_frame);
214 bool rtt_updated = MaybeUpdateRTT(ack_frame, ack_receive_time);
215 DCHECK_GE(ack_frame.largest_observed, unacked_packets_.largest_observed());
216 unacked_packets_.IncreaseLargestObserved(ack_frame.largest_observed);
218 HandleAckForSentPackets(ack_frame);
219 InvokeLossDetection(ack_receive_time);
220 // Ignore losses in RTO mode.
221 if (consecutive_rto_count_ > 0 && !use_new_rto_) {
222 packets_lost_.clear();
224 MaybeInvokeCongestionEvent(rtt_updated, bytes_in_flight);
225 unacked_packets_.RemoveObsoletePackets();
227 sustained_bandwidth_recorder_.RecordEstimate(
228 send_algorithm_->InRecovery(),
229 send_algorithm_->InSlowStart(),
230 send_algorithm_->BandwidthEstimate(),
231 ack_receive_time,
232 clock_->WallNow(),
233 rtt_stats_.smoothed_rtt());
235 // If we have received a truncated ack, then we need to clear out some
236 // previous transmissions to allow the peer to actually ACK new packets.
237 if (ack_frame.is_truncated && !FLAGS_quic_disable_truncated_ack_handling) {
238 unacked_packets_.ClearAllPreviousRetransmissions();
241 // Anytime we are making forward progress and have a new RTT estimate, reset
242 // the backoff counters.
243 if (rtt_updated) {
244 if (consecutive_rto_count_ > 0) {
245 // If the ack acknowledges data sent prior to the RTO,
246 // the RTO was spurious.
247 if (ack_frame.largest_observed < first_rto_transmission_) {
248 // Replace SRTT with latest_rtt and increase the variance to prevent
249 // a spurious RTO from happening again.
250 rtt_stats_.ExpireSmoothedMetrics();
251 } else {
252 if (!use_new_rto_) {
253 send_algorithm_->OnRetransmissionTimeout(true);
257 // Reset all retransmit counters any time a new packet is acked.
258 consecutive_rto_count_ = 0;
259 consecutive_tlp_count_ = 0;
260 consecutive_crypto_retransmission_count_ = 0;
263 if (debug_delegate_ != nullptr) {
264 debug_delegate_->OnIncomingAck(ack_frame, ack_receive_time,
265 unacked_packets_.largest_observed(),
266 rtt_updated, GetLeastUnacked());
270 void QuicSentPacketManager::UpdatePacketInformationReceivedByPeer(
271 const QuicAckFrame& ack_frame) {
272 if (ack_frame.missing_packets.Empty()) {
273 least_packet_awaited_by_peer_ = ack_frame.largest_observed + 1;
274 } else {
275 least_packet_awaited_by_peer_ = ack_frame.missing_packets.Min();
279 void QuicSentPacketManager::MaybeInvokeCongestionEvent(
280 bool rtt_updated, QuicByteCount bytes_in_flight) {
281 if (!rtt_updated && packets_acked_.empty() && packets_lost_.empty()) {
282 return;
284 send_algorithm_->OnCongestionEvent(rtt_updated, bytes_in_flight,
285 packets_acked_, packets_lost_);
286 packets_acked_.clear();
287 packets_lost_.clear();
288 if (network_change_visitor_ != nullptr) {
289 network_change_visitor_->OnCongestionWindowChange();
293 void QuicSentPacketManager::HandleAckForSentPackets(
294 const QuicAckFrame& ack_frame) {
295 // Go through the packets we have not received an ack for and see if this
296 // incoming_ack shows they've been seen by the peer.
297 QuicTime::Delta delta_largest_observed =
298 ack_frame.delta_time_largest_observed;
299 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
300 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
301 it != unacked_packets_.end(); ++it, ++packet_number) {
302 if (packet_number > ack_frame.largest_observed) {
303 // These packets are still in flight.
304 break;
307 if (ack_frame.missing_packets.Contains(packet_number)) {
308 // Don't continue to increase the nack count for packets not in flight.
309 if (!it->in_flight) {
310 continue;
312 // Consider it multiple nacks when there is a gap between the missing
313 // packet and the largest observed, since the purpose of a nack
314 // threshold is to tolerate re-ordering. This handles both StretchAcks
315 // and Forward Acks.
316 // The nack count only increases when the largest observed increases.
317 QuicPacketCount min_nacks = ack_frame.largest_observed - packet_number;
318 // Truncated acks can nack the largest observed, so use a min of 1.
319 if (min_nacks == 0) {
320 min_nacks = 1;
322 unacked_packets_.NackPacket(packet_number, min_nacks);
323 continue;
325 // Packet was acked, so remove it from our unacked packet list.
326 DVLOG(1) << ENDPOINT << "Got an ack for packet " << packet_number;
327 // If data is associated with the most recent transmission of this
328 // packet, then inform the caller.
329 if (it->in_flight) {
330 packets_acked_.push_back(std::make_pair(packet_number, *it));
332 MarkPacketHandled(packet_number, *it, delta_largest_observed);
335 // Discard any retransmittable frames associated with revived packets.
336 for (PacketNumberSet::const_iterator revived_it =
337 ack_frame.revived_packets.begin();
338 revived_it != ack_frame.revived_packets.end(); ++revived_it) {
339 MarkPacketRevived(*revived_it, delta_largest_observed);
343 bool QuicSentPacketManager::HasRetransmittableFrames(
344 QuicPacketNumber packet_number) const {
345 return unacked_packets_.HasRetransmittableFrames(packet_number);
348 void QuicSentPacketManager::RetransmitUnackedPackets(
349 TransmissionType retransmission_type) {
350 DCHECK(retransmission_type == ALL_UNACKED_RETRANSMISSION ||
351 retransmission_type == ALL_INITIAL_RETRANSMISSION);
352 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
353 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
354 it != unacked_packets_.end(); ++it, ++packet_number) {
355 const RetransmittableFrames* frames = it->retransmittable_frames;
356 if (frames != nullptr &&
357 (retransmission_type == ALL_UNACKED_RETRANSMISSION ||
358 frames->encryption_level() == ENCRYPTION_INITIAL)) {
359 MarkForRetransmission(packet_number, retransmission_type);
360 } else if (it->is_fec_packet) {
361 // Remove FEC packets from the packet map, since we can't retransmit them.
362 unacked_packets_.RemoveFromInFlight(packet_number);
367 void QuicSentPacketManager::NeuterUnencryptedPackets() {
368 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
369 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
370 it != unacked_packets_.end(); ++it, ++packet_number) {
371 const RetransmittableFrames* frames = it->retransmittable_frames;
372 if (frames != nullptr && frames->encryption_level() == ENCRYPTION_NONE) {
373 // Once you're forward secure, no unencrypted packets will be sent, crypto
374 // or otherwise. Unencrypted packets are neutered and abandoned, to ensure
375 // they are not retransmitted or considered lost from a congestion control
376 // perspective.
377 pending_retransmissions_.erase(packet_number);
378 unacked_packets_.RemoveFromInFlight(packet_number);
379 unacked_packets_.RemoveRetransmittability(packet_number);
384 void QuicSentPacketManager::MarkForRetransmission(
385 QuicPacketNumber packet_number,
386 TransmissionType transmission_type) {
387 const TransmissionInfo& transmission_info =
388 unacked_packets_.GetTransmissionInfo(packet_number);
389 LOG_IF(DFATAL, transmission_info.retransmittable_frames == nullptr);
390 // Both TLP and the new RTO leave the packets in flight and let the loss
391 // detection decide if packets are lost.
392 if (transmission_type != TLP_RETRANSMISSION &&
393 transmission_type != RTO_RETRANSMISSION) {
394 unacked_packets_.RemoveFromInFlight(packet_number);
396 // TODO(ianswett): Currently the RTO can fire while there are pending NACK
397 // retransmissions for the same data, which is not ideal.
398 if (ContainsKey(pending_retransmissions_, packet_number)) {
399 return;
402 pending_retransmissions_[packet_number] = transmission_type;
405 void QuicSentPacketManager::RecordSpuriousRetransmissions(
406 const PacketNumberList& all_transmissions,
407 QuicPacketNumber acked_packet_number) {
408 for (PacketNumberList::const_reverse_iterator it = all_transmissions.rbegin();
409 it != all_transmissions.rend() && *it > acked_packet_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 QuicPacketNumber packet_number = pending_retransmissions_.begin()->first;
440 TransmissionType transmission_type = pending_retransmissions_.begin()->second;
441 if (unacked_packets_.HasPendingCryptoPackets()) {
442 // Ensure crypto packets are retransmitted before other packets.
443 for (const auto& pair : pending_retransmissions_) {
444 if (HasCryptoHandshake(
445 unacked_packets_.GetTransmissionInfo(pair.first))) {
446 packet_number = pair.first;
447 transmission_type = pair.second;
448 break;
452 DCHECK(unacked_packets_.IsUnacked(packet_number)) << packet_number;
453 const TransmissionInfo& transmission_info =
454 unacked_packets_.GetTransmissionInfo(packet_number);
455 DCHECK(transmission_info.retransmittable_frames);
457 return PendingRetransmission(packet_number, transmission_type,
458 *transmission_info.retransmittable_frames,
459 transmission_info.packet_number_length);
462 void QuicSentPacketManager::MarkPacketRevived(
463 QuicPacketNumber packet_number,
464 QuicTime::Delta delta_largest_observed) {
465 if (!unacked_packets_.IsUnacked(packet_number)) {
466 return;
469 const TransmissionInfo& transmission_info =
470 unacked_packets_.GetTransmissionInfo(packet_number);
471 QuicPacketNumber newest_transmission =
472 transmission_info.all_transmissions == nullptr
473 ? packet_number
474 : *transmission_info.all_transmissions->rbegin();
475 // This packet has been revived at the receiver. If we were going to
476 // retransmit it, do not retransmit it anymore.
477 pending_retransmissions_.erase(newest_transmission);
479 // The AckNotifierManager needs to be notified for revived packets,
480 // since it indicates the packet arrived from the appliction's perspective.
481 ack_notifier_manager_.OnPacketAcked(newest_transmission,
482 delta_largest_observed);
484 unacked_packets_.RemoveRetransmittability(packet_number);
487 void QuicSentPacketManager::MarkPacketHandled(
488 QuicPacketNumber packet_number,
489 const TransmissionInfo& info,
490 QuicTime::Delta delta_largest_observed) {
491 QuicPacketNumber newest_transmission =
492 info.all_transmissions == nullptr ? packet_number
493 : *info.all_transmissions->rbegin();
494 // Remove the most recent packet, if it is pending retransmission.
495 pending_retransmissions_.erase(newest_transmission);
497 // The AckNotifierManager needs to be notified about the most recent
498 // transmission, since that's the one only one it tracks.
499 ack_notifier_manager_.OnPacketAcked(newest_transmission,
500 delta_largest_observed);
501 if (newest_transmission != packet_number) {
502 RecordSpuriousRetransmissions(*info.all_transmissions, packet_number);
503 // Remove the most recent packet from flight if it's a crypto handshake
504 // packet, since they won't be acked now that one has been processed.
505 // Other crypto handshake packets won't be in flight, only the newest
506 // transmission of a crypto packet is in flight at once.
507 // TODO(ianswett): Instead of handling all crypto packets special,
508 // only handle nullptr encrypted packets in a special way.
509 if (HasCryptoHandshake(
510 unacked_packets_.GetTransmissionInfo(newest_transmission))) {
511 unacked_packets_.RemoveFromInFlight(newest_transmission);
515 unacked_packets_.RemoveFromInFlight(packet_number);
516 unacked_packets_.RemoveRetransmittability(packet_number);
519 bool QuicSentPacketManager::IsUnacked(QuicPacketNumber packet_number) const {
520 return unacked_packets_.IsUnacked(packet_number);
523 bool QuicSentPacketManager::HasUnackedPackets() const {
524 return unacked_packets_.HasUnackedPackets();
527 QuicPacketNumber QuicSentPacketManager::GetLeastUnacked() const {
528 return unacked_packets_.GetLeastUnacked();
531 bool QuicSentPacketManager::OnPacketSent(
532 SerializedPacket* serialized_packet,
533 QuicPacketNumber original_packet_number,
534 QuicTime sent_time,
535 QuicByteCount bytes,
536 TransmissionType transmission_type,
537 HasRetransmittableData has_retransmittable_data) {
538 QuicPacketNumber packet_number = serialized_packet->packet_number;
539 DCHECK_LT(0u, packet_number);
540 DCHECK(!unacked_packets_.IsUnacked(packet_number));
541 LOG_IF(DFATAL, bytes == 0) << "Cannot send empty packets.";
543 if (original_packet_number != 0) {
544 PendingRetransmissionMap::iterator it =
545 pending_retransmissions_.find(original_packet_number);
546 if (it != pending_retransmissions_.end()) {
547 pending_retransmissions_.erase(it);
548 } else {
549 DLOG(DFATAL) << "Expected packet number to be in "
550 << "pending_retransmissions_. packet_number: "
551 << original_packet_number;
553 // Inform the ack notifier of retransmissions so it can calculate the
554 // retransmit rate.
555 ack_notifier_manager_.OnPacketRetransmitted(original_packet_number,
556 packet_number, bytes);
559 if (pending_timer_transmission_count_ > 0) {
560 --pending_timer_transmission_count_;
563 // Only track packets as in flight that the send algorithm wants us to track.
564 // Since FEC packets should also be counted towards the congestion window,
565 // consider them as retransmittable for the purposes of congestion control.
566 HasRetransmittableData has_congestion_controlled_data =
567 serialized_packet->is_fec_packet ? HAS_RETRANSMITTABLE_DATA
568 : has_retransmittable_data;
569 const bool in_flight = send_algorithm_->OnPacketSent(
570 sent_time, unacked_packets_.bytes_in_flight(), packet_number, bytes,
571 has_congestion_controlled_data);
573 unacked_packets_.AddSentPacket(*serialized_packet, original_packet_number,
574 transmission_type, sent_time, bytes,
575 in_flight);
577 // Take ownership of the retransmittable frames before exiting.
578 serialized_packet->retransmittable_frames = nullptr;
579 // Reset the retransmission timer anytime a pending packet is sent.
580 return in_flight;
583 void QuicSentPacketManager::OnRetransmissionTimeout() {
584 DCHECK(unacked_packets_.HasInFlightPackets());
585 DCHECK_EQ(0u, pending_timer_transmission_count_);
586 // Handshake retransmission, timer based loss detection, TLP, and RTO are
587 // implemented with a single alarm. The handshake alarm is set when the
588 // handshake has not completed, the loss alarm is set when the loss detection
589 // algorithm says to, and the TLP and RTO alarms are set after that.
590 // The TLP alarm is always set to run for under an RTO.
591 switch (GetRetransmissionMode()) {
592 case HANDSHAKE_MODE:
593 ++stats_->crypto_retransmit_count;
594 RetransmitCryptoPackets();
595 return;
596 case LOSS_MODE: {
597 ++stats_->loss_timeout_count;
598 QuicByteCount bytes_in_flight = unacked_packets_.bytes_in_flight();
599 InvokeLossDetection(clock_->Now());
600 MaybeInvokeCongestionEvent(false, bytes_in_flight);
601 return;
603 case TLP_MODE:
604 // If no tail loss probe can be sent, because there are no retransmittable
605 // packets, execute a conventional RTO to abandon old packets.
606 ++stats_->tlp_count;
607 ++consecutive_tlp_count_;
608 pending_timer_transmission_count_ = 1;
609 // TLPs prefer sending new data instead of retransmitting data, so
610 // give the connection a chance to write before completing the TLP.
611 return;
612 case RTO_MODE:
613 ++stats_->rto_count;
614 RetransmitRtoPackets();
615 return;
619 void QuicSentPacketManager::RetransmitCryptoPackets() {
620 DCHECK_EQ(HANDSHAKE_MODE, GetRetransmissionMode());
621 ++consecutive_crypto_retransmission_count_;
622 bool packet_retransmitted = false;
623 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
624 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
625 it != unacked_packets_.end(); ++it, ++packet_number) {
626 // Only retransmit frames which are in flight, and therefore have been sent.
627 if (!it->in_flight || it->retransmittable_frames == nullptr ||
628 it->retransmittable_frames->HasCryptoHandshake() != IS_HANDSHAKE) {
629 continue;
631 packet_retransmitted = true;
632 MarkForRetransmission(packet_number, HANDSHAKE_RETRANSMISSION);
633 ++pending_timer_transmission_count_;
635 DCHECK(packet_retransmitted) << "No crypto packets found to retransmit.";
638 bool QuicSentPacketManager::MaybeRetransmitTailLossProbe() {
639 if (pending_timer_transmission_count_ == 0) {
640 return false;
642 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
643 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
644 it != unacked_packets_.end(); ++it, ++packet_number) {
645 // Only retransmit frames which are in flight, and therefore have been sent.
646 if (!it->in_flight || it->retransmittable_frames == nullptr) {
647 continue;
649 if (!handshake_confirmed_) {
650 DCHECK_NE(IS_HANDSHAKE, it->retransmittable_frames->HasCryptoHandshake());
652 MarkForRetransmission(packet_number, TLP_RETRANSMISSION);
653 return true;
655 DLOG(ERROR)
656 << "No retransmittable packets, so RetransmitOldestPacket failed.";
657 return false;
660 void QuicSentPacketManager::RetransmitRtoPackets() {
661 LOG_IF(DFATAL, pending_timer_transmission_count_ > 0)
662 << "Retransmissions already queued:" << pending_timer_transmission_count_;
663 // Mark two packets for retransmission.
664 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
665 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
666 it != unacked_packets_.end(); ++it, ++packet_number) {
667 if (it->retransmittable_frames != nullptr &&
668 pending_timer_transmission_count_ < kMaxRetransmissionsOnTimeout) {
669 MarkForRetransmission(packet_number, RTO_RETRANSMISSION);
670 ++pending_timer_transmission_count_;
672 // Abandon non-retransmittable data that's in flight to ensure it doesn't
673 // fill up the congestion window.
674 if (it->retransmittable_frames == nullptr && it->in_flight &&
675 it->all_transmissions == nullptr) {
676 unacked_packets_.RemoveFromInFlight(packet_number);
679 if (pending_timer_transmission_count_ > 0) {
680 if (consecutive_rto_count_ == 0) {
681 first_rto_transmission_ = unacked_packets_.largest_sent_packet() + 1;
683 ++consecutive_rto_count_;
687 QuicSentPacketManager::RetransmissionTimeoutMode
688 QuicSentPacketManager::GetRetransmissionMode() const {
689 DCHECK(unacked_packets_.HasInFlightPackets());
690 if (!handshake_confirmed_ && unacked_packets_.HasPendingCryptoPackets()) {
691 return HANDSHAKE_MODE;
693 if (loss_algorithm_->GetLossTimeout() != QuicTime::Zero()) {
694 return LOSS_MODE;
696 if (consecutive_tlp_count_ < max_tail_loss_probes_) {
697 if (unacked_packets_.HasUnackedRetransmittableFrames()) {
698 return TLP_MODE;
701 return RTO_MODE;
704 void QuicSentPacketManager::InvokeLossDetection(QuicTime time) {
705 PacketNumberSet lost_packets = loss_algorithm_->DetectLostPackets(
706 unacked_packets_, time, unacked_packets_.largest_observed(), rtt_stats_);
707 for (PacketNumberSet::const_iterator it = lost_packets.begin();
708 it != lost_packets.end(); ++it) {
709 QuicPacketNumber packet_number = *it;
710 const TransmissionInfo& transmission_info =
711 unacked_packets_.GetTransmissionInfo(packet_number);
712 // TODO(ianswett): If it's expected the FEC packet may repair the loss, it
713 // should be recorded as a loss to the send algorithm, but not retransmitted
714 // until it's known whether the FEC packet arrived.
715 ++stats_->packets_lost;
716 packets_lost_.push_back(std::make_pair(packet_number, transmission_info));
717 DVLOG(1) << ENDPOINT << "Lost packet " << packet_number;
719 if (transmission_info.retransmittable_frames != nullptr) {
720 MarkForRetransmission(packet_number, LOSS_RETRANSMISSION);
721 } else {
722 // Since we will not retransmit this, we need to remove it from
723 // unacked_packets_. This is either the current transmission of
724 // a packet whose previous transmission has been acked, a packet that has
725 // been TLP retransmitted, or an FEC packet.
726 unacked_packets_.RemoveFromInFlight(packet_number);
731 bool QuicSentPacketManager::MaybeUpdateRTT(
732 const QuicAckFrame& ack_frame,
733 const QuicTime& ack_receive_time) {
734 // We rely on delta_time_largest_observed to compute an RTT estimate, so we
735 // only update rtt when the largest observed gets acked.
736 // NOTE: If ack is a truncated ack, then the largest observed is in fact
737 // unacked, and may cause an RTT sample to be taken.
738 if (!unacked_packets_.IsUnacked(ack_frame.largest_observed)) {
739 return false;
741 // We calculate the RTT based on the highest ACKed packet number, the lower
742 // packet numbers will include the ACK aggregation delay.
743 const TransmissionInfo& transmission_info =
744 unacked_packets_.GetTransmissionInfo(ack_frame.largest_observed);
745 // Ensure the packet has a valid sent time.
746 if (transmission_info.sent_time == QuicTime::Zero()) {
747 LOG(DFATAL) << "Acked packet has zero sent time, largest_observed:"
748 << ack_frame.largest_observed;
749 return false;
752 QuicTime::Delta send_delta =
753 ack_receive_time.Subtract(transmission_info.sent_time);
754 rtt_stats_.UpdateRtt(
755 send_delta, ack_frame.delta_time_largest_observed, ack_receive_time);
757 if (network_change_visitor_ != nullptr) {
758 network_change_visitor_->OnRttChange();
761 return true;
764 QuicTime::Delta QuicSentPacketManager::TimeUntilSend(
765 QuicTime now,
766 HasRetransmittableData retransmittable) {
767 // The TLP logic is entirely contained within QuicSentPacketManager, so the
768 // send algorithm does not need to be consulted.
769 if (pending_timer_transmission_count_ > 0) {
770 return QuicTime::Delta::Zero();
772 return send_algorithm_->TimeUntilSend(
773 now, unacked_packets_.bytes_in_flight(), retransmittable);
776 // Uses a 25ms delayed ack timer. Also helps with better signaling
777 // in low-bandwidth (< ~384 kbps), where an ack is sent per packet.
778 // Ensures that the Delayed Ack timer is always set to a value lesser
779 // than the retransmission timer's minimum value (MinRTO). We want the
780 // delayed ack to get back to the QUIC peer before the sender's
781 // retransmission timer triggers. Since we do not know the
782 // reverse-path one-way delay, we assume equal delays for forward and
783 // reverse paths, and ensure that the timer is set to less than half
784 // of the MinRTO.
785 // There may be a value in making this delay adaptive with the help of
786 // the sender and a signaling mechanism -- if the sender uses a
787 // different MinRTO, we may get spurious retransmissions. May not have
788 // any benefits, but if the delayed ack becomes a significant source
789 // of (likely, tail) latency, then consider such a mechanism.
790 const QuicTime::Delta QuicSentPacketManager::DelayedAckTime() const {
791 return QuicTime::Delta::FromMilliseconds(min(kMaxDelayedAckTimeMs,
792 kMinRetransmissionTimeMs / 2));
795 const QuicTime QuicSentPacketManager::GetRetransmissionTime() const {
796 // Don't set the timer if there are no packets in flight or we've already
797 // queued a tlp transmission and it hasn't been sent yet.
798 if (!unacked_packets_.HasInFlightPackets() ||
799 pending_timer_transmission_count_ > 0) {
800 return QuicTime::Zero();
802 switch (GetRetransmissionMode()) {
803 case HANDSHAKE_MODE:
804 return clock_->ApproximateNow().Add(GetCryptoRetransmissionDelay());
805 case LOSS_MODE:
806 return loss_algorithm_->GetLossTimeout();
807 case TLP_MODE: {
808 // TODO(ianswett): When CWND is available, it would be preferable to
809 // set the timer based on the earliest retransmittable packet.
810 // Base the updated timer on the send time of the last packet.
811 const QuicTime sent_time = unacked_packets_.GetLastPacketSentTime();
812 const QuicTime tlp_time = sent_time.Add(GetTailLossProbeDelay());
813 // Ensure the TLP timer never gets set to a time in the past.
814 return QuicTime::Max(clock_->ApproximateNow(), tlp_time);
816 case RTO_MODE: {
817 // The RTO is based on the first outstanding packet.
818 const QuicTime sent_time = unacked_packets_.GetLastPacketSentTime();
819 QuicTime rto_time = sent_time.Add(GetRetransmissionDelay());
820 // Wait for TLP packets to be acked before an RTO fires.
821 QuicTime tlp_time =
822 unacked_packets_.GetLastPacketSentTime().Add(GetTailLossProbeDelay());
823 return QuicTime::Max(tlp_time, rto_time);
826 DCHECK(false);
827 return QuicTime::Zero();
830 const QuicTime::Delta QuicSentPacketManager::GetCryptoRetransmissionDelay()
831 const {
832 // This is equivalent to the TailLossProbeDelay, but slightly more aggressive
833 // because crypto handshake messages don't incur a delayed ack time.
834 QuicTime::Delta srtt = rtt_stats_.smoothed_rtt();
835 if (srtt.IsZero()) {
836 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats_.initial_rtt_us());
838 int64 delay_ms = max(kMinHandshakeTimeoutMs,
839 static_cast<int64>(1.5 * srtt.ToMilliseconds()));
840 return QuicTime::Delta::FromMilliseconds(
841 delay_ms << consecutive_crypto_retransmission_count_);
844 const QuicTime::Delta QuicSentPacketManager::GetTailLossProbeDelay() const {
845 QuicTime::Delta srtt = rtt_stats_.smoothed_rtt();
846 if (srtt.IsZero()) {
847 srtt = QuicTime::Delta::FromMicroseconds(rtt_stats_.initial_rtt_us());
849 if (enable_half_rtt_tail_loss_probe_ && consecutive_tlp_count_ == 0u) {
850 return QuicTime::Delta::FromMilliseconds(
851 max(kMinTailLossProbeTimeoutMs,
852 static_cast<int64>(0.5 * srtt.ToMilliseconds())));
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 if (retransmission_delay.IsZero()) {
867 // We are in the initial state, use default timeout values.
868 retransmission_delay =
869 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
870 } else if (retransmission_delay.ToMilliseconds() < kMinRetransmissionTimeMs) {
871 retransmission_delay =
872 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs);
875 // Calculate exponential back off.
876 retransmission_delay = retransmission_delay.Multiply(
877 1 << min<size_t>(consecutive_rto_count_, kMaxRetransmissions));
879 if (retransmission_delay.ToMilliseconds() > kMaxRetransmissionTimeMs) {
880 return QuicTime::Delta::FromMilliseconds(kMaxRetransmissionTimeMs);
882 return retransmission_delay;
885 const RttStats* QuicSentPacketManager::GetRttStats() const {
886 return &rtt_stats_;
889 QuicBandwidth QuicSentPacketManager::BandwidthEstimate() const {
890 // TODO(ianswett): Remove BandwidthEstimate from SendAlgorithmInterface
891 // and implement the logic here.
892 return send_algorithm_->BandwidthEstimate();
895 const QuicSustainedBandwidthRecorder&
896 QuicSentPacketManager::SustainedBandwidthRecorder() const {
897 return sustained_bandwidth_recorder_;
900 QuicPacketCount QuicSentPacketManager::EstimateMaxPacketsInFlight(
901 QuicByteCount max_packet_length) const {
902 return send_algorithm_->GetCongestionWindow() / max_packet_length;
905 QuicPacketCount QuicSentPacketManager::GetCongestionWindowInTcpMss() const {
906 return send_algorithm_->GetCongestionWindow() / kDefaultTCPMSS;
909 QuicByteCount QuicSentPacketManager::GetCongestionWindowInBytes() const {
910 return send_algorithm_->GetCongestionWindow();
913 QuicPacketCount QuicSentPacketManager::GetSlowStartThresholdInTcpMss() const {
914 return send_algorithm_->GetSlowStartThreshold() / kDefaultTCPMSS;
917 void QuicSentPacketManager::OnSerializedPacket(
918 const SerializedPacket& serialized_packet) {
919 ack_notifier_manager_.OnSerializedPacket(serialized_packet);
922 void QuicSentPacketManager::CancelRetransmissionsForStream(
923 QuicStreamId stream_id) {
924 unacked_packets_.CancelRetransmissionsForStream(stream_id);
925 PendingRetransmissionMap::iterator it = pending_retransmissions_.begin();
926 while (it != pending_retransmissions_.end()) {
927 if (HasRetransmittableFrames(it->first)) {
928 ++it;
929 continue;
931 it = pending_retransmissions_.erase(it);
935 void QuicSentPacketManager::EnablePacing() {
936 // TODO(ianswett): Replace with a method which wraps the send algorithm in a
937 // pacer every time a new algorithm is set.
938 if (using_pacing_) {
939 return;
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));
951 } // namespace net