[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / net / quic / quic_sent_packet_manager.h
blob06fcfc8b31161b186dda71273ef95515bf86d798
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 OnSpuriousPacketRetransmission(
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;
73 // Called when RTT may have changed, including when an RTT is read from
74 // the config.
75 virtual void OnRttChange() = 0;
78 // Struct to store the pending retransmission information.
79 struct PendingRetransmission {
80 PendingRetransmission(QuicPacketSequenceNumber sequence_number,
81 TransmissionType transmission_type,
82 const RetransmittableFrames& retransmittable_frames,
83 QuicSequenceNumberLength sequence_number_length)
84 : sequence_number(sequence_number),
85 transmission_type(transmission_type),
86 retransmittable_frames(retransmittable_frames),
87 sequence_number_length(sequence_number_length) {
90 QuicPacketSequenceNumber sequence_number;
91 TransmissionType transmission_type;
92 const RetransmittableFrames& retransmittable_frames;
93 QuicSequenceNumberLength sequence_number_length;
96 QuicSentPacketManager(Perspective perspective,
97 const QuicClock* clock,
98 QuicConnectionStats* stats,
99 CongestionControlType congestion_control_type,
100 LossDetectionType loss_type,
101 bool is_secure);
102 virtual ~QuicSentPacketManager();
104 virtual void SetFromConfig(const QuicConfig& config);
106 // Pass the CachedNetworkParameters to the send algorithm.
107 // Returns true if this changes the initial connection state.
108 bool ResumeConnectionState(
109 const CachedNetworkParameters& cached_network_params,
110 bool max_bandwidth_resumption);
112 void SetNumOpenStreams(size_t num_streams);
114 void SetHandshakeConfirmed() { handshake_confirmed_ = true; }
116 // Processes the incoming ack.
117 void OnIncomingAck(const QuicAckFrame& ack_frame,
118 QuicTime ack_receive_time);
120 // Returns true if the non-FEC packet |sequence_number| is unacked.
121 bool IsUnacked(QuicPacketSequenceNumber sequence_number) const;
123 // Requests retransmission of all unacked packets of |retransmission_type|.
124 // The behavior of this method depends on the value of |retransmission_type|:
125 // ALL_UNACKED_RETRANSMISSION - All unacked packets will be retransmitted.
126 // This can happen, for example, after a version negotiation packet has been
127 // received and all packets needs to be retransmitted with the new version.
128 // ALL_INITIAL_RETRANSMISSION - Only initially encrypted packets will be
129 // retransmitted. This can happen, for example, when a CHLO has been rejected
130 // and the previously encrypted data needs to be encrypted with a new key.
131 void RetransmitUnackedPackets(TransmissionType retransmission_type);
133 // Retransmits the oldest pending packet there is still a tail loss probe
134 // pending. Invoked after OnRetransmissionTimeout.
135 bool MaybeRetransmitTailLossProbe();
137 // Removes the retransmittable frames from all unencrypted packets to ensure
138 // they don't get retransmitted.
139 void NeuterUnencryptedPackets();
141 // Returns true if the unacked packet |sequence_number| has retransmittable
142 // frames. This will only return false if the packet has been acked, if a
143 // previous transmission of this packet was ACK'd, or if this packet has been
144 // retransmitted as with different sequence number.
145 bool HasRetransmittableFrames(QuicPacketSequenceNumber sequence_number) const;
147 // Returns true if there are pending retransmissions.
148 bool HasPendingRetransmissions() const;
150 // Retrieves the next pending retransmission. You must ensure that
151 // there are pending retransmissions prior to calling this function.
152 PendingRetransmission NextPendingRetransmission();
154 bool HasUnackedPackets() const;
156 // Returns the smallest sequence number of a serialized packet which has not
157 // been acked by the peer.
158 QuicPacketSequenceNumber GetLeastUnacked() const;
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 // Called by the connection every time it receives a serialized packet.
217 void OnSerializedPacket(const SerializedPacket& serialized_packet);
219 // No longer retransmit data for |stream_id|.
220 void CancelRetransmissionsForStream(QuicStreamId stream_id);
222 // Enables pacing if it has not already been enabled.
223 void EnablePacing();
225 bool using_pacing() const { return using_pacing_; }
227 void set_debug_delegate(DebugDelegate* debug_delegate) {
228 debug_delegate_ = debug_delegate;
231 QuicPacketSequenceNumber largest_observed() const {
232 return unacked_packets_.largest_observed();
235 QuicPacketSequenceNumber least_packet_awaited_by_peer() {
236 return least_packet_awaited_by_peer_;
239 void set_network_change_visitor(NetworkChangeVisitor* visitor) {
240 DCHECK(!network_change_visitor_);
241 DCHECK(visitor);
242 network_change_visitor_ = visitor;
245 // Used in Chromium, but not in the server.
246 size_t consecutive_rto_count() const {
247 return consecutive_rto_count_;
250 // Used in Chromium, but not in the server.
251 size_t consecutive_tlp_count() const {
252 return consecutive_tlp_count_;
255 private:
256 friend class test::QuicConnectionPeer;
257 friend class test::QuicSentPacketManagerPeer;
259 // The retransmission timer is a single timer which switches modes depending
260 // upon connection state.
261 enum RetransmissionTimeoutMode {
262 // A conventional TCP style RTO.
263 RTO_MODE,
264 // A tail loss probe. By default, QUIC sends up to two before RTOing.
265 TLP_MODE,
266 // Retransmission of handshake packets prior to handshake completion.
267 HANDSHAKE_MODE,
268 // Re-invoke the loss detection when a packet is not acked before the
269 // loss detection algorithm expects.
270 LOSS_MODE,
273 typedef linked_hash_map<QuicPacketSequenceNumber,
274 TransmissionType> PendingRetransmissionMap;
276 // Updates the least_packet_awaited_by_peer.
277 void UpdatePacketInformationReceivedByPeer(const QuicAckFrame& ack_frame);
279 // Process the incoming ack looking for newly ack'd data packets.
280 void HandleAckForSentPackets(const QuicAckFrame& ack_frame);
282 // Returns the current retransmission mode.
283 RetransmissionTimeoutMode GetRetransmissionMode() const;
285 // Retransmits all crypto stream packets.
286 void RetransmitCryptoPackets();
288 // Retransmits two packets for an RTO and removes any non-retransmittable
289 // packets from flight.
290 void RetransmitRtoPackets();
292 // Returns the timer for retransmitting crypto handshake packets.
293 const QuicTime::Delta GetCryptoRetransmissionDelay() const;
295 // Returns the timer for a new tail loss probe.
296 const QuicTime::Delta GetTailLossProbeDelay() const;
298 // Returns the retransmission timeout, after which a full RTO occurs.
299 const QuicTime::Delta GetRetransmissionDelay() const;
301 // Update the RTT if the ack is for the largest acked sequence number.
302 // Returns true if the rtt was updated.
303 bool MaybeUpdateRTT(const QuicAckFrame& ack_frame,
304 const QuicTime& ack_receive_time);
306 // Invokes the loss detection algorithm and loses and retransmits packets if
307 // necessary.
308 void InvokeLossDetection(QuicTime time);
310 // Invokes OnCongestionEvent if |rtt_updated| is true, there are pending acks,
311 // or pending losses. Clears pending acks and pending losses afterwards.
312 // |bytes_in_flight| is the number of bytes in flight before the losses or
313 // acks.
314 void MaybeInvokeCongestionEvent(bool rtt_updated,
315 QuicByteCount bytes_in_flight);
317 // Marks |sequence_number| as having been revived by the peer, but not
318 // received, so the packet remains pending if it is and the congestion control
319 // does not consider the packet acked.
320 void MarkPacketRevived(QuicPacketSequenceNumber sequence_number,
321 QuicTime::Delta delta_largest_observed);
323 // Removes the retransmittability and pending properties from the packet at
324 // |it| due to receipt by the peer. Returns an iterator to the next remaining
325 // unacked packet.
326 void MarkPacketHandled(QuicPacketSequenceNumber sequence_number,
327 const TransmissionInfo& info,
328 QuicTime::Delta delta_largest_observed);
330 // Request that |sequence_number| be retransmitted after the other pending
331 // retransmissions. Does not add it to the retransmissions if it's already
332 // a pending retransmission.
333 void MarkForRetransmission(QuicPacketSequenceNumber sequence_number,
334 TransmissionType transmission_type);
336 // Notify observers about spurious retransmits.
337 void RecordSpuriousRetransmissions(
338 const SequenceNumberList& all_transmissions,
339 QuicPacketSequenceNumber acked_sequence_number);
341 // Returns true if the client is sending or the server has received a
342 // connection option.
343 bool HasClientSentConnectionOption(const QuicConfig& config,
344 QuicTag tag) const;
346 // Newly serialized retransmittable and fec packets are added to this map,
347 // which contains owning pointers to any contained frames. If a packet is
348 // retransmitted, this map will contain entries for both the old and the new
349 // packet. The old packet's retransmittable frames entry will be nullptr,
350 // while the new packet's entry will contain the frames to retransmit.
351 // If the old packet is acked before the new packet, then the old entry will
352 // be removed from the map and the new entry's retransmittable frames will be
353 // set to nullptr.
354 QuicUnackedPacketMap unacked_packets_;
356 // Pending retransmissions which have not been packetized and sent yet.
357 PendingRetransmissionMap pending_retransmissions_;
359 // Tracks if the connection was created by the server or the client.
360 Perspective perspective_;
362 // An AckNotifier can register to be informed when ACKs have been received for
363 // all packets that a given block of data was sent in. The AckNotifierManager
364 // maintains the currently active notifiers.
365 AckNotifierManager ack_notifier_manager_;
367 const QuicClock* clock_;
368 QuicConnectionStats* stats_;
369 DebugDelegate* debug_delegate_;
370 NetworkChangeVisitor* network_change_visitor_;
371 const QuicPacketCount initial_congestion_window_;
372 RttStats rtt_stats_;
373 scoped_ptr<SendAlgorithmInterface> send_algorithm_;
374 scoped_ptr<LossDetectionInterface> loss_algorithm_;
375 bool n_connection_simulation_;
377 // Receiver side buffer in bytes.
378 QuicByteCount receive_buffer_bytes_;
380 // Least sequence number which the peer is still waiting for.
381 QuicPacketSequenceNumber least_packet_awaited_by_peer_;
383 // Tracks the first RTO packet. If any packet before that packet gets acked,
384 // it indicates the RTO was spurious and should be reversed(F-RTO).
385 QuicPacketSequenceNumber first_rto_transmission_;
386 // Number of times the RTO timer has fired in a row without receiving an ack.
387 size_t consecutive_rto_count_;
388 // Number of times the tail loss probe has been sent.
389 size_t consecutive_tlp_count_;
390 // Number of times the crypto handshake has been retransmitted.
391 size_t consecutive_crypto_retransmission_count_;
392 // Number of pending transmissions of TLP, RTO, or crypto packets.
393 size_t pending_timer_transmission_count_;
394 // Maximum number of tail loss probes to send before firing an RTO.
395 size_t max_tail_loss_probes_;
396 bool using_pacing_;
397 // If true, use the new RTO with loss based CWND reduction instead of the send
398 // algorithms's OnRetransmissionTimeout to reduce the congestion window.
399 bool use_new_rto_;
401 // Vectors packets acked and lost as a result of the last congestion event.
402 SendAlgorithmInterface::CongestionVector packets_acked_;
403 SendAlgorithmInterface::CongestionVector packets_lost_;
405 // Set to true after the crypto handshake has successfully completed. After
406 // this is true we no longer use HANDSHAKE_MODE, and further frames sent on
407 // the crypto stream (i.e. SCUP messages) are treated like normal
408 // retransmittable frames.
409 bool handshake_confirmed_;
411 // Records bandwidth from server to client in normal operation, over periods
412 // of time with no loss events.
413 QuicSustainedBandwidthRecorder sustained_bandwidth_recorder_;
415 DISALLOW_COPY_AND_ASSIGN(QuicSentPacketManager);
418 } // namespace net
420 #endif // NET_QUIC_QUIC_SENT_PACKET_MANAGER_H_