Land Recent QUIC Changes.
[chromium-blink-merge.git] / net / quic / quic_sent_packet_manager.h
blob96891cba16b634493c726cea33ee284227d723db
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 #ifndef NET_QUIC_QUIC_SENT_PACKET_MANAGER_H_
6 #define NET_QUIC_QUIC_SENT_PACKET_MANAGER_H_
8 #include <map>
9 #include <set>
10 #include <utility>
11 #include <vector>
13 #include "base/containers/hash_tables.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "net/base/linked_hash_map.h"
16 #include "net/quic/congestion_control/loss_detection_interface.h"
17 #include "net/quic/congestion_control/rtt_stats.h"
18 #include "net/quic/congestion_control/send_algorithm_interface.h"
19 #include "net/quic/crypto/cached_network_parameters.h"
20 #include "net/quic/quic_ack_notifier_manager.h"
21 #include "net/quic/quic_protocol.h"
22 #include "net/quic/quic_sustained_bandwidth_recorder.h"
23 #include "net/quic/quic_unacked_packet_map.h"
25 namespace net {
27 namespace test {
28 class QuicConnectionPeer;
29 class QuicSentPacketManagerPeer;
30 } // namespace test
32 class QuicClock;
33 class QuicConfig;
34 struct QuicConnectionStats;
36 // Class which tracks the set of packets sent on a QUIC connection and contains
37 // a send algorithm to decide when to send new packets. It keeps track of any
38 // retransmittable data associated with each packet. If a packet is
39 // retransmitted, it will keep track of each version of a packet so that if a
40 // previous transmission is acked, the data will not be retransmitted.
41 class NET_EXPORT_PRIVATE QuicSentPacketManager {
42 public:
43 // Interface which gets callbacks from the QuicSentPacketManager at
44 // interesting points. Implementations must not mutate the state of
45 // the packet manager or connection as a result of these callbacks.
46 class NET_EXPORT_PRIVATE DebugDelegate {
47 public:
48 virtual ~DebugDelegate() {}
50 // Called when a spurious retransmission is detected.
51 virtual void OnSpuriousPacketRetransmition(
52 TransmissionType transmission_type,
53 QuicByteCount byte_size) {}
55 virtual void OnIncomingAck(
56 const QuicAckFrame& ack_frame,
57 QuicTime ack_receive_time,
58 QuicPacketSequenceNumber largest_observed,
59 bool rtt_updated,
60 QuicPacketSequenceNumber least_unacked_sent_packet) {}
63 // Interface which gets callbacks from the QuicSentPacketManager when
64 // network-related state changes. Implementations must not mutate the
65 // state of the packet manager as a result of these callbacks.
66 class NET_EXPORT_PRIVATE NetworkChangeVisitor {
67 public:
68 virtual ~NetworkChangeVisitor() {}
70 // Called when congestion window may have changed.
71 virtual void OnCongestionWindowChange() = 0;
72 // TODO(jri): Add OnRttStatsChange() to this class as well.
75 // Struct to store the pending retransmission information.
76 struct PendingRetransmission {
77 PendingRetransmission(QuicPacketSequenceNumber sequence_number,
78 TransmissionType transmission_type,
79 const RetransmittableFrames& retransmittable_frames,
80 QuicSequenceNumberLength sequence_number_length)
81 : sequence_number(sequence_number),
82 transmission_type(transmission_type),
83 retransmittable_frames(retransmittable_frames),
84 sequence_number_length(sequence_number_length) {
87 QuicPacketSequenceNumber sequence_number;
88 TransmissionType transmission_type;
89 const RetransmittableFrames& retransmittable_frames;
90 QuicSequenceNumberLength sequence_number_length;
93 QuicSentPacketManager(bool is_server,
94 const QuicClock* clock,
95 QuicConnectionStats* stats,
96 CongestionControlType congestion_control_type,
97 LossDetectionType loss_type,
98 bool is_secure);
99 virtual ~QuicSentPacketManager();
101 virtual void SetFromConfig(const QuicConfig& config);
103 // Pass the CachedNetworkParameters to the send algorithm.
104 // Returns true if this changes the initial connection state.
105 bool ResumeConnectionState(
106 const CachedNetworkParameters& cached_network_params);
108 void SetNumOpenStreams(size_t num_streams);
110 void SetHandshakeConfirmed() { handshake_confirmed_ = true; }
112 // Processes the incoming ack.
113 void OnIncomingAck(const QuicAckFrame& ack_frame,
114 QuicTime ack_receive_time);
116 // Returns true if the non-FEC packet |sequence_number| is unacked.
117 bool IsUnacked(QuicPacketSequenceNumber sequence_number) const;
119 // Requests retransmission of all unacked packets of |retransmission_type|.
120 // The behavior of this method depends on the value of |retransmission_type|:
121 // ALL_UNACKED_RETRANSMISSION - All unacked packets will be retransmitted.
122 // This can happen, for example, after a version negotiation packet has been
123 // received and all packets needs to be retransmitted with the new version.
124 // ALL_INITIAL_RETRANSMISSION - Only initially encrypted packets will be
125 // retransmitted. This can happen, for example, when a CHLO has been rejected
126 // and the previously encrypted data needs to be encrypted with a new key.
127 void RetransmitUnackedPackets(TransmissionType retransmission_type);
129 // Retransmits the oldest pending packet there is still a tail loss probe
130 // pending. Invoked after OnRetransmissionTimeout.
131 bool MaybeRetransmitTailLossProbe();
133 // Removes the retransmittable frames from all unencrypted packets to ensure
134 // they don't get retransmitted.
135 void NeuterUnencryptedPackets();
137 // Returns true if the unacked packet |sequence_number| has retransmittable
138 // frames. This will only return false if the packet has been acked, if a
139 // previous transmission of this packet was ACK'd, or if this packet has been
140 // retransmitted as with different sequence number.
141 bool HasRetransmittableFrames(QuicPacketSequenceNumber sequence_number) const;
143 // Returns true if there are pending retransmissions.
144 bool HasPendingRetransmissions() const;
146 // Retrieves the next pending retransmission.
147 PendingRetransmission NextPendingRetransmission();
149 bool HasUnackedPackets() const;
151 // Returns the smallest sequence number of a serialized packet which has not
152 // been acked by the peer.
153 QuicPacketSequenceNumber GetLeastUnacked() const;
155 // Called when a congestion feedback frame is received from peer.
156 virtual void OnIncomingQuicCongestionFeedbackFrame(
157 const QuicCongestionFeedbackFrame& frame,
158 const QuicTime& feedback_receive_time);
160 // Called when we have sent bytes to the peer. This informs the manager both
161 // the number of bytes sent and if they were retransmitted. Returns true if
162 // the sender should reset the retransmission timer.
163 virtual bool OnPacketSent(SerializedPacket* serialized_packet,
164 QuicPacketSequenceNumber original_sequence_number,
165 QuicTime sent_time,
166 QuicByteCount bytes,
167 TransmissionType transmission_type,
168 HasRetransmittableData has_retransmittable_data);
170 // Called when the retransmission timer expires.
171 virtual void OnRetransmissionTimeout();
173 // Calculate the time until we can send the next packet to the wire.
174 // Note 1: When kUnknownWaitTime is returned, there is no need to poll
175 // TimeUntilSend again until we receive an OnIncomingAckFrame event.
176 // Note 2: Send algorithms may or may not use |retransmit| in their
177 // calculations.
178 virtual QuicTime::Delta TimeUntilSend(QuicTime now,
179 HasRetransmittableData retransmittable);
181 // Returns amount of time for delayed ack timer.
182 const QuicTime::Delta DelayedAckTime() const;
184 // Returns the current delay for the retransmission timer, which may send
185 // either a tail loss probe or do a full RTO. Returns QuicTime::Zero() if
186 // there are no retransmittable packets.
187 const QuicTime GetRetransmissionTime() const;
189 const RttStats* GetRttStats() const;
191 // Returns the estimated bandwidth calculated by the congestion algorithm.
192 QuicBandwidth BandwidthEstimate() const;
194 // Returns true if the current instantaneous bandwidth estimate is reliable.
195 bool HasReliableBandwidthEstimate() const;
197 const QuicSustainedBandwidthRecorder& SustainedBandwidthRecorder() const;
199 // Returns the size of the current congestion window in number of
200 // kDefaultTCPMSS-sized segments. Note, this is not the *available* window.
201 // Some send algorithms may not use a congestion window and will return 0.
202 QuicPacketCount GetCongestionWindowInTcpMss() const;
204 // Returns the number of packets of length |max_packet_length| which fit in
205 // the current congestion window. More packets may end up in flight if the
206 // congestion window has been recently reduced, of if non-full packets are
207 // sent.
208 QuicPacketCount EstimateMaxPacketsInFlight(
209 QuicByteCount max_packet_length) const;
211 // Returns the size of the slow start congestion window in nume of 1460 byte
212 // TCP segments, aka ssthresh. Some send algorithms do not define a slow
213 // start threshold and will return 0.
214 QuicPacketCount GetSlowStartThresholdInTcpMss() const;
216 // Enables pacing if it has not already been enabled.
217 void EnablePacing();
219 bool using_pacing() const { return using_pacing_; }
221 void set_debug_delegate(DebugDelegate* debug_delegate) {
222 debug_delegate_ = debug_delegate;
225 QuicPacketSequenceNumber largest_observed() const {
226 return unacked_packets_.largest_observed();
229 QuicPacketSequenceNumber least_packet_awaited_by_peer() {
230 return least_packet_awaited_by_peer_;
233 void set_network_change_visitor(NetworkChangeVisitor* visitor) {
234 DCHECK(!network_change_visitor_);
235 DCHECK(visitor);
236 network_change_visitor_ = visitor;
239 size_t consecutive_rto_count() const {
240 return consecutive_rto_count_;
243 size_t consecutive_tlp_count() const {
244 return consecutive_tlp_count_;
247 private:
248 friend class test::QuicConnectionPeer;
249 friend class test::QuicSentPacketManagerPeer;
251 // The retransmission timer is a single timer which switches modes depending
252 // upon connection state.
253 enum RetransmissionTimeoutMode {
254 // A conventional TCP style RTO.
255 RTO_MODE,
256 // A tail loss probe. By default, QUIC sends up to two before RTOing.
257 TLP_MODE,
258 // Retransmission of handshake packets prior to handshake completion.
259 HANDSHAKE_MODE,
260 // Re-invoke the loss detection when a packet is not acked before the
261 // loss detection algorithm expects.
262 LOSS_MODE,
265 typedef linked_hash_map<QuicPacketSequenceNumber,
266 TransmissionType> PendingRetransmissionMap;
268 // Called when a packet is retransmitted with a new sequence number.
269 // Replaces the old entry in the unacked packet map with the new
270 // sequence number.
271 void OnRetransmittedPacket(QuicPacketSequenceNumber old_sequence_number,
272 QuicPacketSequenceNumber new_sequence_number);
274 // Updates the least_packet_awaited_by_peer.
275 void UpdatePacketInformationReceivedByPeer(const QuicAckFrame& ack_frame);
277 // Process the incoming ack looking for newly ack'd data packets.
278 void HandleAckForSentPackets(const QuicAckFrame& ack_frame);
280 // Returns the current retransmission mode.
281 RetransmissionTimeoutMode GetRetransmissionMode() const;
283 // Retransmits all crypto stream packets.
284 void RetransmitCryptoPackets();
286 // Retransmits all the packets and abandons by invoking a full RTO.
287 void RetransmitAllPackets();
289 // Returns the timer for retransmitting crypto handshake packets.
290 const QuicTime::Delta GetCryptoRetransmissionDelay() const;
292 // Returns the timer for a new tail loss probe.
293 const QuicTime::Delta GetTailLossProbeDelay() const;
295 // Returns the retransmission timeout, after which a full RTO occurs.
296 const QuicTime::Delta GetRetransmissionDelay() const;
298 // Update the RTT if the ack is for the largest acked sequence number.
299 // Returns true if the rtt was updated.
300 bool MaybeUpdateRTT(const QuicAckFrame& ack_frame,
301 const QuicTime& ack_receive_time);
303 // Invokes the loss detection algorithm and loses and retransmits packets if
304 // necessary.
305 void InvokeLossDetection(QuicTime time);
307 // Invokes OnCongestionEvent if |rtt_updated| is true, there are pending acks,
308 // or pending losses. Clears pending acks and pending losses afterwards.
309 // |bytes_in_flight| is the number of bytes in flight before the losses or
310 // acks.
311 void MaybeInvokeCongestionEvent(bool rtt_updated,
312 QuicByteCount bytes_in_flight);
314 // Marks |sequence_number| as having been revived by the peer, but not
315 // received, so the packet remains pending if it is and the congestion control
316 // does not consider the packet acked.
317 void MarkPacketRevived(QuicPacketSequenceNumber sequence_number,
318 QuicTime::Delta delta_largest_observed);
320 // Removes the retransmittability and pending properties from the packet at
321 // |it| due to receipt by the peer. Returns an iterator to the next remaining
322 // unacked packet.
323 void MarkPacketHandled(QuicPacketSequenceNumber sequence_number,
324 const TransmissionInfo& info,
325 QuicTime::Delta delta_largest_observed);
327 // Request that |sequence_number| be retransmitted after the other pending
328 // retransmissions. Does not add it to the retransmissions if it's already
329 // a pending retransmission.
330 void MarkForRetransmission(QuicPacketSequenceNumber sequence_number,
331 TransmissionType transmission_type);
333 // Notify observers about spurious retransmits.
334 void RecordSpuriousRetransmissions(
335 const SequenceNumberList& all_transmissions,
336 QuicPacketSequenceNumber acked_sequence_number);
338 // Returns true if the client is sending or the server has received a
339 // connection option.
340 bool HasClientSentConnectionOption(const QuicConfig& config,
341 QuicTag tag) const;
343 // Newly serialized retransmittable and fec packets are added to this map,
344 // which contains owning pointers to any contained frames. If a packet is
345 // retransmitted, this map will contain entries for both the old and the new
346 // packet. The old packet's retransmittable frames entry will be nullptr,
347 // while the new packet's entry will contain the frames to retransmit.
348 // If the old packet is acked before the new packet, then the old entry will
349 // be removed from the map and the new entry's retransmittable frames will be
350 // set to nullptr.
351 QuicUnackedPacketMap unacked_packets_;
353 // Pending retransmissions which have not been packetized and sent yet.
354 PendingRetransmissionMap pending_retransmissions_;
356 // Tracks if the connection was created by the server.
357 bool is_server_;
359 // An AckNotifier can register to be informed when ACKs have been received for
360 // all packets that a given block of data was sent in. The AckNotifierManager
361 // maintains the currently active notifiers.
362 AckNotifierManager ack_notifier_manager_;
364 const QuicClock* clock_;
365 QuicConnectionStats* stats_;
366 DebugDelegate* debug_delegate_;
367 NetworkChangeVisitor* network_change_visitor_;
368 const QuicPacketCount initial_congestion_window_;
369 RttStats rtt_stats_;
370 scoped_ptr<SendAlgorithmInterface> send_algorithm_;
371 scoped_ptr<LossDetectionInterface> loss_algorithm_;
372 bool n_connection_simulation_;
374 // Receiver side buffer in bytes.
375 QuicByteCount receive_buffer_bytes_;
377 // Least sequence number which the peer is still waiting for.
378 QuicPacketSequenceNumber least_packet_awaited_by_peer_;
380 // Tracks the first RTO packet. If any packet before that packet gets acked,
381 // it indicates the RTO was spurious and should be reversed(F-RTO).
382 QuicPacketSequenceNumber first_rto_transmission_;
383 // Number of times the RTO timer has fired in a row without receiving an ack.
384 size_t consecutive_rto_count_;
385 // Number of times the tail loss probe has been sent.
386 size_t consecutive_tlp_count_;
387 // Number of times the crypto handshake has been retransmitted.
388 size_t consecutive_crypto_retransmission_count_;
389 // Number of pending transmissions of TLP or crypto packets.
390 size_t pending_timer_transmission_count_;
391 // Maximum number of tail loss probes to send before firing an RTO.
392 size_t max_tail_loss_probes_;
393 bool using_pacing_;
395 // Vectors packets acked and lost as a result of the last congestion event.
396 SendAlgorithmInterface::CongestionVector packets_acked_;
397 SendAlgorithmInterface::CongestionVector packets_lost_;
399 // Set to true after the crypto handshake has successfully completed. After
400 // this is true we no longer use HANDSHAKE_MODE, and further frames sent on
401 // the crypto stream (i.e. SCUP messages) are treated like normal
402 // retransmittable frames.
403 bool handshake_confirmed_;
405 // Records bandwidth from server to client in normal operation, over periods
406 // of time with no loss events.
407 QuicSustainedBandwidthRecorder sustained_bandwidth_recorder_;
409 DISALLOW_COPY_AND_ASSIGN(QuicSentPacketManager);
412 } // namespace net
414 #endif // NET_QUIC_QUIC_SENT_PACKET_MANAGER_H_