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