Skip to main content

quiche/recovery/gcongestion/
recovery.rs

1use crate::packet;
2use crate::recovery::OnLossDetectionTimeoutOutcome;
3use crate::recovery::INITIAL_TIME_THRESHOLD_OVERHEAD;
4use crate::recovery::TIME_THRESHOLD_OVERHEAD_MULTIPLIER;
5use crate::Error;
6use crate::Result;
7
8use std::collections::VecDeque;
9use std::time::Duration;
10use std::time::Instant;
11
12use smallvec::SmallVec;
13
14#[cfg(feature = "qlog")]
15use qlog::events::EventData;
16
17#[cfg(feature = "qlog")]
18use crate::recovery::QlogMetrics;
19
20use crate::frame;
21
22use crate::recovery::bytes_in_flight::BytesInFlight;
23use crate::recovery::gcongestion::Bandwidth;
24use crate::recovery::rtt::RttStats;
25use crate::recovery::CongestionControlAlgorithm;
26use crate::recovery::HandshakeStatus;
27use crate::recovery::LossDetectionTimer;
28use crate::recovery::OnAckReceivedOutcome;
29use crate::recovery::RangeSet;
30use crate::recovery::RecoveryConfig;
31use crate::recovery::RecoveryOps;
32use crate::recovery::RecoveryStats;
33use crate::recovery::ReleaseDecision;
34use crate::recovery::Sent;
35use crate::recovery::StartupExit;
36use crate::recovery::GRANULARITY;
37use crate::recovery::INITIAL_PACKET_THRESHOLD;
38use crate::recovery::INITIAL_TIME_THRESHOLD;
39use crate::recovery::MAX_OUTSTANDING_NON_ACK_ELICITING;
40use crate::recovery::MAX_PACKET_THRESHOLD;
41use crate::recovery::MAX_PTO_PROBES_COUNT;
42use crate::recovery::PACKET_REORDER_TIME_THRESHOLD;
43
44use super::bbr2::BBRv2;
45use super::pacer::Pacer;
46use super::Acked;
47use super::Lost;
48
49// Congestion Control
50const MAX_WINDOW_PACKETS: usize = 20_000;
51
52#[derive(Debug)]
53struct SentPacket {
54    pkt_num: u64,
55    status: SentStatus,
56}
57
58#[derive(Debug)]
59enum SentStatus {
60    Sent {
61        time_sent: Instant,
62        ack_eliciting: bool,
63        in_flight: bool,
64        has_data: bool,
65        is_pmtud_probe: bool,
66        sent_bytes: usize,
67        frames: SmallVec<[frame::Frame; 1]>,
68    },
69    Acked,
70    Lost,
71}
72
73impl SentStatus {
74    fn ack(&mut self) -> Self {
75        std::mem::replace(self, SentStatus::Acked)
76    }
77
78    fn lose(&mut self) -> Self {
79        if !matches!(self, SentStatus::Acked) {
80            std::mem::replace(self, SentStatus::Lost)
81        } else {
82            SentStatus::Acked
83        }
84    }
85}
86
87#[derive(Default)]
88struct RecoveryEpoch {
89    /// The time the most recent ack-eliciting packet was sent.
90    time_of_last_ack_eliciting_packet: Option<Instant>,
91
92    /// The largest packet number acknowledged in the packet number space so
93    /// far.
94    largest_acked_packet: Option<u64>,
95
96    /// The time at which the next packet in that packet number space can be
97    /// considered lost based on exceeding the reordering window in time.
98    loss_time: Option<Instant>,
99
100    /// An association of packet numbers in a packet number space to information
101    /// about them.
102    sent_packets: VecDeque<SentPacket>,
103
104    loss_probes: usize,
105    pkts_in_flight: usize,
106
107    acked_frames: VecDeque<frame::Frame>,
108
109    // Frames scheduled for retransmission due to PTO are tracked
110    // separately so we can check that frames were drained before
111    // generating more PTO probes.
112    lost_frames_ack: VecDeque<frame::Frame>,
113    lost_frames_pto: VecDeque<frame::Frame>,
114
115    /// The largest packet number sent in the packet number space so far.
116    #[allow(dead_code)]
117    test_largest_sent_pkt_num_on_path: Option<u64>,
118}
119
120struct AckedDetectionResult {
121    acked_bytes: usize,
122    spurious_losses: usize,
123    spurious_pkt_thresh: Option<u64>,
124    has_ack_eliciting: bool,
125}
126
127struct LossDetectionResult {
128    lost_bytes: usize,
129    lost_packets: usize,
130
131    pmtud_lost_bytes: usize,
132    pmtud_lost_packets: SmallVec<[u64; 1]>,
133}
134
135impl RecoveryEpoch {
136    /// Discard the Epoch state and return the total size of unacked packets
137    /// that were discarded
138    fn discard(&mut self, cc: &mut Pacer) -> usize {
139        let unacked_bytes = self
140            .sent_packets
141            .drain(..)
142            .map(|p| {
143                if let SentPacket {
144                    status:
145                        SentStatus::Sent {
146                            in_flight,
147                            sent_bytes,
148                            ..
149                        },
150                    pkt_num,
151                } = p
152                {
153                    cc.on_packet_neutered(pkt_num);
154                    if in_flight {
155                        return sent_bytes;
156                    }
157                }
158                0
159            })
160            .sum();
161
162        std::mem::take(&mut self.sent_packets);
163        self.clear_lost_frames();
164        std::mem::take(&mut self.acked_frames);
165        self.time_of_last_ack_eliciting_packet = None;
166        self.loss_time = None;
167        self.loss_probes = 0;
168        self.pkts_in_flight = 0;
169
170        unacked_bytes
171    }
172
173    // `peer_sent_ack_ranges` should not be used without validation.
174    fn detect_and_remove_acked_packets(
175        &mut self, peer_sent_ack_ranges: &RangeSet, newly_acked: &mut Vec<Acked>,
176        skip_pn: Option<u64>, trace_id: &str,
177    ) -> Result<AckedDetectionResult> {
178        newly_acked.clear();
179
180        let mut acked_bytes = 0;
181        let mut spurious_losses = 0;
182        let mut spurious_pkt_thresh = None;
183        let mut has_ack_eliciting = false;
184
185        let largest_ack_received = peer_sent_ack_ranges.last().unwrap();
186        let largest_acked = self
187            .largest_acked_packet
188            .unwrap_or(0)
189            .max(largest_ack_received);
190
191        for peer_sent_range in peer_sent_ack_ranges.iter() {
192            if skip_pn.is_some_and(|skip_pn| peer_sent_range.contains(&skip_pn)) {
193                // https://www.rfc-editor.org/rfc/rfc9000#section-13.1
194                // An endpoint SHOULD treat receipt of an acknowledgment
195                // for a packet it did not send as
196                // a connection error of type PROTOCOL_VIOLATION
197                return Err(Error::OptimisticAckDetected);
198            }
199
200            // Because packets always have incrementing numbers, they are always
201            // in sorted order.
202            let start = if self
203                .sent_packets
204                .front()
205                .filter(|e| e.pkt_num >= peer_sent_range.start)
206                .is_some()
207            {
208                // Usually it will be the first packet.
209                0
210            } else {
211                self.sent_packets
212                    .binary_search_by_key(&peer_sent_range.start, |p| p.pkt_num)
213                    .unwrap_or_else(|e| e)
214            };
215
216            for SentPacket { pkt_num, status } in
217                self.sent_packets.range_mut(start..)
218            {
219                if *pkt_num < peer_sent_range.end {
220                    match status.ack() {
221                        SentStatus::Sent {
222                            time_sent,
223                            in_flight,
224                            sent_bytes,
225                            frames,
226                            ack_eliciting,
227                            ..
228                        } => {
229                            if in_flight {
230                                self.pkts_in_flight -= 1;
231                                acked_bytes += sent_bytes;
232                            }
233                            newly_acked.push(Acked {
234                                pkt_num: *pkt_num,
235                                time_sent,
236                            });
237
238                            self.acked_frames.extend(frames);
239
240                            has_ack_eliciting |= ack_eliciting;
241
242                            trace!("{trace_id} packet newly acked {pkt_num}");
243                        },
244
245                        SentStatus::Acked => {},
246                        SentStatus::Lost => {
247                            // An acked packet was already declared lost
248                            spurious_losses += 1;
249                            spurious_pkt_thresh
250                                .get_or_insert(largest_acked - *pkt_num + 1);
251                        },
252                    }
253                } else {
254                    break;
255                }
256            }
257        }
258
259        self.drain_acked_and_lost_packets();
260
261        Ok(AckedDetectionResult {
262            acked_bytes,
263            spurious_losses,
264            spurious_pkt_thresh,
265            has_ack_eliciting,
266        })
267    }
268
269    fn detect_and_remove_lost_packets(
270        &mut self, loss_delay: Duration, pkt_thresh: Option<u64>, now: Instant,
271        newly_lost: &mut Vec<Lost>,
272    ) -> LossDetectionResult {
273        newly_lost.clear();
274        let mut lost_bytes = 0;
275        self.loss_time = None;
276
277        let lost_send_time = now.checked_sub(loss_delay).unwrap();
278        let largest_acked = self.largest_acked_packet.unwrap_or(0);
279        let mut pmtud_lost_bytes = 0;
280        let mut pmtud_lost_packets = SmallVec::new();
281
282        for SentPacket { pkt_num, status } in &mut self.sent_packets {
283            if *pkt_num > largest_acked {
284                break;
285            }
286
287            if let SentStatus::Sent { time_sent, .. } = status {
288                let loss_by_time = *time_sent <= lost_send_time;
289                let loss_by_pkt = match pkt_thresh {
290                    Some(pkt_thresh) => largest_acked >= *pkt_num + pkt_thresh,
291                    None => false,
292                };
293
294                if loss_by_time || loss_by_pkt {
295                    if let SentStatus::Sent {
296                        in_flight,
297                        sent_bytes,
298                        frames,
299                        is_pmtud_probe,
300                        ..
301                    } = status.lose()
302                    {
303                        self.lost_frames_ack.extend(frames);
304
305                        if in_flight {
306                            self.pkts_in_flight -= 1;
307
308                            if is_pmtud_probe {
309                                pmtud_lost_bytes += sent_bytes;
310                                pmtud_lost_packets.push(*pkt_num);
311                                // Do not track PMTUD probes losses
312                                continue;
313                            }
314
315                            lost_bytes += sent_bytes;
316                        }
317
318                        newly_lost.push(Lost {
319                            packet_number: *pkt_num,
320                            bytes_lost: sent_bytes,
321                        });
322                    }
323                } else {
324                    self.loss_time = Some(*time_sent + loss_delay);
325                    break;
326                }
327            }
328        }
329
330        LossDetectionResult {
331            lost_bytes,
332            lost_packets: newly_lost.len(),
333
334            pmtud_lost_bytes,
335            pmtud_lost_packets,
336        }
337    }
338
339    /// Remove packets that were already handled from the front of the queue,
340    /// but avoid removing packets from the middle of the queue to avoid
341    /// compaction
342    fn drain_acked_and_lost_packets(&mut self) {
343        while let Some(SentPacket {
344            status: SentStatus::Acked | SentStatus::Lost,
345            ..
346        }) = self.sent_packets.front()
347        {
348            self.sent_packets.pop_front();
349        }
350    }
351
352    fn least_unacked(&self) -> u64 {
353        for pkt in self.sent_packets.iter() {
354            if let SentPacket {
355                pkt_num,
356                status: SentStatus::Sent { .. },
357            } = pkt
358            {
359                return *pkt_num;
360            }
361        }
362
363        self.largest_acked_packet.unwrap_or(0) + 1
364    }
365
366    /// Returns the next lost frame, trying ACK-based lost frames first,
367    /// then PTO-based lost frames.
368    fn next_lost_frame(&mut self) -> Option<frame::Frame> {
369        self.lost_frames_ack
370            .pop_front()
371            .or_else(|| self.lost_frames_pto.pop_front())
372    }
373
374    /// Returns true if there are any lost frames (ACK or PTO).
375    fn has_lost_frames(&self) -> bool {
376        !self.lost_frames_ack.is_empty() || !self.lost_frames_pto.is_empty()
377    }
378
379    /// Returns the total count of lost frames (ACK + PTO).
380    #[cfg(test)]
381    fn lost_frames_count(&self) -> usize {
382        self.lost_frames_ack.len() + self.lost_frames_pto.len()
383    }
384
385    /// Clears all lost frames (both ACK and PTO).
386    fn clear_lost_frames(&mut self) {
387        self.lost_frames_ack.clear();
388        self.lost_frames_pto.clear();
389    }
390}
391
392struct LossThreshold {
393    pkt_thresh: Option<u64>,
394    time_thresh: f64,
395
396    // # Experiment: enable_relaxed_loss_threshold
397    //
398    // If `Some` this will disable pkt_thresh on the first loss and then double
399    // time_thresh on subsequent loss.
400    //
401    // The actual threshold is calcualted as `1.0 +
402    // INITIAL_TIME_THRESHOLD_OVERHEAD` and equivalent to the initial value
403    // of INITIAL_TIME_THRESHOLD.
404    time_thresh_overhead: Option<f64>,
405}
406
407impl LossThreshold {
408    fn new(recovery_config: &RecoveryConfig) -> Self {
409        let time_thresh_overhead =
410            if recovery_config.enable_relaxed_loss_threshold {
411                Some(INITIAL_TIME_THRESHOLD_OVERHEAD)
412            } else {
413                None
414            };
415        LossThreshold {
416            pkt_thresh: Some(INITIAL_PACKET_THRESHOLD),
417            time_thresh: INITIAL_TIME_THRESHOLD,
418            time_thresh_overhead,
419        }
420    }
421
422    fn pkt_thresh(&self) -> Option<u64> {
423        self.pkt_thresh
424    }
425
426    fn time_thresh(&self) -> f64 {
427        self.time_thresh
428    }
429
430    fn on_spurious_loss(&mut self, new_pkt_thresh: u64) {
431        match &mut self.time_thresh_overhead {
432            Some(time_thresh_overhead) => {
433                if self.pkt_thresh.is_some() {
434                    // Disable packet threshold on first spurious loss.
435                    self.pkt_thresh = None;
436                } else {
437                    // Double time threshold but cap it at `1.0`, which ends up
438                    // being 2x the RTT.
439                    *time_thresh_overhead *= TIME_THRESHOLD_OVERHEAD_MULTIPLIER;
440                    *time_thresh_overhead = time_thresh_overhead.min(1.0);
441
442                    self.time_thresh = 1.0 + *time_thresh_overhead;
443                }
444            },
445            None => {
446                let new_packet_threshold = self
447                    .pkt_thresh
448                    .expect("packet threshold should always be Some when `enable_relaxed_loss_threshold` is false")
449                    .max(new_pkt_thresh.min(MAX_PACKET_THRESHOLD));
450                self.pkt_thresh = Some(new_packet_threshold);
451
452                self.time_thresh = PACKET_REORDER_TIME_THRESHOLD;
453            },
454        }
455    }
456}
457
458pub struct GRecovery {
459    epochs: [RecoveryEpoch; packet::Epoch::count()],
460
461    loss_timer: LossDetectionTimer,
462
463    pto_count: u32,
464
465    rtt_stats: RttStats,
466
467    recovery_stats: RecoveryStats,
468
469    pub lost_count: usize,
470
471    pub lost_spurious_count: usize,
472
473    loss_thresh: LossThreshold,
474
475    bytes_in_flight: BytesInFlight,
476
477    pub bytes_lost: u64,
478
479    max_datagram_size: usize,
480    time_sent_set_to_now: bool,
481
482    #[cfg(feature = "qlog")]
483    qlog_metrics: QlogMetrics,
484
485    #[cfg(feature = "qlog")]
486    qlog_prev_cc_state: &'static str,
487
488    /// How many non-ack-eliciting packets have been sent.
489    outstanding_non_ack_eliciting: usize,
490
491    /// A resusable list of acks.
492    newly_acked: Vec<Acked>,
493
494    /// A [`Vec`] that can be reused for calls of
495    /// [`Self::detect_and_remove_lost_packets`] to avoid allocations
496    lost_reuse: Vec<Lost>,
497
498    pacer: Pacer,
499}
500
501impl GRecovery {
502    #[cfg(feature = "qlog")]
503    fn send_rate(&self) -> Bandwidth {
504        self.pacer.send_rate().unwrap_or(Bandwidth::zero())
505    }
506
507    #[cfg(feature = "qlog")]
508    fn ack_rate(&self) -> Bandwidth {
509        self.pacer.ack_rate().unwrap_or(Bandwidth::zero())
510    }
511
512    pub fn new(recovery_config: &RecoveryConfig) -> Option<Self> {
513        let cc = match recovery_config.cc_algorithm {
514            CongestionControlAlgorithm::Bbr2Gcongestion => BBRv2::new(
515                recovery_config.initial_congestion_window_packets,
516                MAX_WINDOW_PACKETS,
517                recovery_config.max_send_udp_payload_size,
518                recovery_config.initial_rtt,
519                recovery_config.custom_bbr_params.as_ref(),
520            ),
521            _ => return None,
522        };
523
524        Some(Self {
525            epochs: Default::default(),
526            rtt_stats: RttStats::new(
527                recovery_config.initial_rtt,
528                recovery_config.max_ack_delay,
529            ),
530            recovery_stats: RecoveryStats::default(),
531            loss_timer: Default::default(),
532            pto_count: 0,
533
534            lost_count: 0,
535            lost_spurious_count: 0,
536
537            loss_thresh: LossThreshold::new(recovery_config),
538            bytes_in_flight: Default::default(),
539            bytes_lost: 0,
540
541            max_datagram_size: recovery_config.max_send_udp_payload_size,
542            time_sent_set_to_now: cc.time_sent_set_to_now(),
543
544            #[cfg(feature = "qlog")]
545            qlog_metrics: QlogMetrics::default(),
546
547            #[cfg(feature = "qlog")]
548            qlog_prev_cc_state: "",
549
550            outstanding_non_ack_eliciting: 0,
551
552            pacer: Pacer::new(
553                recovery_config.pacing,
554                cc,
555                recovery_config
556                    .max_pacing_rate
557                    .map(Bandwidth::from_mbits_per_second),
558            ),
559
560            newly_acked: Vec::new(),
561            lost_reuse: Vec::new(),
562        })
563    }
564
565    fn detect_and_remove_lost_packets(
566        &mut self, epoch: packet::Epoch, now: Instant,
567    ) -> (usize, usize) {
568        let loss_delay =
569            self.rtt_stats.loss_delay(self.loss_thresh.time_thresh());
570        let lost = &mut self.lost_reuse;
571
572        let LossDetectionResult {
573            lost_bytes,
574            lost_packets,
575            pmtud_lost_bytes,
576            pmtud_lost_packets,
577        } = self.epochs[epoch].detect_and_remove_lost_packets(
578            loss_delay,
579            self.loss_thresh.pkt_thresh(),
580            now,
581            lost,
582        );
583
584        self.bytes_in_flight
585            .saturating_subtract(lost_bytes + pmtud_lost_bytes, now);
586
587        for pkt in pmtud_lost_packets {
588            self.pacer.on_packet_neutered(pkt);
589        }
590
591        (lost_bytes, lost_packets)
592    }
593
594    fn loss_time_and_space(&self) -> (Option<Instant>, packet::Epoch) {
595        let mut epoch = packet::Epoch::Initial;
596        let mut time = self.epochs[epoch].loss_time;
597
598        // Iterate over all packet number spaces starting from Handshake.
599        for e in [packet::Epoch::Handshake, packet::Epoch::Application] {
600            let new_time = self.epochs[e].loss_time;
601            if time.is_none() || new_time < time {
602                time = new_time;
603                epoch = e;
604            }
605        }
606
607        (time, epoch)
608    }
609
610    fn pto_time_and_space(
611        &self, handshake_status: HandshakeStatus, now: Instant,
612    ) -> (Option<Instant>, packet::Epoch) {
613        let mut duration = self.pto() * 2_u32.saturating_pow(self.pto_count);
614
615        // Arm PTO from now when there are no inflight packets.
616        if self.bytes_in_flight.is_zero() {
617            if handshake_status.has_handshake_keys {
618                return (Some(now + duration), packet::Epoch::Handshake);
619            } else {
620                return (Some(now + duration), packet::Epoch::Initial);
621            }
622        }
623
624        let mut pto_timeout = None;
625        let mut pto_space = packet::Epoch::Initial;
626
627        // Iterate over all packet number spaces.
628        for &e in packet::Epoch::epochs(
629            packet::Epoch::Initial..=packet::Epoch::Application,
630        ) {
631            if self.epochs[e].pkts_in_flight == 0 {
632                continue;
633            }
634
635            if e == packet::Epoch::Application {
636                // Skip Application Data until handshake completes.
637                if !handshake_status.completed {
638                    return (pto_timeout, pto_space);
639                }
640
641                // Include max_ack_delay and backoff for Application Data.
642                duration += self.rtt_stats.max_ack_delay *
643                    2_u32.saturating_pow(self.pto_count);
644            }
645
646            let new_time = self.epochs[e]
647                .time_of_last_ack_eliciting_packet
648                .map(|t| t + duration);
649
650            if pto_timeout.is_none() || new_time < pto_timeout {
651                pto_timeout = new_time;
652                pto_space = e;
653            }
654        }
655
656        (pto_timeout, pto_space)
657    }
658
659    fn set_loss_detection_timer(
660        &mut self, handshake_status: HandshakeStatus, now: Instant,
661    ) {
662        if let (Some(earliest_loss_time), _) = self.loss_time_and_space() {
663            // Time threshold loss detection.
664            self.loss_timer.update(earliest_loss_time);
665            return;
666        }
667
668        if self.bytes_in_flight.is_zero() &&
669            handshake_status.peer_verified_address
670        {
671            self.loss_timer.clear();
672            return;
673        }
674
675        // PTO timer.
676        if let (Some(timeout), _) = self.pto_time_and_space(handshake_status, now)
677        {
678            self.loss_timer.update(timeout);
679        } else {
680            self.loss_timer.clear();
681        }
682    }
683}
684
685impl RecoveryOps for GRecovery {
686    fn lost_count(&self) -> usize {
687        self.lost_count
688    }
689
690    fn bytes_lost(&self) -> u64 {
691        self.bytes_lost
692    }
693
694    fn should_elicit_ack(&self, epoch: packet::Epoch) -> bool {
695        self.epochs[epoch].loss_probes > 0 ||
696            self.outstanding_non_ack_eliciting >=
697                MAX_OUTSTANDING_NON_ACK_ELICITING
698    }
699
700    fn next_acked_frame(&mut self, epoch: packet::Epoch) -> Option<frame::Frame> {
701        self.epochs[epoch].acked_frames.pop_front()
702    }
703
704    fn next_lost_frame(&mut self, epoch: packet::Epoch) -> Option<frame::Frame> {
705        self.epochs[epoch].next_lost_frame()
706    }
707
708    fn get_largest_acked_on_epoch(&self, epoch: packet::Epoch) -> Option<u64> {
709        self.epochs[epoch].largest_acked_packet
710    }
711
712    fn has_lost_frames(&self, epoch: packet::Epoch) -> bool {
713        self.epochs[epoch].has_lost_frames()
714    }
715
716    fn loss_probes(&self, epoch: packet::Epoch) -> usize {
717        self.epochs[epoch].loss_probes
718    }
719
720    #[cfg(test)]
721    fn inc_loss_probes(&mut self, epoch: packet::Epoch) {
722        self.epochs[epoch].loss_probes += 1;
723    }
724
725    #[cfg(test)]
726    fn lost_frames_count(&self, epoch: packet::Epoch) -> usize {
727        self.epochs[epoch].lost_frames_count()
728    }
729
730    fn ping_sent(&mut self, epoch: packet::Epoch) {
731        self.epochs[epoch].loss_probes =
732            self.epochs[epoch].loss_probes.saturating_sub(1);
733    }
734
735    fn on_packet_sent(
736        &mut self, pkt: Sent, epoch: packet::Epoch,
737        handshake_status: HandshakeStatus, now: Instant, trace_id: &str,
738    ) {
739        let time_sent = if self.time_sent_set_to_now {
740            now
741        } else {
742            self.get_next_release_time().time(now).unwrap_or(now)
743        };
744
745        let epoch = &mut self.epochs[epoch];
746
747        let ack_eliciting = pkt.ack_eliciting;
748        let in_flight = pkt.in_flight;
749        let is_pmtud_probe = pkt.is_pmtud_probe;
750        let pkt_num = pkt.pkt_num;
751        let sent_bytes = pkt.size;
752
753        if let Some(SentPacket { pkt_num, .. }) = epoch.sent_packets.back() {
754            assert!(*pkt_num < pkt.pkt_num, "Packet numbers must increase");
755        }
756
757        let status = SentStatus::Sent {
758            time_sent,
759            ack_eliciting,
760            in_flight,
761            is_pmtud_probe,
762            has_data: pkt.has_data,
763            sent_bytes,
764            frames: pkt.frames,
765        };
766
767        #[cfg(test)]
768        {
769            epoch.test_largest_sent_pkt_num_on_path = epoch
770                .test_largest_sent_pkt_num_on_path
771                .max(Some(pkt.pkt_num));
772        }
773
774        epoch.sent_packets.push_back(SentPacket { pkt_num, status });
775
776        if ack_eliciting {
777            epoch.time_of_last_ack_eliciting_packet = Some(time_sent);
778            self.outstanding_non_ack_eliciting = 0;
779        } else {
780            self.outstanding_non_ack_eliciting += 1;
781        }
782
783        if in_flight {
784            self.pacer.on_packet_sent(
785                time_sent,
786                self.bytes_in_flight.get(),
787                pkt_num,
788                sent_bytes,
789                pkt.has_data,
790                &self.rtt_stats,
791            );
792
793            self.bytes_in_flight.add(sent_bytes, now);
794            epoch.pkts_in_flight += 1;
795            self.set_loss_detection_timer(handshake_status, time_sent);
796        }
797
798        trace!("{trace_id} {self:?}");
799    }
800
801    fn get_packet_send_time(&self, now: Instant) -> Instant {
802        self.pacer.get_next_release_time().time(now).unwrap_or(now)
803    }
804
805    // `peer_sent_ack_ranges` should not be used without validation.
806    fn on_ack_received(
807        &mut self, peer_sent_ack_ranges: &RangeSet, ack_delay: u64,
808        epoch: packet::Epoch, handshake_status: HandshakeStatus, now: Instant,
809        skip_pn: Option<u64>, trace_id: &str,
810    ) -> Result<OnAckReceivedOutcome> {
811        let prior_in_flight = self.bytes_in_flight.get();
812
813        let AckedDetectionResult {
814            acked_bytes,
815            spurious_losses,
816            spurious_pkt_thresh,
817            has_ack_eliciting,
818        } = self.epochs[epoch].detect_and_remove_acked_packets(
819            peer_sent_ack_ranges,
820            &mut self.newly_acked,
821            skip_pn,
822            trace_id,
823        )?;
824
825        self.lost_spurious_count += spurious_losses;
826        if let Some(thresh) = spurious_pkt_thresh {
827            self.loss_thresh.on_spurious_loss(thresh);
828        }
829
830        if self.newly_acked.is_empty() {
831            return Ok(OnAckReceivedOutcome {
832                acked_bytes,
833                spurious_losses,
834                ..Default::default()
835            });
836        }
837
838        self.bytes_in_flight.saturating_subtract(acked_bytes, now);
839
840        let largest_newly_acked = self.newly_acked.last().unwrap();
841
842        // Update `largest_acked_packet` based on the validated `newly_acked`
843        // value.
844        let largest_acked_pkt_num = self.epochs[epoch]
845            .largest_acked_packet
846            .unwrap_or(0)
847            .max(largest_newly_acked.pkt_num);
848        self.epochs[epoch].largest_acked_packet = Some(largest_acked_pkt_num);
849
850        // Check if largest packet is newly acked.
851        let update_rtt = largest_newly_acked.pkt_num == largest_acked_pkt_num &&
852            has_ack_eliciting;
853        if update_rtt {
854            let latest_rtt = now - largest_newly_acked.time_sent;
855            self.rtt_stats.update_rtt(
856                latest_rtt,
857                Duration::from_micros(ack_delay),
858                now,
859                handshake_status.completed,
860            );
861        }
862
863        let (lost_bytes, lost_packets) =
864            self.detect_and_remove_lost_packets(epoch, now);
865
866        self.pacer.on_congestion_event(
867            update_rtt,
868            prior_in_flight,
869            self.bytes_in_flight.get(),
870            now,
871            &self.newly_acked,
872            &self.lost_reuse,
873            self.epochs[epoch].least_unacked(),
874            &self.rtt_stats,
875            &mut self.recovery_stats,
876        );
877
878        self.pto_count = 0;
879        self.lost_count += lost_packets;
880
881        self.set_loss_detection_timer(handshake_status, now);
882
883        trace!("{trace_id} {self:?}");
884
885        Ok(OnAckReceivedOutcome {
886            lost_packets,
887            lost_bytes,
888            acked_bytes,
889            spurious_losses,
890        })
891    }
892
893    fn on_loss_detection_timeout(
894        &mut self, handshake_status: HandshakeStatus, now: Instant,
895        trace_id: &str,
896    ) -> OnLossDetectionTimeoutOutcome {
897        let (earliest_loss_time, epoch) = self.loss_time_and_space();
898
899        if earliest_loss_time.is_some() {
900            let prior_in_flight = self.bytes_in_flight.get();
901
902            let (lost_bytes, lost_packets) =
903                self.detect_and_remove_lost_packets(epoch, now);
904
905            self.pacer.on_congestion_event(
906                false,
907                prior_in_flight,
908                self.bytes_in_flight.get(),
909                now,
910                &[],
911                &self.lost_reuse,
912                self.epochs[epoch].least_unacked(),
913                &self.rtt_stats,
914                &mut self.recovery_stats,
915            );
916
917            self.lost_count += lost_packets;
918
919            self.set_loss_detection_timer(handshake_status, now);
920
921            trace!("{trace_id} {self:?}");
922            return OnLossDetectionTimeoutOutcome {
923                lost_packets,
924                lost_bytes,
925            };
926        }
927
928        let epoch = if self.bytes_in_flight.get() > 0 {
929            // Send new data if available, else retransmit old data. If neither
930            // is available, send a single PING frame.
931            let (_, e) = self.pto_time_and_space(handshake_status, now);
932
933            e
934        } else {
935            // Client sends an anti-deadlock packet: Initial is padded to earn
936            // more anti-amplification credit, a Handshake packet proves address
937            // ownership.
938            if handshake_status.has_handshake_keys {
939                packet::Epoch::Handshake
940            } else {
941                packet::Epoch::Initial
942            }
943        };
944
945        self.pto_count += 1;
946
947        let epoch = &mut self.epochs[epoch];
948
949        epoch.loss_probes = MAX_PTO_PROBES_COUNT.min(self.pto_count as usize);
950
951        let sent_packets_iter_limit = if !epoch.lost_frames_pto.is_empty() {
952            // Skip the search for frames to add to PTO probes if frames
953            // added in a prior PTO haven't been processed yet.
954            0
955        } else {
956            usize::MAX
957        };
958
959        // Skip packets that have already been acked or lost, and packets
960        // that don't contain either CRYPTO or STREAM frames and only return as
961        // many packets as the number of probe packets that will be sent.
962        let unacked_frames = epoch
963            .sent_packets
964            .iter()
965            .take(sent_packets_iter_limit)
966            .filter_map(|p| {
967                if let SentStatus::Sent {
968                    has_data: true,
969                    frames,
970                    ..
971                } = &p.status
972                {
973                    Some(frames)
974                } else {
975                    None
976                }
977            })
978            .take(epoch.loss_probes)
979            .flatten()
980            .filter(|f| !matches!(f, frame::Frame::DatagramHeader { .. }));
981
982        // Retransmit the frames from the oldest sent packets on PTO. However
983        // the packets are not actually declared lost (so there is no effect to
984        // congestion control), we just reschedule the data they carried.
985        //
986        // This will also trigger sending an ACK and retransmitting frames like
987        // HANDSHAKE_DONE and MAX_DATA / MAX_STREAM_DATA as well, in addition
988        // to CRYPTO and STREAM, if the original packet carried them.
989        epoch.lost_frames_pto.extend(unacked_frames.cloned());
990
991        self.pacer
992            .on_retransmission_timeout(epoch.has_lost_frames());
993
994        self.set_loss_detection_timer(handshake_status, now);
995
996        trace!("{trace_id} {self:?}");
997        OnLossDetectionTimeoutOutcome {
998            lost_packets: 0,
999            lost_bytes: 0,
1000        }
1001    }
1002
1003    fn on_pkt_num_space_discarded(
1004        &mut self, epoch: packet::Epoch, handshake_status: HandshakeStatus,
1005        now: Instant,
1006    ) {
1007        let epoch = &mut self.epochs[epoch];
1008        self.bytes_in_flight
1009            .saturating_subtract(epoch.discard(&mut self.pacer), now);
1010
1011        // Discarding a packet number space is forward progress, so the PTO
1012        // backoff starts over (RFC 9002, Appendix A.11).
1013        self.pto_count = 0;
1014
1015        self.set_loss_detection_timer(handshake_status, now);
1016    }
1017
1018    fn on_path_change(
1019        &mut self, epoch: packet::Epoch, now: Instant, _trace_id: &str,
1020    ) -> (usize, usize) {
1021        let (lost_bytes, lost_packets) =
1022            self.detect_and_remove_lost_packets(epoch, now);
1023
1024        (lost_packets, lost_bytes)
1025    }
1026
1027    fn loss_detection_timer(&self) -> Option<Instant> {
1028        self.loss_timer.time
1029    }
1030
1031    fn cwnd(&self) -> usize {
1032        self.pacer.get_congestion_window()
1033    }
1034
1035    fn cwnd_available(&self) -> usize {
1036        self.cwnd().saturating_sub(self.bytes_in_flight.get())
1037    }
1038
1039    fn rtt(&self) -> Duration {
1040        self.rtt_stats.rtt()
1041    }
1042
1043    fn min_rtt(&self) -> Option<Duration> {
1044        self.rtt_stats.min_rtt()
1045    }
1046
1047    fn max_rtt(&self) -> Option<Duration> {
1048        self.rtt_stats.max_rtt()
1049    }
1050
1051    fn rttvar(&self) -> Duration {
1052        self.rtt_stats.rttvar()
1053    }
1054
1055    fn pto(&self) -> Duration {
1056        let r = &self.rtt_stats;
1057        r.rtt() + (r.rttvar() * 4).max(GRANULARITY)
1058    }
1059
1060    /// The most recent data delivery rate estimate.
1061    fn delivery_rate(&self) -> Bandwidth {
1062        self.pacer.bandwidth_estimate(&self.rtt_stats)
1063    }
1064
1065    fn max_bandwidth(&self) -> Option<Bandwidth> {
1066        Some(self.pacer.max_bandwidth())
1067    }
1068
1069    fn rtt_persistent_jump_count(&self) -> u64 {
1070        self.pacer.rtt_persistent_jump_count()
1071    }
1072
1073    /// Statistics from when a CCA first exited the startup phase.
1074    fn startup_exit(&self) -> Option<StartupExit> {
1075        self.recovery_stats.startup_exit
1076    }
1077
1078    fn max_datagram_size(&self) -> usize {
1079        self.max_datagram_size
1080    }
1081
1082    fn pmtud_update_max_datagram_size(&mut self, new_max_datagram_size: usize) {
1083        self.max_datagram_size = new_max_datagram_size;
1084        self.pacer.update_mss(self.max_datagram_size);
1085    }
1086
1087    fn update_max_datagram_size(&mut self, new_max_datagram_size: usize) {
1088        self.pmtud_update_max_datagram_size(
1089            self.max_datagram_size.min(new_max_datagram_size),
1090        )
1091    }
1092
1093    // FIXME only used by gcongestion
1094    fn on_app_limited(&mut self) {
1095        self.pacer.on_app_limited(self.bytes_in_flight.get())
1096    }
1097
1098    fn sent_packets_len(&self, epoch: packet::Epoch) -> usize {
1099        self.epochs[epoch].sent_packets.len()
1100    }
1101
1102    #[cfg(test)]
1103    fn in_flight_count(&self, epoch: packet::Epoch) -> usize {
1104        self.epochs[epoch].pkts_in_flight
1105    }
1106
1107    fn bytes_in_flight(&self) -> usize {
1108        self.bytes_in_flight.get()
1109    }
1110
1111    fn bytes_in_flight_duration(&self) -> Duration {
1112        self.bytes_in_flight.get_duration()
1113    }
1114
1115    #[cfg(test)]
1116    fn pacing_rate(&self) -> u64 {
1117        self.pacer
1118            .pacing_rate(self.bytes_in_flight.get(), &self.rtt_stats)
1119            .to_bytes_per_period(Duration::from_secs(1))
1120    }
1121
1122    #[cfg(test)]
1123    fn pto_count(&self) -> u32 {
1124        self.pto_count
1125    }
1126
1127    #[cfg(test)]
1128    fn pkt_thresh(&self) -> Option<u64> {
1129        self.loss_thresh.pkt_thresh()
1130    }
1131
1132    #[cfg(test)]
1133    fn time_thresh(&self) -> f64 {
1134        self.loss_thresh.time_thresh()
1135    }
1136
1137    #[cfg(test)]
1138    fn lost_spurious_count(&self) -> usize {
1139        self.lost_spurious_count
1140    }
1141
1142    #[cfg(test)]
1143    fn detect_lost_packets_for_test(
1144        &mut self, epoch: packet::Epoch, now: Instant,
1145    ) -> (usize, usize) {
1146        let ret = self.detect_and_remove_lost_packets(epoch, now);
1147        self.epochs[epoch].drain_acked_and_lost_packets();
1148        ret
1149    }
1150
1151    #[cfg(test)]
1152    fn largest_sent_pkt_num_on_path(&self, epoch: packet::Epoch) -> Option<u64> {
1153        self.epochs[epoch].test_largest_sent_pkt_num_on_path
1154    }
1155
1156    #[cfg(any(test, feature = "qlog"))]
1157    fn app_limited(&self) -> bool {
1158        self.pacer.is_app_limited(self.bytes_in_flight.get())
1159    }
1160
1161    // FIXME only used by congestion
1162    fn update_app_limited(&mut self, _v: bool) {
1163        // TODO
1164    }
1165
1166    // FIXME only used by congestion
1167    fn delivery_rate_update_app_limited(&mut self, _v: bool) {
1168        // TODO
1169    }
1170
1171    fn update_max_ack_delay(&mut self, max_ack_delay: Duration) {
1172        self.rtt_stats.max_ack_delay = max_ack_delay;
1173    }
1174
1175    fn get_next_release_time(&self) -> ReleaseDecision {
1176        self.pacer.get_next_release_time()
1177    }
1178
1179    fn gcongestion_enabled(&self) -> bool {
1180        true
1181    }
1182
1183    #[cfg(feature = "qlog")]
1184    fn state_str(&self, _now: Instant) -> &'static str {
1185        self.pacer.state_str()
1186    }
1187
1188    #[cfg(feature = "qlog")]
1189    fn get_updated_qlog_event_data(&mut self) -> Option<EventData> {
1190        let qlog_metrics = QlogMetrics {
1191            min_rtt: *self.rtt_stats.min_rtt,
1192            smoothed_rtt: self.rtt(),
1193            latest_rtt: self.rtt_stats.latest_rtt(),
1194            rttvar: self.rtt_stats.rttvar(),
1195            cwnd: self.cwnd() as u64,
1196            bytes_in_flight: self.bytes_in_flight.get() as u64,
1197            ssthresh: self.pacer.ssthresh(),
1198
1199            pacing_rate: Some(
1200                self.pacer
1201                    .pacing_rate(self.bytes_in_flight.get(), &self.rtt_stats)
1202                    .to_bytes_per_second(),
1203            ),
1204            delivery_rate: Some(self.delivery_rate().to_bytes_per_second()),
1205            send_rate: Some(self.send_rate().to_bytes_per_second()),
1206            ack_rate: Some(self.ack_rate().to_bytes_per_second()),
1207            lost_packets: Some(self.lost_count as u64),
1208            lost_bytes: Some(self.bytes_lost),
1209            pto_count: Some(self.pto_count),
1210            app_limited: Some(self.app_limited()),
1211        };
1212
1213        self.qlog_metrics.maybe_update(qlog_metrics)
1214    }
1215
1216    #[cfg(feature = "qlog")]
1217    fn get_updated_qlog_cc_state(
1218        &mut self, now: Instant,
1219    ) -> Option<&'static str> {
1220        let cc_state = self.state_str(now);
1221        if cc_state != self.qlog_prev_cc_state {
1222            self.qlog_prev_cc_state = cc_state;
1223            Some(cc_state)
1224        } else {
1225            None
1226        }
1227    }
1228
1229    fn send_quantum(&self) -> usize {
1230        let pacing_rate = self
1231            .pacer
1232            .pacing_rate(self.bytes_in_flight.get(), &self.rtt_stats);
1233
1234        let floor = if pacing_rate < Bandwidth::from_kbits_per_second(1200) {
1235            self.max_datagram_size
1236        } else {
1237            2 * self.max_datagram_size
1238        };
1239
1240        pacing_rate
1241            .to_bytes_per_period(ReleaseDecision::EQUAL_THRESHOLD)
1242            .min(64 * 1024)
1243            .max(floor as u64) as usize
1244    }
1245}
1246
1247impl std::fmt::Debug for GRecovery {
1248    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
1249        write!(f, "timer={:?} ", self.loss_detection_timer())?;
1250        write!(f, "rtt_stats={:?} ", self.rtt_stats)?;
1251        write!(f, "bytes_in_flight={} ", self.bytes_in_flight.get())?;
1252        write!(f, "{:?} ", self.pacer)?;
1253        Ok(())
1254    }
1255}
1256
1257#[cfg(test)]
1258mod tests {
1259    use super::*;
1260    use crate::Config;
1261
1262    #[test]
1263    fn loss_threshold() {
1264        let config = Config::new(crate::PROTOCOL_VERSION).unwrap();
1265        let recovery_config = RecoveryConfig::from_config(&config);
1266        assert!(!recovery_config.enable_relaxed_loss_threshold);
1267
1268        let mut loss_thresh = LossThreshold::new(&recovery_config);
1269        assert_eq!(loss_thresh.time_thresh_overhead, None);
1270        assert_eq!(loss_thresh.pkt_thresh().unwrap(), INITIAL_PACKET_THRESHOLD);
1271        assert_eq!(loss_thresh.time_thresh(), INITIAL_TIME_THRESHOLD);
1272
1273        // First spurious loss.
1274        loss_thresh.on_spurious_loss(INITIAL_PACKET_THRESHOLD);
1275        assert_eq!(loss_thresh.pkt_thresh().unwrap(), INITIAL_PACKET_THRESHOLD);
1276        assert_eq!(loss_thresh.time_thresh(), PACKET_REORDER_TIME_THRESHOLD);
1277
1278        // Packet gaps < INITIAL_PACKET_THRESHOLD will NOT change packet
1279        // threshold.
1280        for packet_gap in 0..INITIAL_PACKET_THRESHOLD {
1281            loss_thresh.on_spurious_loss(packet_gap);
1282
1283            // Packet threshold only increases once the packet gap increases.
1284            assert_eq!(
1285                loss_thresh.pkt_thresh().unwrap(),
1286                INITIAL_PACKET_THRESHOLD
1287            );
1288            assert_eq!(loss_thresh.time_thresh(), PACKET_REORDER_TIME_THRESHOLD);
1289        }
1290
1291        // Subsequent spurious loss with packet_gaps > INITIAL_PACKET_THRESHOLD.
1292        // Test values much larger than MAX_PACKET_THRESHOLD, i.e.
1293        // `MAX_PACKET_THRESHOLD * 2`
1294        for packet_gap in INITIAL_PACKET_THRESHOLD + 1..MAX_PACKET_THRESHOLD * 2 {
1295            loss_thresh.on_spurious_loss(packet_gap);
1296
1297            // Packet threshold is equal to packet gap beyond
1298            // INITIAL_PACKET_THRESHOLD, but capped
1299            // at MAX_PACKET_THRESHOLD.
1300            let new_packet_threshold = if packet_gap < MAX_PACKET_THRESHOLD {
1301                packet_gap
1302            } else {
1303                MAX_PACKET_THRESHOLD
1304            };
1305            assert_eq!(loss_thresh.pkt_thresh().unwrap(), new_packet_threshold);
1306            assert_eq!(loss_thresh.time_thresh(), PACKET_REORDER_TIME_THRESHOLD);
1307        }
1308        // Packet threshold is capped at MAX_PACKET_THRESHOLD
1309        assert_eq!(loss_thresh.pkt_thresh().unwrap(), MAX_PACKET_THRESHOLD);
1310        assert_eq!(loss_thresh.time_thresh(), PACKET_REORDER_TIME_THRESHOLD);
1311
1312        // Packet threshold is monotonically increasing
1313        loss_thresh.on_spurious_loss(INITIAL_PACKET_THRESHOLD);
1314        assert_eq!(loss_thresh.pkt_thresh().unwrap(), MAX_PACKET_THRESHOLD);
1315        assert_eq!(loss_thresh.time_thresh(), PACKET_REORDER_TIME_THRESHOLD);
1316    }
1317
1318    #[test]
1319    fn relaxed_loss_threshold() {
1320        // The max time threshold when operating in relaxed loss mode.
1321        const MAX_TIME_THRESHOLD: f64 = 2.0;
1322
1323        let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
1324        config.set_enable_relaxed_loss_threshold(true);
1325        let recovery_config = RecoveryConfig::from_config(&config);
1326        assert!(recovery_config.enable_relaxed_loss_threshold);
1327
1328        let mut loss_thresh = LossThreshold::new(&recovery_config);
1329        assert_eq!(
1330            loss_thresh.time_thresh_overhead,
1331            Some(INITIAL_TIME_THRESHOLD_OVERHEAD)
1332        );
1333        assert_eq!(loss_thresh.pkt_thresh().unwrap(), INITIAL_PACKET_THRESHOLD);
1334        assert_eq!(loss_thresh.time_thresh(), INITIAL_TIME_THRESHOLD);
1335
1336        // First spurious loss.
1337        loss_thresh.on_spurious_loss(INITIAL_PACKET_THRESHOLD);
1338        assert_eq!(loss_thresh.pkt_thresh(), None);
1339        assert_eq!(loss_thresh.time_thresh(), INITIAL_TIME_THRESHOLD);
1340
1341        // Subsequent spurious loss.
1342        for subsequent_loss_count in 1..100 {
1343            // Double the overhead until it caps at `2.0`.
1344            //
1345            // The initial time-threshold overhead reaches `1.0` after three
1346            // rounds of doubling.
1347            let new_time_threshold = if subsequent_loss_count <= 3 {
1348                1.0 + INITIAL_TIME_THRESHOLD_OVERHEAD *
1349                    2_f64.powi(subsequent_loss_count as i32)
1350            } else {
1351                2.0
1352            };
1353
1354            loss_thresh.on_spurious_loss(subsequent_loss_count);
1355            assert_eq!(loss_thresh.pkt_thresh(), None);
1356            assert_eq!(loss_thresh.time_thresh(), new_time_threshold);
1357        }
1358        // Time threshold is capped at 2.0.
1359        assert_eq!(loss_thresh.pkt_thresh(), None);
1360        assert_eq!(loss_thresh.time_thresh(), MAX_TIME_THRESHOLD);
1361    }
1362
1363    #[test]
1364    fn test_high_pto_count_no_panic() {
1365        let mut config = Config::new(crate::PROTOCOL_VERSION).unwrap();
1366        config.set_cc_algorithm(CongestionControlAlgorithm::Bbr2Gcongestion);
1367        let recovery_config = RecoveryConfig::from_config(&config);
1368        let mut r = GRecovery::new(&recovery_config).unwrap();
1369
1370        r.pto_count = 99999;
1371
1372        let handshake_status = HandshakeStatus {
1373            completed: true,
1374            has_handshake_keys: true,
1375            peer_verified_address: true,
1376        };
1377        let now = Instant::now();
1378
1379        let _ = r.pto_time_and_space(handshake_status, now);
1380    }
1381}