1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/quic/quic_packet_generator.h"
7 #include "base/basictypes.h"
8 #include "base/logging.h"
9 #include "net/quic/quic_ack_notifier.h"
10 #include "net/quic/quic_fec_group.h"
11 #include "net/quic/quic_flags.h"
12 #include "net/quic/quic_utils.h"
14 using base::StringPiece
;
20 // We want to put some space between a protected packet and the FEC packet to
21 // avoid losing them both within the same loss episode. On the other hand, we
22 // expect to be able to recover from any loss in about an RTT. We resolve this
23 // tradeoff by sending an FEC packet atmost half an RTT, or equivalently, half
24 // the max number of in-flight packets, the first protected packet. Since we
25 // don't want to delay an FEC packet past half an RTT, we set the max FEC group
26 // size to be half the current congestion window.
27 const float kMaxPacketsInFlightMultiplierForFecGroupSize
= 0.5;
28 const float kRttMultiplierForFecTimeout
= 0.5;
30 // Minimum timeout for FEC alarm, set to half the minimum Tail Loss Probe
32 const int64 kMinFecTimeoutMs
= 5u;
36 class QuicAckNotifier
;
38 QuicPacketGenerator::QuicPacketGenerator(QuicConnectionId connection_id
,
40 QuicRandom
* random_generator
,
41 DelegateInterface
* delegate
)
42 : delegate_(delegate
),
43 debug_delegate_(nullptr),
44 packet_creator_(connection_id
, framer
, random_generator
),
46 fec_timeout_(QuicTime::Delta::Zero()),
47 should_fec_protect_(false),
48 should_send_ack_(false),
49 should_send_stop_waiting_(false),
51 stop_waiting_queued_(false) {
54 QuicPacketGenerator::~QuicPacketGenerator() {
55 for (QuicFrames::iterator it
= queued_control_frames_
.begin();
56 it
!= queued_control_frames_
.end(); ++it
) {
59 delete it
->padding_frame
;
62 delete it
->stream_frame
;
67 case RST_STREAM_FRAME
:
68 delete it
->rst_stream_frame
;
70 case CONNECTION_CLOSE_FRAME
:
71 delete it
->connection_close_frame
;
74 delete it
->goaway_frame
;
76 case WINDOW_UPDATE_FRAME
:
77 delete it
->window_update_frame
;
80 delete it
->blocked_frame
;
82 case STOP_WAITING_FRAME
:
83 delete it
->stop_waiting_frame
;
86 delete it
->ping_frame
;
89 DCHECK(false) << "Cannot delete type: " << it
->type
;
94 void QuicPacketGenerator::OnCongestionWindowChange(
95 QuicPacketCount max_packets_in_flight
) {
96 packet_creator_
.set_max_packets_per_fec_group(
97 static_cast<size_t>(kMaxPacketsInFlightMultiplierForFecGroupSize
*
98 max_packets_in_flight
));
101 void QuicPacketGenerator::OnRttChange(QuicTime::Delta rtt
) {
102 fec_timeout_
= rtt
.Multiply(kRttMultiplierForFecTimeout
);
105 void QuicPacketGenerator::SetShouldSendAck(bool also_send_stop_waiting
) {
107 // Ack already queued, nothing to do.
111 if (also_send_stop_waiting
&& stop_waiting_queued_
) {
112 LOG(DFATAL
) << "Should only ever be one pending stop waiting frame.";
116 should_send_ack_
= true;
117 should_send_stop_waiting_
= also_send_stop_waiting
;
118 SendQueuedFrames(false);
121 void QuicPacketGenerator::AddControlFrame(const QuicFrame
& frame
) {
122 queued_control_frames_
.push_back(frame
);
123 SendQueuedFrames(false);
126 QuicConsumedData
QuicPacketGenerator::ConsumeData(
128 const IOVector
& data_to_write
,
129 QuicStreamOffset offset
,
131 FecProtection fec_protection
,
132 QuicAckNotifier::DelegateInterface
* delegate
) {
133 bool has_handshake
= id
== kCryptoStreamId
;
134 // To make reasoning about crypto frames easier, we don't combine them with
135 // other retransmittable frames in a single packet.
137 has_handshake
&& packet_creator_
.HasPendingRetransmittableFrames();
138 SendQueuedFrames(flush
);
140 size_t total_bytes_consumed
= 0;
141 bool fin_consumed
= false;
143 if (!packet_creator_
.HasRoomForStreamFrame(id
, offset
)) {
144 SerializeAndSendPacket();
147 if (fec_protection
== MUST_FEC_PROTECT
) {
148 MaybeStartFecProtection();
151 // This notifier will be owned by the AckNotifierManager (or deleted below) if
152 // not attached to a packet.
153 QuicAckNotifier
* notifier
= nullptr;
154 if (delegate
!= nullptr) {
155 notifier
= new QuicAckNotifier(delegate
);
158 IOVector data
= data_to_write
;
159 size_t data_size
= data
.TotalBufferSize();
160 if (!fin
&& (data_size
== 0)) {
161 LOG(DFATAL
) << "Attempt to consume empty data without FIN.";
162 return QuicConsumedData(0, false);
165 int frames_created
= 0;
166 while (delegate_
->ShouldGeneratePacket(
167 NOT_RETRANSMISSION
, HAS_RETRANSMITTABLE_DATA
,
168 has_handshake
? IS_HANDSHAKE
: NOT_HANDSHAKE
)) {
170 size_t bytes_consumed
= packet_creator_
.CreateStreamFrame(
171 id
, data
, offset
+ total_bytes_consumed
, fin
, &frame
);
174 // We want to track which packet this stream frame ends up in.
175 if (notifier
!= nullptr) {
176 ack_notifiers_
.push_back(notifier
);
179 if (!AddFrame(frame
)) {
180 LOG(DFATAL
) << "Failed to add stream frame.";
181 // Inability to add a STREAM frame creates an unrecoverable hole in a
182 // the stream, so it's best to close the connection.
183 delegate_
->CloseConnection(QUIC_INTERNAL_ERROR
, false);
185 return QuicConsumedData(0, false);
188 total_bytes_consumed
+= bytes_consumed
;
189 fin_consumed
= fin
&& total_bytes_consumed
== data_size
;
190 data
.Consume(bytes_consumed
);
191 DCHECK(data
.Empty() || packet_creator_
.BytesFree() == 0u);
193 // TODO(ianswett): Restore packet reordering.
194 if (!InBatchMode() || !packet_creator_
.HasRoomForStreamFrame(id
, offset
)) {
195 SerializeAndSendPacket();
199 // We're done writing the data. Exit the loop.
200 // We don't make this a precondition because we could have 0 bytes of data
201 // if we're simply writing a fin.
202 if (fec_protection
== MUST_FEC_PROTECT
) {
203 // Turn off FEC protection when we're done writing protected data.
204 DVLOG(1) << "Turning FEC protection OFF";
205 should_fec_protect_
= false;
211 if (notifier
!= nullptr && frames_created
== 0) {
212 // Safe to delete the AckNotifer as it was never attached to a packet.
216 // Don't allow the handshake to be bundled with other retransmittable frames.
218 SendQueuedFrames(true);
221 // Try to close FEC group since we've either run out of data to send or we're
222 // blocked. If not in batch mode, force close the group.
223 MaybeSendFecPacketAndCloseGroup(/*force=*/false);
225 DCHECK(InBatchMode() || !packet_creator_
.HasPendingFrames());
226 return QuicConsumedData(total_bytes_consumed
, fin_consumed
);
229 bool QuicPacketGenerator::CanSendWithNextPendingFrameAddition() const {
230 DCHECK(HasPendingFrames());
231 HasRetransmittableData retransmittable
=
232 (should_send_ack_
|| should_send_stop_waiting_
)
233 ? NO_RETRANSMITTABLE_DATA
234 : HAS_RETRANSMITTABLE_DATA
;
235 if (retransmittable
== HAS_RETRANSMITTABLE_DATA
) {
236 DCHECK(!queued_control_frames_
.empty()); // These are retransmittable.
238 return delegate_
->ShouldGeneratePacket(NOT_RETRANSMISSION
, retransmittable
,
242 void QuicPacketGenerator::SendQueuedFrames(bool flush
) {
243 // Only add pending frames if we are SURE we can then send the whole packet.
244 while (HasPendingFrames() &&
245 (flush
|| CanSendWithNextPendingFrameAddition())) {
246 if (!AddNextPendingFrame()) {
247 // Packet was full, so serialize and send it.
248 SerializeAndSendPacket();
251 if (packet_creator_
.HasPendingFrames() && (flush
|| !InBatchMode())) {
252 SerializeAndSendPacket();
254 MaybeSendFecPacketAndCloseGroup(flush
);
257 void QuicPacketGenerator::MaybeStartFecProtection() {
258 if (!packet_creator_
.IsFecEnabled()) {
261 DVLOG(1) << "Turning FEC protection ON";
262 should_fec_protect_
= true;
263 if (packet_creator_
.IsFecProtected()) {
264 // Only start creator's FEC protection if not already on.
267 if (HasQueuedFrames()) {
268 // TODO(jri): This currently requires that the generator flush out any
269 // pending frames when FEC protection is turned on. If current packet can be
270 // converted to an FEC protected packet, do it. This will require the
271 // generator to check if the resulting expansion still allows the incoming
272 // frame to be added to the packet.
273 SendQueuedFrames(true);
275 packet_creator_
.StartFecProtectingPackets();
276 DCHECK(packet_creator_
.IsFecProtected());
279 void QuicPacketGenerator::MaybeSendFecPacketAndCloseGroup(bool force
) {
280 if (!ShouldSendFecPacket(force
)) {
283 // TODO(jri): SerializeFec can return a NULL packet, and this should
284 // cause an early return, with a call to delegate_->OnPacketGenerationError.
285 SerializedPacket serialized_fec
= packet_creator_
.SerializeFec();
286 DCHECK(serialized_fec
.packet
);
287 delegate_
->OnSerializedPacket(serialized_fec
);
288 // Turn FEC protection off if creator's protection is on and the creator
289 // does not have an open FEC group.
290 // Note: We only wait until the frames queued in the creator are flushed;
291 // pending frames in the generator will not keep us from turning FEC off.
292 if (!should_fec_protect_
&& !packet_creator_
.IsFecGroupOpen()) {
293 packet_creator_
.StopFecProtectingPackets();
294 DCHECK(!packet_creator_
.IsFecProtected());
298 bool QuicPacketGenerator::ShouldSendFecPacket(bool force
) {
299 return packet_creator_
.IsFecProtected() &&
300 !packet_creator_
.HasPendingFrames() &&
301 packet_creator_
.ShouldSendFec(force
);
304 void QuicPacketGenerator::OnFecTimeout() {
305 DCHECK(!InBatchMode());
306 if (!ShouldSendFecPacket(true)) {
307 LOG(DFATAL
) << "No FEC packet to send on FEC timeout.";
310 // Flush out any pending frames in the generator and the creator, and then
311 // send out FEC packet.
312 SendQueuedFrames(true);
313 MaybeSendFecPacketAndCloseGroup(/*force=*/true);
316 QuicTime::Delta
QuicPacketGenerator::GetFecTimeout(
317 QuicPacketSequenceNumber sequence_number
) {
318 // Do not set up FEC alarm for |sequence_number| it is not the first packet in
319 // the current group.
320 if (packet_creator_
.IsFecGroupOpen() &&
321 (sequence_number
== packet_creator_
.fec_group_number())) {
322 return QuicTime::Delta::Max(
323 fec_timeout_
, QuicTime::Delta::FromMilliseconds(kMinFecTimeoutMs
));
325 return QuicTime::Delta::Infinite();
328 bool QuicPacketGenerator::InBatchMode() {
332 void QuicPacketGenerator::StartBatchOperations() {
336 void QuicPacketGenerator::FinishBatchOperations() {
338 SendQueuedFrames(false);
341 void QuicPacketGenerator::FlushAllQueuedFrames() {
342 SendQueuedFrames(true);
345 bool QuicPacketGenerator::HasQueuedFrames() const {
346 return packet_creator_
.HasPendingFrames() || HasPendingFrames();
349 bool QuicPacketGenerator::HasPendingFrames() const {
350 return should_send_ack_
|| should_send_stop_waiting_
||
351 !queued_control_frames_
.empty();
354 bool QuicPacketGenerator::AddNextPendingFrame() {
355 if (should_send_ack_
) {
356 delegate_
->PopulateAckFrame(&pending_ack_frame_
);
358 // If we can't this add the frame now, then we still need to do so later.
359 should_send_ack_
= !AddFrame(QuicFrame(&pending_ack_frame_
));
360 // Return success if we have cleared out this flag (i.e., added the frame).
361 // If we still need to send, then the frame is full, and we have failed.
362 return !should_send_ack_
;
365 if (should_send_stop_waiting_
) {
366 delegate_
->PopulateStopWaitingFrame(&pending_stop_waiting_frame_
);
367 stop_waiting_queued_
= true;
368 // If we can't this add the frame now, then we still need to do so later.
369 should_send_stop_waiting_
=
370 !AddFrame(QuicFrame(&pending_stop_waiting_frame_
));
371 // Return success if we have cleared out this flag (i.e., added the frame).
372 // If we still need to send, then the frame is full, and we have failed.
373 return !should_send_stop_waiting_
;
376 LOG_IF(DFATAL
, queued_control_frames_
.empty())
377 << "AddNextPendingFrame called with no queued control frames.";
378 if (!AddFrame(queued_control_frames_
.back())) {
382 queued_control_frames_
.pop_back();
386 bool QuicPacketGenerator::AddFrame(const QuicFrame
& frame
) {
387 bool success
= packet_creator_
.AddSavedFrame(frame
);
388 if (success
&& debug_delegate_
) {
389 debug_delegate_
->OnFrameAddedToPacket(frame
);
394 void QuicPacketGenerator::SerializeAndSendPacket() {
395 SerializedPacket serialized_packet
= packet_creator_
.SerializePacket();
396 DCHECK(serialized_packet
.packet
);
398 // There may be AckNotifiers interested in this packet.
399 serialized_packet
.notifiers
.swap(ack_notifiers_
);
400 ack_notifiers_
.clear();
402 delegate_
->OnSerializedPacket(serialized_packet
);
403 MaybeSendFecPacketAndCloseGroup(/*force=*/false);
405 // The packet has now been serialized, so the frames are no longer queued.
407 stop_waiting_queued_
= false;
410 void QuicPacketGenerator::StopSendingVersion() {
411 packet_creator_
.StopSendingVersion();
414 QuicPacketSequenceNumber
QuicPacketGenerator::sequence_number() const {
415 return packet_creator_
.sequence_number();
418 QuicByteCount
QuicPacketGenerator::max_packet_length() const {
419 return packet_creator_
.max_packet_length();
422 void QuicPacketGenerator::set_max_packet_length(QuicByteCount length
) {
423 packet_creator_
.SetMaxPacketLength(length
);
426 QuicEncryptedPacket
* QuicPacketGenerator::SerializeVersionNegotiationPacket(
427 const QuicVersionVector
& supported_versions
) {
428 return packet_creator_
.SerializeVersionNegotiationPacket(supported_versions
);
431 SerializedPacket
QuicPacketGenerator::ReserializeAllFrames(
432 const RetransmittableFrames
& frames
,
433 QuicSequenceNumberLength original_length
) {
434 return packet_creator_
.ReserializeAllFrames(frames
, original_length
);
437 void QuicPacketGenerator::UpdateSequenceNumberLength(
438 QuicPacketSequenceNumber least_packet_awaited_by_peer
,
439 QuicPacketCount max_packets_in_flight
) {
440 return packet_creator_
.UpdateSequenceNumberLength(
441 least_packet_awaited_by_peer
, max_packets_in_flight
);
444 void QuicPacketGenerator::SetConnectionIdLength(uint32 length
) {
446 packet_creator_
.set_connection_id_length(PACKET_0BYTE_CONNECTION_ID
);
447 } else if (length
== 1) {
448 packet_creator_
.set_connection_id_length(PACKET_1BYTE_CONNECTION_ID
);
449 } else if (length
<= 4) {
450 packet_creator_
.set_connection_id_length(PACKET_4BYTE_CONNECTION_ID
);
452 packet_creator_
.set_connection_id_length(PACKET_8BYTE_CONNECTION_ID
);
457 void QuicPacketGenerator::set_encryption_level(EncryptionLevel level
) {
458 packet_creator_
.set_encryption_level(level
);
461 void QuicPacketGenerator::SetEncrypter(EncryptionLevel level
,
462 QuicEncrypter
* encrypter
) {
463 packet_creator_
.SetEncrypter(level
, encrypter
);