blob: e078f5f6f449ff8318a20256d67ea9922346c1c6 [file] [log] [blame]
QUICHE teama6ef0a62019-03-07 20:34:33 -05001// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "net/third_party/quiche/src/quic/core/quic_sent_packet_manager.h"
6
7#include <algorithm>
vasilvv872e7a32019-03-12 16:42:44 -07008#include <string>
QUICHE teama6ef0a62019-03-07 20:34:33 -05009
10#include "net/third_party/quiche/src/quic/core/congestion_control/general_loss_algorithm.h"
11#include "net/third_party/quiche/src/quic/core/congestion_control/pacing_sender.h"
12#include "net/third_party/quiche/src/quic/core/crypto/crypto_protocol.h"
13#include "net/third_party/quiche/src/quic/core/proto/cached_network_parameters.pb.h"
14#include "net/third_party/quiche/src/quic/core/quic_connection_stats.h"
15#include "net/third_party/quiche/src/quic/core/quic_pending_retransmission.h"
16#include "net/third_party/quiche/src/quic/core/quic_utils.h"
17#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
18#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
19#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
20#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
21#include "net/third_party/quiche/src/quic/platform/api/quic_map_util.h"
QUICHE teama6ef0a62019-03-07 20:34:33 -050022
23namespace quic {
24
25namespace {
26static const int64_t kDefaultRetransmissionTimeMs = 500;
27static const int64_t kMaxRetransmissionTimeMs = 60000;
28// Maximum number of exponential backoffs used for RTO timeouts.
29static const size_t kMaxRetransmissions = 10;
30// Maximum number of packets retransmitted upon an RTO.
31static const size_t kMaxRetransmissionsOnTimeout = 2;
32// The path degrading delay is the sum of this number of consecutive RTO delays.
33const size_t kNumRetransmissionDelaysForPathDegradingDelay = 2;
34
35// Ensure the handshake timer isnt't faster than 10ms.
36// This limits the tenth retransmitted packet to 10s after the initial CHLO.
37static const int64_t kMinHandshakeTimeoutMs = 10;
38
39// Sends up to two tail loss probes before firing an RTO,
40// per draft RFC draft-dukkipati-tcpm-tcp-loss-probe.
41static const size_t kDefaultMaxTailLossProbes = 2;
42
43inline bool HasCryptoHandshake(const QuicTransmissionInfo& transmission_info) {
44 DCHECK(!transmission_info.has_crypto_handshake ||
45 !transmission_info.retransmittable_frames.empty());
46 return transmission_info.has_crypto_handshake;
47}
48
49// Returns true if retransmissions the specified type leave the data in flight.
50inline bool RetransmissionLeavesBytesInFlight(
51 TransmissionType transmission_type) {
52 // Both TLP and the new RTO leave the packets in flight and let the loss
53 // detection decide if packets are lost.
54 return transmission_type == TLP_RETRANSMISSION ||
55 transmission_type == PROBING_RETRANSMISSION ||
56 transmission_type == RTO_RETRANSMISSION;
57}
58
59// Returns true of retransmissions of the specified type should retransmit
60// the frames directly (as opposed to resulting in a loss notification).
61inline bool ShouldForceRetransmission(TransmissionType transmission_type) {
62 return transmission_type == HANDSHAKE_RETRANSMISSION ||
63 transmission_type == TLP_RETRANSMISSION ||
64 transmission_type == PROBING_RETRANSMISSION ||
65 transmission_type == RTO_RETRANSMISSION;
66}
67
68} // namespace
69
70#define ENDPOINT \
71 (unacked_packets_.perspective() == Perspective::IS_SERVER ? "Server: " \
72 : "Client: ")
73
74QuicSentPacketManager::QuicSentPacketManager(
75 Perspective perspective,
76 const QuicClock* clock,
77 QuicConnectionStats* stats,
78 CongestionControlType congestion_control_type,
79 LossDetectionType loss_type)
80 : unacked_packets_(perspective),
81 clock_(clock),
82 stats_(stats),
83 debug_delegate_(nullptr),
84 network_change_visitor_(nullptr),
85 initial_congestion_window_(kInitialCongestionWindow),
86 loss_algorithm_(
87 unacked_packets_.use_uber_loss_algorithm()
88 ? dynamic_cast<LossDetectionInterface*>(&uber_loss_algorithm_)
89 : dynamic_cast<LossDetectionInterface*>(
90 &general_loss_algorithm_)),
91 general_loss_algorithm_(loss_type),
92 uber_loss_algorithm_(loss_type),
93 consecutive_rto_count_(0),
94 consecutive_tlp_count_(0),
95 consecutive_crypto_retransmission_count_(0),
96 pending_timer_transmission_count_(0),
97 max_tail_loss_probes_(kDefaultMaxTailLossProbes),
98 max_rto_packets_(kMaxRetransmissionsOnTimeout),
99 enable_half_rtt_tail_loss_probe_(false),
100 using_pacing_(false),
101 use_new_rto_(false),
102 conservative_handshake_retransmits_(false),
103 min_tlp_timeout_(
104 QuicTime::Delta::FromMilliseconds(kMinTailLossProbeTimeoutMs)),
105 min_rto_timeout_(
106 QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs)),
107 ietf_style_tlp_(false),
108 ietf_style_2x_tlp_(false),
109 largest_mtu_acked_(0),
110 handshake_confirmed_(false),
111 delayed_ack_time_(
112 QuicTime::Delta::FromMilliseconds(kDefaultDelayedAckTimeMs)),
113 rtt_updated_(false),
QUICHE team9929cc42019-03-13 08:17:43 -0700114 acked_packets_iter_(last_ack_frame_.packets.rbegin()),
115 tolerate_reneging_(GetQuicReloadableFlag(quic_tolerate_reneging)) {
116 if (tolerate_reneging_) {
117 QUIC_RELOADABLE_FLAG_COUNT(quic_tolerate_reneging);
118 }
QUICHE teama6ef0a62019-03-07 20:34:33 -0500119 SetSendAlgorithm(congestion_control_type);
120}
121
122QuicSentPacketManager::~QuicSentPacketManager() {}
123
124void QuicSentPacketManager::SetFromConfig(const QuicConfig& config) {
125 const Perspective perspective = unacked_packets_.perspective();
126 if (config.HasReceivedInitialRoundTripTimeUs() &&
127 config.ReceivedInitialRoundTripTimeUs() > 0) {
128 if (!config.HasClientSentConnectionOption(kNRTT, perspective)) {
129 SetInitialRtt(QuicTime::Delta::FromMicroseconds(
130 config.ReceivedInitialRoundTripTimeUs()));
131 }
132 } else if (config.HasInitialRoundTripTimeUsToSend() &&
133 config.GetInitialRoundTripTimeUsToSend() > 0) {
134 SetInitialRtt(QuicTime::Delta::FromMicroseconds(
135 config.GetInitialRoundTripTimeUsToSend()));
136 }
137 if (config.HasClientSentConnectionOption(kMAD0, perspective)) {
138 rtt_stats_.set_ignore_max_ack_delay(true);
139 }
140 if (config.HasClientSentConnectionOption(kMAD1, perspective)) {
141 rtt_stats_.set_initial_max_ack_delay(delayed_ack_time_);
142 }
143 if (config.HasClientSentConnectionOption(kMAD2, perspective)) {
144 min_tlp_timeout_ = QuicTime::Delta::Zero();
145 }
146 if (config.HasClientSentConnectionOption(kMAD3, perspective)) {
147 min_rto_timeout_ = QuicTime::Delta::Zero();
148 }
149 if (config.HasClientSentConnectionOption(kMAD4, perspective)) {
150 ietf_style_tlp_ = true;
151 }
152 if (config.HasClientSentConnectionOption(kMAD5, perspective)) {
153 ietf_style_2x_tlp_ = true;
154 }
155
156 // Configure congestion control.
157 if (config.HasClientRequestedIndependentOption(kTBBR, perspective)) {
158 SetSendAlgorithm(kBBR);
159 }
160 if (config.HasClientRequestedIndependentOption(kRENO, perspective)) {
161 SetSendAlgorithm(kRenoBytes);
162 } else if (config.HasClientRequestedIndependentOption(kBYTE, perspective) ||
163 (GetQuicReloadableFlag(quic_default_to_bbr) &&
164 config.HasClientRequestedIndependentOption(kQBIC, perspective))) {
165 SetSendAlgorithm(kCubicBytes);
166 } else if (GetQuicReloadableFlag(quic_enable_pcc3) &&
167 config.HasClientRequestedIndependentOption(kTPCC, perspective)) {
168 SetSendAlgorithm(kPCC);
169 }
170 // Initial window.
171 if (GetQuicReloadableFlag(quic_unified_iw_options)) {
172 if (config.HasClientRequestedIndependentOption(kIW03, perspective)) {
173 initial_congestion_window_ = 3;
174 send_algorithm_->SetInitialCongestionWindowInPackets(3);
175 }
176 if (config.HasClientRequestedIndependentOption(kIW10, perspective)) {
177 initial_congestion_window_ = 10;
178 send_algorithm_->SetInitialCongestionWindowInPackets(10);
179 }
180 if (config.HasClientRequestedIndependentOption(kIW20, perspective)) {
181 initial_congestion_window_ = 20;
182 send_algorithm_->SetInitialCongestionWindowInPackets(20);
183 }
184 if (config.HasClientRequestedIndependentOption(kIW50, perspective)) {
185 initial_congestion_window_ = 50;
186 send_algorithm_->SetInitialCongestionWindowInPackets(50);
187 }
188 }
189
190 using_pacing_ = !FLAGS_quic_disable_pacing_for_perf_tests;
191
192 if (config.HasClientSentConnectionOption(k1CON, perspective)) {
193 send_algorithm_->SetNumEmulatedConnections(1);
194 }
195 if (config.HasClientSentConnectionOption(kNTLP, perspective)) {
196 max_tail_loss_probes_ = 0;
197 }
198 if (config.HasClientSentConnectionOption(k1TLP, perspective)) {
199 max_tail_loss_probes_ = 1;
200 }
201 if (config.HasClientSentConnectionOption(k1RTO, perspective)) {
202 max_rto_packets_ = 1;
203 }
204 if (config.HasClientSentConnectionOption(kTLPR, perspective)) {
205 enable_half_rtt_tail_loss_probe_ = true;
206 }
207 if (config.HasClientSentConnectionOption(kNRTO, perspective)) {
208 use_new_rto_ = true;
209 }
210 // Configure loss detection.
211 if (config.HasClientRequestedIndependentOption(kTIME, perspective)) {
212 if (unacked_packets_.use_uber_loss_algorithm()) {
213 uber_loss_algorithm_.SetLossDetectionType(kTime);
214 } else {
215 general_loss_algorithm_.SetLossDetectionType(kTime);
216 }
217 }
218 if (config.HasClientRequestedIndependentOption(kATIM, perspective)) {
219 if (unacked_packets_.use_uber_loss_algorithm()) {
220 uber_loss_algorithm_.SetLossDetectionType(kAdaptiveTime);
221 } else {
222 general_loss_algorithm_.SetLossDetectionType(kAdaptiveTime);
223 }
224 }
225 if (config.HasClientRequestedIndependentOption(kLFAK, perspective)) {
226 if (unacked_packets_.use_uber_loss_algorithm()) {
227 uber_loss_algorithm_.SetLossDetectionType(kLazyFack);
228 } else {
229 general_loss_algorithm_.SetLossDetectionType(kLazyFack);
230 }
231 }
232 if (config.HasClientSentConnectionOption(kCONH, perspective)) {
233 conservative_handshake_retransmits_ = true;
234 }
235 send_algorithm_->SetFromConfig(config, perspective);
236
237 if (network_change_visitor_ != nullptr) {
238 network_change_visitor_->OnCongestionChange();
239 }
240}
241
242void QuicSentPacketManager::ResumeConnectionState(
243 const CachedNetworkParameters& cached_network_params,
244 bool max_bandwidth_resumption) {
245 QuicBandwidth bandwidth = QuicBandwidth::FromBytesPerSecond(
246 max_bandwidth_resumption
247 ? cached_network_params.max_bandwidth_estimate_bytes_per_second()
248 : cached_network_params.bandwidth_estimate_bytes_per_second());
249 QuicTime::Delta rtt =
250 QuicTime::Delta::FromMilliseconds(cached_network_params.min_rtt_ms());
251 AdjustNetworkParameters(bandwidth, rtt);
252}
253
254void QuicSentPacketManager::AdjustNetworkParameters(QuicBandwidth bandwidth,
255 QuicTime::Delta rtt) {
256 if (!rtt.IsZero()) {
257 SetInitialRtt(rtt);
258 }
259 send_algorithm_->AdjustNetworkParameters(bandwidth, rtt);
260 if (debug_delegate_ != nullptr) {
261 debug_delegate_->OnAdjustNetworkParameters(bandwidth, rtt);
262 }
263}
264
265void QuicSentPacketManager::SetHandshakeConfirmed() {
266 handshake_confirmed_ = true;
267 if (unacked_packets_.use_uber_loss_algorithm()) {
268 NeuterHandshakePackets();
269 }
270}
271
272void QuicSentPacketManager::PostProcessAfterMarkingPacketHandled(
273 const QuicAckFrame& ack_frame,
274 QuicTime ack_receive_time,
275 bool rtt_updated,
276 QuicByteCount prior_bytes_in_flight) {
277 if (session_decides_what_to_write()) {
278 unacked_packets_.NotifyAggregatedStreamFrameAcked(
279 last_ack_frame_.ack_delay_time);
280 }
281 InvokeLossDetection(ack_receive_time);
282 // Ignore losses in RTO mode.
283 if (consecutive_rto_count_ > 0 && !use_new_rto_) {
284 packets_lost_.clear();
285 }
286 MaybeInvokeCongestionEvent(rtt_updated, prior_bytes_in_flight,
287 ack_receive_time);
288 unacked_packets_.RemoveObsoletePackets();
289
290 sustained_bandwidth_recorder_.RecordEstimate(
291 send_algorithm_->InRecovery(), send_algorithm_->InSlowStart(),
292 send_algorithm_->BandwidthEstimate(), ack_receive_time, clock_->WallNow(),
293 rtt_stats_.smoothed_rtt());
294
295 // Anytime we are making forward progress and have a new RTT estimate, reset
296 // the backoff counters.
297 if (rtt_updated) {
298 if (consecutive_rto_count_ > 0) {
299 // If the ack acknowledges data sent prior to the RTO,
300 // the RTO was spurious.
301 if (LargestAcked(ack_frame) < first_rto_transmission_) {
302 // Replace SRTT with latest_rtt and increase the variance to prevent
303 // a spurious RTO from happening again.
304 rtt_stats_.ExpireSmoothedMetrics();
305 } else {
306 if (!use_new_rto_) {
307 send_algorithm_->OnRetransmissionTimeout(true);
308 }
309 }
310 }
311 // Reset all retransmit counters any time a new packet is acked.
312 consecutive_rto_count_ = 0;
313 consecutive_tlp_count_ = 0;
314 consecutive_crypto_retransmission_count_ = 0;
315 }
316
317 if (debug_delegate_ != nullptr) {
318 debug_delegate_->OnIncomingAck(ack_frame, ack_receive_time,
319 LargestAcked(ack_frame), rtt_updated,
320 GetLeastUnacked());
321 }
322 // Remove packets below least unacked from all_packets_acked_ and
323 // last_ack_frame_.
324 last_ack_frame_.packets.RemoveUpTo(unacked_packets_.GetLeastUnacked());
325 last_ack_frame_.received_packet_times.clear();
326}
327
328void QuicSentPacketManager::MaybeInvokeCongestionEvent(
329 bool rtt_updated,
330 QuicByteCount prior_in_flight,
331 QuicTime event_time) {
332 if (!rtt_updated && packets_acked_.empty() && packets_lost_.empty()) {
333 return;
334 }
335 if (using_pacing_) {
336 pacing_sender_.OnCongestionEvent(rtt_updated, prior_in_flight, event_time,
337 packets_acked_, packets_lost_);
338 } else {
339 send_algorithm_->OnCongestionEvent(rtt_updated, prior_in_flight, event_time,
340 packets_acked_, packets_lost_);
341 }
342 packets_acked_.clear();
343 packets_lost_.clear();
344 if (network_change_visitor_ != nullptr) {
345 network_change_visitor_->OnCongestionChange();
346 }
347}
348
349void QuicSentPacketManager::RetransmitUnackedPackets(
350 TransmissionType retransmission_type) {
351 DCHECK(retransmission_type == ALL_UNACKED_RETRANSMISSION ||
352 retransmission_type == ALL_INITIAL_RETRANSMISSION);
353 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
354 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
355 it != unacked_packets_.end(); ++it, ++packet_number) {
356 if ((retransmission_type == ALL_UNACKED_RETRANSMISSION ||
357 it->encryption_level == ENCRYPTION_ZERO_RTT) &&
358 unacked_packets_.HasRetransmittableFrames(*it)) {
359 MarkForRetransmission(packet_number, retransmission_type);
360 }
361 }
362}
363
364void QuicSentPacketManager::NeuterUnencryptedPackets() {
365 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
366 if (session_decides_what_to_write()) {
367 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
368 it != unacked_packets_.end(); ++it, ++packet_number) {
369 if (!it->retransmittable_frames.empty() &&
370 it->encryption_level == ENCRYPTION_NONE) {
371 // Once the connection swithes to forward secure, no unencrypted packets
372 // will be sent. The data has been abandoned in the cryto stream. Remove
373 // it from in flight.
374 unacked_packets_.RemoveFromInFlight(packet_number);
375 }
376 }
377 return;
378 }
379 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
380 it != unacked_packets_.end(); ++it, ++packet_number) {
381 if (it->encryption_level == ENCRYPTION_NONE &&
382 unacked_packets_.HasRetransmittableFrames(*it)) {
383 // Once you're forward secure, no unencrypted packets will be sent, crypto
384 // or otherwise. Unencrypted packets are neutered and abandoned, to ensure
385 // they are not retransmitted or considered lost from a congestion control
386 // perspective.
387 pending_retransmissions_.erase(packet_number);
388 unacked_packets_.RemoveFromInFlight(packet_number);
389 unacked_packets_.RemoveRetransmittability(packet_number);
390 }
391 }
392}
393
394void QuicSentPacketManager::NeuterHandshakePackets() {
395 DCHECK(unacked_packets_.use_uber_loss_algorithm());
396 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
397 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
398 it != unacked_packets_.end(); ++it, ++packet_number) {
399 if (session_decides_what_to_write()) {
400 if (!it->retransmittable_frames.empty() &&
401 unacked_packets_.GetPacketNumberSpace(it->encryption_level) ==
402 HANDSHAKE_DATA) {
403 unacked_packets_.RemoveFromInFlight(packet_number);
404 }
405 continue;
406 }
407 if (unacked_packets_.GetPacketNumberSpace(it->encryption_level) ==
408 HANDSHAKE_DATA &&
409 unacked_packets_.HasRetransmittableFrames(*it)) {
410 pending_retransmissions_.erase(packet_number);
411 unacked_packets_.RemoveFromInFlight(packet_number);
412 unacked_packets_.RemoveRetransmittability(packet_number);
413 }
414 }
415}
416
417void QuicSentPacketManager::MarkForRetransmission(
418 QuicPacketNumber packet_number,
419 TransmissionType transmission_type) {
420 QuicTransmissionInfo* transmission_info =
421 unacked_packets_.GetMutableTransmissionInfo(packet_number);
422 // When session decides what to write, a previous RTO retransmission may cause
423 // connection close; packets without retransmittable frames can be marked for
424 // loss retransmissions.
425 QUIC_BUG_IF((transmission_type != LOSS_RETRANSMISSION &&
426 (!session_decides_what_to_write() ||
427 transmission_type != RTO_RETRANSMISSION)) &&
428 !unacked_packets_.HasRetransmittableFrames(*transmission_info))
429 << "transmission_type: "
430 << QuicUtils::TransmissionTypeToString(transmission_type);
431 // Handshake packets should never be sent as probing retransmissions.
432 DCHECK(!transmission_info->has_crypto_handshake ||
433 transmission_type != PROBING_RETRANSMISSION);
434 if (!RetransmissionLeavesBytesInFlight(transmission_type)) {
435 unacked_packets_.RemoveFromInFlight(transmission_info);
436 }
437
438 if (!session_decides_what_to_write()) {
439 if (!unacked_packets_.HasRetransmittableFrames(*transmission_info)) {
440 return;
441 }
442 if (!QuicContainsKey(pending_retransmissions_, packet_number)) {
443 pending_retransmissions_[packet_number] = transmission_type;
444 }
445 return;
446 }
447
448 HandleRetransmission(transmission_type, transmission_info);
449
450 // Update packet state according to transmission type.
451 transmission_info->state =
452 QuicUtils::RetransmissionTypeToPacketState(transmission_type);
453}
454
455void QuicSentPacketManager::HandleRetransmission(
456 TransmissionType transmission_type,
457 QuicTransmissionInfo* transmission_info) {
458 DCHECK(session_decides_what_to_write());
459 if (ShouldForceRetransmission(transmission_type)) {
460 // TODO(fayang): Consider to make RTO and PROBING retransmission
461 // strategies be configurable by applications. Today, TLP, RTO and PROBING
462 // retransmissions are handled similarly, i.e., always retranmist the
463 // oldest outstanding data. This is not ideal in general because different
464 // applications may want different strategies. For example, some
465 // applications may want to use higher priority stream data for bandwidth
466 // probing, and some applications want to consider RTO is an indication of
467 // loss, etc.
468 unacked_packets_.RetransmitFrames(*transmission_info, transmission_type);
469 return;
470 }
471
472 unacked_packets_.NotifyFramesLost(*transmission_info, transmission_type);
473 if (transmission_info->retransmittable_frames.empty()) {
474 return;
475 }
476
477 if (transmission_type == LOSS_RETRANSMISSION) {
478 // Record the first packet sent after loss, which allows to wait 1
479 // more RTT before giving up on this lost packet.
480 transmission_info->retransmission =
481 unacked_packets_.largest_sent_packet() + 1;
482 } else {
483 // Clear the recorded first packet sent after loss when version or
484 // encryption changes.
485 transmission_info->retransmission.Clear();
486 }
487}
488
489void QuicSentPacketManager::RecordOneSpuriousRetransmission(
490 const QuicTransmissionInfo& info) {
491 stats_->bytes_spuriously_retransmitted += info.bytes_sent;
492 ++stats_->packets_spuriously_retransmitted;
493 if (debug_delegate_ != nullptr) {
494 debug_delegate_->OnSpuriousPacketRetransmission(info.transmission_type,
495 info.bytes_sent);
496 }
497}
498
499void QuicSentPacketManager::RecordSpuriousRetransmissions(
500 const QuicTransmissionInfo& info,
501 QuicPacketNumber acked_packet_number) {
502 if (session_decides_what_to_write()) {
503 RecordOneSpuriousRetransmission(info);
504 if (info.transmission_type == LOSS_RETRANSMISSION) {
505 // Only inform the loss detection of spurious retransmits it caused.
506 loss_algorithm_->SpuriousRetransmitDetected(
507 unacked_packets_, clock_->Now(), rtt_stats_, acked_packet_number);
508 }
509 return;
510 }
511 QuicPacketNumber retransmission = info.retransmission;
512 while (retransmission.IsInitialized()) {
513 const QuicTransmissionInfo& retransmit_info =
514 unacked_packets_.GetTransmissionInfo(retransmission);
515 retransmission = retransmit_info.retransmission;
516 RecordOneSpuriousRetransmission(retransmit_info);
517 }
518 // Only inform the loss detection of spurious retransmits it caused.
519 if (unacked_packets_.GetTransmissionInfo(info.retransmission)
520 .transmission_type == LOSS_RETRANSMISSION) {
521 loss_algorithm_->SpuriousRetransmitDetected(
522 unacked_packets_, clock_->Now(), rtt_stats_, info.retransmission);
523 }
524}
525
526QuicPendingRetransmission QuicSentPacketManager::NextPendingRetransmission() {
527 QUIC_BUG_IF(pending_retransmissions_.empty())
528 << "Unexpected call to NextPendingRetransmission() with empty pending "
529 << "retransmission list. Corrupted memory usage imminent.";
530 QUIC_BUG_IF(session_decides_what_to_write())
531 << "Unexpected call to NextPendingRetransmission() when session handles "
532 "retransmissions";
533 QuicPacketNumber packet_number = pending_retransmissions_.begin()->first;
534 TransmissionType transmission_type = pending_retransmissions_.begin()->second;
535 if (unacked_packets_.HasPendingCryptoPackets()) {
536 // Ensure crypto packets are retransmitted before other packets.
537 for (const auto& pair : pending_retransmissions_) {
538 if (HasCryptoHandshake(
539 unacked_packets_.GetTransmissionInfo(pair.first))) {
540 packet_number = pair.first;
541 transmission_type = pair.second;
542 break;
543 }
544 }
545 }
546 DCHECK(unacked_packets_.IsUnacked(packet_number)) << packet_number;
547 const QuicTransmissionInfo& transmission_info =
548 unacked_packets_.GetTransmissionInfo(packet_number);
549 DCHECK(unacked_packets_.HasRetransmittableFrames(transmission_info));
550
551 return QuicPendingRetransmission(packet_number, transmission_type,
552 transmission_info);
553}
554
555QuicPacketNumber QuicSentPacketManager::GetNewestRetransmission(
556 QuicPacketNumber packet_number,
557 const QuicTransmissionInfo& transmission_info) const {
558 if (session_decides_what_to_write()) {
559 return packet_number;
560 }
561 QuicPacketNumber retransmission = transmission_info.retransmission;
562 while (retransmission.IsInitialized()) {
563 packet_number = retransmission;
564 retransmission =
565 unacked_packets_.GetTransmissionInfo(retransmission).retransmission;
566 }
567 return packet_number;
568}
569
570void QuicSentPacketManager::MarkPacketHandled(QuicPacketNumber packet_number,
571 QuicTransmissionInfo* info,
572 QuicTime::Delta ack_delay_time) {
573 QuicPacketNumber newest_transmission =
574 GetNewestRetransmission(packet_number, *info);
575 // Remove the most recent packet, if it is pending retransmission.
576 pending_retransmissions_.erase(newest_transmission);
577
578 if (newest_transmission == packet_number) {
579 // Try to aggregate acked stream frames if acked packet is not a
580 // retransmission.
581 const bool fast_path = session_decides_what_to_write() &&
582 info->transmission_type == NOT_RETRANSMISSION;
583 if (fast_path) {
584 unacked_packets_.MaybeAggregateAckedStreamFrame(*info, ack_delay_time);
585 } else {
586 if (session_decides_what_to_write()) {
587 unacked_packets_.NotifyAggregatedStreamFrameAcked(ack_delay_time);
588 }
589 const bool new_data_acked =
590 unacked_packets_.NotifyFramesAcked(*info, ack_delay_time);
591 if (session_decides_what_to_write() && !new_data_acked &&
592 info->transmission_type != NOT_RETRANSMISSION) {
593 // Record as a spurious retransmission if this packet is a
594 // retransmission and no new data gets acked.
595 QUIC_DVLOG(1) << "Detect spurious retransmitted packet "
596 << packet_number << " transmission type: "
597 << QuicUtils::TransmissionTypeToString(
598 info->transmission_type);
599 RecordSpuriousRetransmissions(*info, packet_number);
600 }
601 }
602 } else {
603 DCHECK(!session_decides_what_to_write());
604 RecordSpuriousRetransmissions(*info, packet_number);
605 // Remove the most recent packet from flight if it's a crypto handshake
606 // packet, since they won't be acked now that one has been processed.
607 // Other crypto handshake packets won't be in flight, only the newest
608 // transmission of a crypto packet is in flight at once.
609 // TODO(ianswett): Instead of handling all crypto packets special,
610 // only handle nullptr encrypted packets in a special way.
611 const QuicTransmissionInfo& newest_transmission_info =
612 unacked_packets_.GetTransmissionInfo(newest_transmission);
613 unacked_packets_.NotifyFramesAcked(newest_transmission_info,
614 ack_delay_time);
615 if (HasCryptoHandshake(newest_transmission_info)) {
616 unacked_packets_.RemoveFromInFlight(newest_transmission);
617 }
618 }
619
620 if (network_change_visitor_ != nullptr &&
621 info->bytes_sent > largest_mtu_acked_) {
622 largest_mtu_acked_ = info->bytes_sent;
623 network_change_visitor_->OnPathMtuIncreased(largest_mtu_acked_);
624 }
625 unacked_packets_.RemoveFromInFlight(info);
626 unacked_packets_.RemoveRetransmittability(info);
627 info->state = ACKED;
628}
629
630bool QuicSentPacketManager::OnPacketSent(
631 SerializedPacket* serialized_packet,
632 QuicPacketNumber original_packet_number,
633 QuicTime sent_time,
634 TransmissionType transmission_type,
635 HasRetransmittableData has_retransmittable_data) {
636 QuicPacketNumber packet_number = serialized_packet->packet_number;
637 DCHECK_LE(FirstSendingPacketNumber(), packet_number);
638 DCHECK(!unacked_packets_.IsUnacked(packet_number));
639 QUIC_BUG_IF(serialized_packet->encrypted_length == 0)
640 << "Cannot send empty packets.";
641
642 if (original_packet_number.IsInitialized()) {
643 pending_retransmissions_.erase(original_packet_number);
644 }
645
646 if (pending_timer_transmission_count_ > 0) {
647 --pending_timer_transmission_count_;
648 }
649
650 bool in_flight = has_retransmittable_data == HAS_RETRANSMITTABLE_DATA;
651 if (using_pacing_) {
652 pacing_sender_.OnPacketSent(
653 sent_time, unacked_packets_.bytes_in_flight(), packet_number,
654 serialized_packet->encrypted_length, has_retransmittable_data);
655 } else {
656 send_algorithm_->OnPacketSent(
657 sent_time, unacked_packets_.bytes_in_flight(), packet_number,
658 serialized_packet->encrypted_length, has_retransmittable_data);
659 }
660
661 unacked_packets_.AddSentPacket(serialized_packet, original_packet_number,
662 transmission_type, sent_time, in_flight);
663 // Reset the retransmission timer anytime a pending packet is sent.
664 return in_flight;
665}
666
667void QuicSentPacketManager::OnRetransmissionTimeout() {
668 DCHECK(unacked_packets_.HasInFlightPackets());
669 DCHECK_EQ(0u, pending_timer_transmission_count_);
670 // Handshake retransmission, timer based loss detection, TLP, and RTO are
671 // implemented with a single alarm. The handshake alarm is set when the
672 // handshake has not completed, the loss alarm is set when the loss detection
673 // algorithm says to, and the TLP and RTO alarms are set after that.
674 // The TLP alarm is always set to run for under an RTO.
675 switch (GetRetransmissionMode()) {
676 case HANDSHAKE_MODE:
677 ++stats_->crypto_retransmit_count;
678 RetransmitCryptoPackets();
679 return;
680 case LOSS_MODE: {
681 ++stats_->loss_timeout_count;
682 QuicByteCount prior_in_flight = unacked_packets_.bytes_in_flight();
683 const QuicTime now = clock_->Now();
684 InvokeLossDetection(now);
685 MaybeInvokeCongestionEvent(false, prior_in_flight, now);
686 return;
687 }
688 case TLP_MODE:
689 ++stats_->tlp_count;
690 ++consecutive_tlp_count_;
691 pending_timer_transmission_count_ = 1;
692 // TLPs prefer sending new data instead of retransmitting data, so
693 // give the connection a chance to write before completing the TLP.
694 return;
695 case RTO_MODE:
696 ++stats_->rto_count;
697 RetransmitRtoPackets();
698 return;
699 }
700}
701
702void QuicSentPacketManager::RetransmitCryptoPackets() {
703 DCHECK_EQ(HANDSHAKE_MODE, GetRetransmissionMode());
704 ++consecutive_crypto_retransmission_count_;
705 bool packet_retransmitted = false;
706 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
707 std::vector<QuicPacketNumber> crypto_retransmissions;
708 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
709 it != unacked_packets_.end(); ++it, ++packet_number) {
710 // Only retransmit frames which are in flight, and therefore have been sent.
711 if (!it->in_flight ||
712 (session_decides_what_to_write() && it->state != OUTSTANDING) ||
713 !it->has_crypto_handshake ||
714 !unacked_packets_.HasRetransmittableFrames(*it)) {
715 continue;
716 }
717 packet_retransmitted = true;
718 if (session_decides_what_to_write()) {
719 crypto_retransmissions.push_back(packet_number);
720 } else {
721 MarkForRetransmission(packet_number, HANDSHAKE_RETRANSMISSION);
722 }
723 ++pending_timer_transmission_count_;
724 }
725 DCHECK(packet_retransmitted) << "No crypto packets found to retransmit.";
726 if (session_decides_what_to_write()) {
727 for (QuicPacketNumber retransmission : crypto_retransmissions) {
728 MarkForRetransmission(retransmission, HANDSHAKE_RETRANSMISSION);
729 }
730 }
731}
732
733bool QuicSentPacketManager::MaybeRetransmitTailLossProbe() {
734 if (pending_timer_transmission_count_ == 0) {
735 return false;
736 }
737 if (!MaybeRetransmitOldestPacket(TLP_RETRANSMISSION)) {
738 // If no tail loss probe can be sent, because there are no retransmittable
739 // packets, execute a conventional RTO to abandon old packets.
740 if (GetQuicReloadableFlag(quic_optimize_inflight_check)) {
741 QUIC_RELOADABLE_FLAG_COUNT(quic_optimize_inflight_check);
742 pending_timer_transmission_count_ = 0;
743 RetransmitRtoPackets();
744 }
745 return false;
746 }
747 return true;
748}
749
750bool QuicSentPacketManager::MaybeRetransmitOldestPacket(TransmissionType type) {
751 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
752 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
753 it != unacked_packets_.end(); ++it, ++packet_number) {
754 // Only retransmit frames which are in flight, and therefore have been sent.
755 if (!it->in_flight ||
756 (session_decides_what_to_write() && it->state != OUTSTANDING) ||
757 !unacked_packets_.HasRetransmittableFrames(*it)) {
758 continue;
759 }
760 MarkForRetransmission(packet_number, type);
761 return true;
762 }
763 QUIC_DVLOG(1)
764 << "No retransmittable packets, so RetransmitOldestPacket failed.";
765 return false;
766}
767
768void QuicSentPacketManager::RetransmitRtoPackets() {
769 QUIC_BUG_IF(pending_timer_transmission_count_ > 0)
770 << "Retransmissions already queued:" << pending_timer_transmission_count_;
771 // Mark two packets for retransmission.
772 QuicPacketNumber packet_number = unacked_packets_.GetLeastUnacked();
773 std::vector<QuicPacketNumber> retransmissions;
774 for (QuicUnackedPacketMap::const_iterator it = unacked_packets_.begin();
775 it != unacked_packets_.end(); ++it, ++packet_number) {
776 if ((!session_decides_what_to_write() || it->state == OUTSTANDING) &&
777 unacked_packets_.HasRetransmittableFrames(*it) &&
778 pending_timer_transmission_count_ < max_rto_packets_) {
779 if (session_decides_what_to_write()) {
780 retransmissions.push_back(packet_number);
781 } else {
782 MarkForRetransmission(packet_number, RTO_RETRANSMISSION);
783 }
784 ++pending_timer_transmission_count_;
785 }
786 // Abandon non-retransmittable data that's in flight to ensure it doesn't
787 // fill up the congestion window.
788 bool has_retransmissions = it->retransmission.IsInitialized();
789 if (session_decides_what_to_write()) {
790 has_retransmissions = it->state != OUTSTANDING;
791 }
792 if (it->in_flight && !has_retransmissions &&
793 !unacked_packets_.HasRetransmittableFrames(*it)) {
794 // Log only for non-retransmittable data.
795 // Retransmittable data is marked as lost during loss detection, and will
796 // be logged later.
797 unacked_packets_.RemoveFromInFlight(packet_number);
798 if (debug_delegate_ != nullptr) {
799 debug_delegate_->OnPacketLoss(packet_number, RTO_RETRANSMISSION,
800 clock_->Now());
801 }
802 }
803 }
804 if (pending_timer_transmission_count_ > 0) {
805 if (consecutive_rto_count_ == 0) {
806 first_rto_transmission_ = unacked_packets_.largest_sent_packet() + 1;
807 }
808 ++consecutive_rto_count_;
809 }
810 if (session_decides_what_to_write()) {
811 for (QuicPacketNumber retransmission : retransmissions) {
812 MarkForRetransmission(retransmission, RTO_RETRANSMISSION);
813 }
814 }
815}
816
817QuicSentPacketManager::RetransmissionTimeoutMode
818QuicSentPacketManager::GetRetransmissionMode() const {
819 DCHECK(unacked_packets_.HasInFlightPackets());
820 if (!handshake_confirmed_ && unacked_packets_.HasPendingCryptoPackets()) {
821 return HANDSHAKE_MODE;
822 }
823 if (loss_algorithm_->GetLossTimeout() != QuicTime::Zero()) {
824 return LOSS_MODE;
825 }
826 if (consecutive_tlp_count_ < max_tail_loss_probes_) {
827 if (GetQuicReloadableFlag(quic_optimize_inflight_check) ||
828 unacked_packets_.HasUnackedRetransmittableFrames()) {
829 return TLP_MODE;
830 }
831 }
832 return RTO_MODE;
833}
834
835void QuicSentPacketManager::InvokeLossDetection(QuicTime time) {
836 if (!packets_acked_.empty()) {
837 DCHECK_LE(packets_acked_.front().packet_number,
838 packets_acked_.back().packet_number);
839 largest_newly_acked_ = packets_acked_.back().packet_number;
840 }
841 loss_algorithm_->DetectLosses(unacked_packets_, time, rtt_stats_,
842 largest_newly_acked_, packets_acked_,
843 &packets_lost_);
844 for (const LostPacket& packet : packets_lost_) {
845 ++stats_->packets_lost;
846 if (debug_delegate_ != nullptr) {
847 debug_delegate_->OnPacketLoss(packet.packet_number, LOSS_RETRANSMISSION,
848 time);
849 }
850
851 MarkForRetransmission(packet.packet_number, LOSS_RETRANSMISSION);
852 }
853}
854
855bool QuicSentPacketManager::MaybeUpdateRTT(QuicPacketNumber largest_acked,
856 QuicTime::Delta ack_delay_time,
857 QuicTime ack_receive_time) {
858 // We rely on ack_delay_time to compute an RTT estimate, so we
859 // only update rtt when the largest observed gets acked.
860 if (!unacked_packets_.IsUnacked(largest_acked)) {
861 return false;
862 }
863 // We calculate the RTT based on the highest ACKed packet number, the lower
864 // packet numbers will include the ACK aggregation delay.
865 const QuicTransmissionInfo& transmission_info =
866 unacked_packets_.GetTransmissionInfo(largest_acked);
867 // Ensure the packet has a valid sent time.
868 if (transmission_info.sent_time == QuicTime::Zero()) {
869 QUIC_BUG << "Acked packet has zero sent time, largest_acked:"
870 << largest_acked;
871 return false;
872 }
873 if (transmission_info.sent_time > ack_receive_time) {
874 QUIC_CODE_COUNT(quic_receive_acked_before_sending);
875 }
876
877 QuicTime::Delta send_delta = ack_receive_time - transmission_info.sent_time;
878 rtt_stats_.UpdateRtt(send_delta, ack_delay_time, ack_receive_time);
879
880 return true;
881}
882
883QuicTime::Delta QuicSentPacketManager::TimeUntilSend(QuicTime now) const {
884 // The TLP logic is entirely contained within QuicSentPacketManager, so the
885 // send algorithm does not need to be consulted.
886 if (pending_timer_transmission_count_ > 0) {
887 return QuicTime::Delta::Zero();
888 }
889
890 if (using_pacing_) {
891 return pacing_sender_.TimeUntilSend(now,
892 unacked_packets_.bytes_in_flight());
893 }
894
895 return send_algorithm_->CanSend(unacked_packets_.bytes_in_flight())
896 ? QuicTime::Delta::Zero()
897 : QuicTime::Delta::Infinite();
898}
899
900const QuicTime QuicSentPacketManager::GetRetransmissionTime() const {
901 // Don't set the timer if there is nothing to retransmit or we've already
902 // queued a tlp transmission and it hasn't been sent yet.
903 if (!unacked_packets_.HasInFlightPackets() ||
904 pending_timer_transmission_count_ > 0) {
905 return QuicTime::Zero();
906 }
907 if (!GetQuicReloadableFlag(quic_optimize_inflight_check) &&
908 !unacked_packets_.HasUnackedRetransmittableFrames()) {
909 return QuicTime::Zero();
910 }
911 switch (GetRetransmissionMode()) {
912 case HANDSHAKE_MODE:
913 return unacked_packets_.GetLastCryptoPacketSentTime() +
914 GetCryptoRetransmissionDelay();
915 case LOSS_MODE:
916 return loss_algorithm_->GetLossTimeout();
917 case TLP_MODE: {
918 // TODO(ianswett): When CWND is available, it would be preferable to
919 // set the timer based on the earliest retransmittable packet.
920 // Base the updated timer on the send time of the last packet.
921 const QuicTime sent_time = unacked_packets_.GetLastPacketSentTime();
922 const QuicTime tlp_time = sent_time + GetTailLossProbeDelay();
923 // Ensure the TLP timer never gets set to a time in the past.
924 return std::max(clock_->ApproximateNow(), tlp_time);
925 }
926 case RTO_MODE: {
927 // The RTO is based on the first outstanding packet.
928 const QuicTime sent_time = unacked_packets_.GetLastPacketSentTime();
929 QuicTime rto_time = sent_time + GetRetransmissionDelay();
930 // Wait for TLP packets to be acked before an RTO fires.
931 QuicTime tlp_time =
932 unacked_packets_.GetLastPacketSentTime() + GetTailLossProbeDelay();
933 return std::max(tlp_time, rto_time);
934 }
935 }
936 DCHECK(false);
937 return QuicTime::Zero();
938}
939
940const QuicTime::Delta QuicSentPacketManager::GetPathDegradingDelay() const {
941 QuicTime::Delta delay = QuicTime::Delta::Zero();
942 for (size_t i = 0; i < max_tail_loss_probes_; ++i) {
943 delay = delay + GetTailLossProbeDelay(i);
944 }
945 for (size_t i = 0; i < kNumRetransmissionDelaysForPathDegradingDelay; ++i) {
946 delay = delay + GetRetransmissionDelay(i);
947 }
948 return delay;
949}
950
951const QuicTime::Delta QuicSentPacketManager::GetCryptoRetransmissionDelay()
952 const {
953 // This is equivalent to the TailLossProbeDelay, but slightly more aggressive
954 // because crypto handshake messages don't incur a delayed ack time.
955 QuicTime::Delta srtt = rtt_stats_.SmoothedOrInitialRtt();
956 int64_t delay_ms;
957 if (conservative_handshake_retransmits_) {
958 // Using the delayed ack time directly could cause conservative handshake
959 // retransmissions to actually be more aggressive than the default.
960 delay_ms = std::max(delayed_ack_time_.ToMilliseconds(),
961 static_cast<int64_t>(2 * srtt.ToMilliseconds()));
962 } else {
963 delay_ms = std::max(kMinHandshakeTimeoutMs,
964 static_cast<int64_t>(1.5 * srtt.ToMilliseconds()));
965 }
966 return QuicTime::Delta::FromMilliseconds(
967 delay_ms << consecutive_crypto_retransmission_count_);
968}
969
970const QuicTime::Delta QuicSentPacketManager::GetTailLossProbeDelay(
971 size_t consecutive_tlp_count) const {
972 QuicTime::Delta srtt = rtt_stats_.SmoothedOrInitialRtt();
973 if (enable_half_rtt_tail_loss_probe_ && consecutive_tlp_count == 0u) {
974 return std::max(min_tlp_timeout_, srtt * 0.5);
975 }
976 if (ietf_style_tlp_) {
977 return std::max(min_tlp_timeout_, 1.5 * srtt + rtt_stats_.max_ack_delay());
978 }
979 if (ietf_style_2x_tlp_) {
980 return std::max(min_tlp_timeout_, 2 * srtt + rtt_stats_.max_ack_delay());
981 }
982 if (!unacked_packets_.HasMultipleInFlightPackets()) {
983 // This expression really should be using the delayed ack time, but in TCP
984 // MinRTO was traditionally set to 2x the delayed ack timer and this
985 // expression assumed QUIC did the same.
986 return std::max(2 * srtt, 1.5 * srtt + (min_rto_timeout_ * 0.5));
987 }
988 return std::max(min_tlp_timeout_, 2 * srtt);
989}
990
991const QuicTime::Delta QuicSentPacketManager::GetRetransmissionDelay(
992 size_t consecutive_rto_count) const {
993 QuicTime::Delta retransmission_delay = QuicTime::Delta::Zero();
994 if (rtt_stats_.smoothed_rtt().IsZero()) {
995 // We are in the initial state, use default timeout values.
996 retransmission_delay =
997 QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
998 } else {
999 retransmission_delay =
1000 rtt_stats_.smoothed_rtt() + 4 * rtt_stats_.mean_deviation();
1001 if (retransmission_delay < min_rto_timeout_) {
1002 retransmission_delay = min_rto_timeout_;
1003 }
1004 }
1005
1006 // Calculate exponential back off.
1007 retransmission_delay =
1008 retransmission_delay *
1009 (1 << std::min<size_t>(consecutive_rto_count, kMaxRetransmissions));
1010
1011 if (retransmission_delay.ToMilliseconds() > kMaxRetransmissionTimeMs) {
1012 return QuicTime::Delta::FromMilliseconds(kMaxRetransmissionTimeMs);
1013 }
1014 return retransmission_delay;
1015}
1016
vasilvvc48c8712019-03-11 13:38:16 -07001017std::string QuicSentPacketManager::GetDebugState() const {
QUICHE teama6ef0a62019-03-07 20:34:33 -05001018 return send_algorithm_->GetDebugState();
1019}
1020
1021void QuicSentPacketManager::CancelRetransmissionsForStream(
1022 QuicStreamId stream_id) {
1023 if (session_decides_what_to_write()) {
1024 return;
1025 }
1026 unacked_packets_.CancelRetransmissionsForStream(stream_id);
1027 auto it = pending_retransmissions_.begin();
1028 while (it != pending_retransmissions_.end()) {
1029 if (unacked_packets_.HasRetransmittableFrames(it->first)) {
1030 ++it;
1031 continue;
1032 }
1033 it = pending_retransmissions_.erase(it);
1034 }
1035}
1036
1037void QuicSentPacketManager::SetSendAlgorithm(
1038 CongestionControlType congestion_control_type) {
1039 SetSendAlgorithm(SendAlgorithmInterface::Create(
1040 clock_, &rtt_stats_, &unacked_packets_, congestion_control_type,
1041 QuicRandom::GetInstance(), stats_, initial_congestion_window_));
1042}
1043
1044void QuicSentPacketManager::SetSendAlgorithm(
1045 SendAlgorithmInterface* send_algorithm) {
1046 send_algorithm_.reset(send_algorithm);
1047 pacing_sender_.set_sender(send_algorithm);
1048}
1049
1050void QuicSentPacketManager::OnConnectionMigration(AddressChangeType type) {
1051 if (type == PORT_CHANGE || type == IPV4_SUBNET_CHANGE) {
1052 // Rtt and cwnd do not need to be reset when the peer address change is
1053 // considered to be caused by NATs.
1054 return;
1055 }
1056 consecutive_rto_count_ = 0;
1057 consecutive_tlp_count_ = 0;
1058 rtt_stats_.OnConnectionMigration();
1059 send_algorithm_->OnConnectionMigration();
1060}
1061
1062void QuicSentPacketManager::OnAckFrameStart(QuicPacketNumber largest_acked,
1063 QuicTime::Delta ack_delay_time,
1064 QuicTime ack_receive_time) {
1065 DCHECK(packets_acked_.empty());
1066 DCHECK_LE(largest_acked, unacked_packets_.largest_sent_packet());
1067 rtt_updated_ =
1068 MaybeUpdateRTT(largest_acked, ack_delay_time, ack_receive_time);
1069 DCHECK(!unacked_packets_.largest_acked().IsInitialized() ||
QUICHE team9929cc42019-03-13 08:17:43 -07001070 largest_acked >= unacked_packets_.largest_acked() ||
1071 tolerate_reneging_);
QUICHE teama6ef0a62019-03-07 20:34:33 -05001072 last_ack_frame_.ack_delay_time = ack_delay_time;
1073 acked_packets_iter_ = last_ack_frame_.packets.rbegin();
1074}
1075
1076void QuicSentPacketManager::OnAckRange(QuicPacketNumber start,
1077 QuicPacketNumber end) {
1078 if (!last_ack_frame_.largest_acked.IsInitialized() ||
1079 end > last_ack_frame_.largest_acked + 1) {
1080 // Largest acked increases.
1081 unacked_packets_.IncreaseLargestAcked(end - 1);
1082 last_ack_frame_.largest_acked = end - 1;
1083 }
1084 // Drop ack ranges which ack packets below least_unacked.
1085 QuicPacketNumber least_unacked = unacked_packets_.GetLeastUnacked();
1086 if (least_unacked.IsInitialized() && end <= least_unacked) {
1087 return;
1088 }
1089 start = std::max(start, least_unacked);
1090 do {
1091 QuicPacketNumber newly_acked_start = start;
1092 if (acked_packets_iter_ != last_ack_frame_.packets.rend()) {
1093 newly_acked_start = std::max(start, acked_packets_iter_->max());
1094 }
1095 for (QuicPacketNumber acked = end - 1; acked >= newly_acked_start;
1096 --acked) {
1097 // Check if end is above the current range. If so add newly acked packets
1098 // in descending order.
1099 packets_acked_.push_back(AckedPacket(acked, 0, QuicTime::Zero()));
1100 if (acked == FirstSendingPacketNumber()) {
1101 break;
1102 }
1103 }
1104 if (acked_packets_iter_ == last_ack_frame_.packets.rend() ||
1105 start > acked_packets_iter_->min()) {
1106 // Finish adding all newly acked packets.
1107 return;
1108 }
1109 end = std::min(end, acked_packets_iter_->min());
1110 ++acked_packets_iter_;
1111 } while (start < end);
1112}
1113
1114void QuicSentPacketManager::OnAckTimestamp(QuicPacketNumber packet_number,
1115 QuicTime timestamp) {
1116 last_ack_frame_.received_packet_times.push_back({packet_number, timestamp});
1117 for (AckedPacket& packet : packets_acked_) {
1118 if (packet.packet_number == packet_number) {
1119 packet.receive_timestamp = timestamp;
1120 return;
1121 }
1122 }
1123}
1124
1125bool QuicSentPacketManager::OnAckFrameEnd(QuicTime ack_receive_time) {
1126 QuicByteCount prior_bytes_in_flight = unacked_packets_.bytes_in_flight();
1127 // Reverse packets_acked_ so that it is in ascending order.
1128 reverse(packets_acked_.begin(), packets_acked_.end());
1129 for (AckedPacket& acked_packet : packets_acked_) {
1130 QuicTransmissionInfo* info =
1131 unacked_packets_.GetMutableTransmissionInfo(acked_packet.packet_number);
1132 if (!QuicUtils::IsAckable(info->state)) {
1133 if (info->state == ACKED) {
1134 QUIC_BUG << "Trying to ack an already acked packet: "
1135 << acked_packet.packet_number
1136 << ", last_ack_frame_: " << last_ack_frame_
1137 << ", least_unacked: " << unacked_packets_.GetLeastUnacked()
1138 << ", packets_acked_: " << packets_acked_;
1139 } else {
1140 QUIC_PEER_BUG << "Received ack for unackable packet: "
1141 << acked_packet.packet_number << " with state: "
1142 << QuicUtils::SentPacketStateToString(info->state);
1143 }
1144 continue;
1145 }
1146 QUIC_DVLOG(1) << ENDPOINT << "Got an ack for packet "
1147 << acked_packet.packet_number;
1148 last_ack_frame_.packets.Add(acked_packet.packet_number);
1149 if (info->largest_acked.IsInitialized()) {
1150 if (largest_packet_peer_knows_is_acked_.IsInitialized()) {
1151 largest_packet_peer_knows_is_acked_ =
1152 std::max(largest_packet_peer_knows_is_acked_, info->largest_acked);
1153 } else {
1154 largest_packet_peer_knows_is_acked_ = info->largest_acked;
1155 }
1156 }
1157 // If data is associated with the most recent transmission of this
1158 // packet, then inform the caller.
1159 if (info->in_flight) {
1160 acked_packet.bytes_acked = info->bytes_sent;
1161 } else {
1162 // Unackable packets are skipped earlier.
1163 largest_newly_acked_ = acked_packet.packet_number;
1164 }
1165 if (unacked_packets_.use_uber_loss_algorithm()) {
1166 unacked_packets_.MaybeUpdateLargestAckedOfPacketNumberSpace(
1167 info->encryption_level, acked_packet.packet_number);
1168 }
1169 MarkPacketHandled(acked_packet.packet_number, info,
1170 last_ack_frame_.ack_delay_time);
1171 }
1172 const bool acked_new_packet = !packets_acked_.empty();
1173 PostProcessAfterMarkingPacketHandled(last_ack_frame_, ack_receive_time,
1174 rtt_updated_, prior_bytes_in_flight);
1175
1176 return acked_new_packet;
1177}
1178
1179void QuicSentPacketManager::SetDebugDelegate(DebugDelegate* debug_delegate) {
1180 debug_delegate_ = debug_delegate;
1181}
1182
1183void QuicSentPacketManager::OnApplicationLimited() {
1184 if (using_pacing_) {
1185 pacing_sender_.OnApplicationLimited();
1186 }
1187 send_algorithm_->OnApplicationLimited(unacked_packets_.bytes_in_flight());
1188 if (debug_delegate_ != nullptr) {
1189 debug_delegate_->OnApplicationLimited();
1190 }
1191}
1192
1193QuicTime QuicSentPacketManager::GetNextReleaseTime() const {
1194 return using_pacing_ ? pacing_sender_.ideal_next_packet_send_time()
1195 : QuicTime::Zero();
1196}
1197
1198void QuicSentPacketManager::SetInitialRtt(QuicTime::Delta rtt) {
1199 const QuicTime::Delta min_rtt =
1200 QuicTime::Delta::FromMicroseconds(kMinInitialRoundTripTimeUs);
1201 const QuicTime::Delta max_rtt =
1202 QuicTime::Delta::FromMicroseconds(kMaxInitialRoundTripTimeUs);
1203 rtt_stats_.set_initial_rtt(std::max(min_rtt, std::min(max_rtt, rtt)));
1204}
1205
1206#undef ENDPOINT // undef for jumbo builds
1207} // namespace quic