forked from mozilla/neqo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclassic_cc.rs
More file actions
2250 lines (2026 loc) · 81.4 KB
/
classic_cc.rs
File metadata and controls
2250 lines (2026 loc) · 81.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// Congestion control
use std::{
cmp::{max, min},
fmt::{Debug, Display},
time::{Duration, Instant},
};
use neqo_common::{const_max, const_min, qdebug, qinfo, qlog::Qlog, qtrace};
use rustc_hash::FxHashMap as HashMap;
use super::CongestionController;
use crate::{
Pmtud,
cc::CongestionTrigger::{self, Ecn, Loss},
packet, qlog,
recovery::sent,
rtt::RttEstimate,
sender::PACING_BURST_SIZE,
stats::{CongestionControlStats, SlowStartExitReason},
};
pub const CWND_INITIAL_PKTS: usize = 10;
pub const PERSISTENT_CONG_THRESH: u32 = 3;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Phase {
/// In either slow start or congestion avoidance, not recovery.
SlowStart,
/// In congestion avoidance.
CongestionAvoidance,
/// In a recovery period, but no packets have been sent yet. This is a
/// transient phase because we want to exempt the first packet sent after
/// entering recovery from the congestion window.
RecoveryStart,
/// In a recovery period, with the first packet sent at this time.
Recovery,
/// Start of persistent congestion, which is transient, like `RecoveryStart`.
PersistentCongestion,
}
impl Phase {
pub const fn in_recovery(self) -> bool {
matches!(self, Self::RecoveryStart | Self::Recovery)
}
pub fn in_slow_start(self) -> bool {
self == Self::SlowStart
}
/// These states are transient, we tell qlog on entry, but not on exit.
pub const fn transient(self) -> bool {
matches!(self, Self::RecoveryStart | Self::PersistentCongestion)
}
/// Update a transient phase to the actual phase.
pub fn update(&mut self) {
*self = match self {
Self::PersistentCongestion => Self::SlowStart,
Self::RecoveryStart => Self::Recovery,
_ => unreachable!(),
};
}
pub const fn to_qlog(self) -> &'static str {
match self {
Self::SlowStart | Self::PersistentCongestion => "slow_start",
Self::CongestionAvoidance => "congestion_avoidance",
Self::Recovery | Self::RecoveryStart => "recovery",
}
}
}
pub trait WindowAdjustment: Display + Debug {
/// This is called when an ack is received.
/// The function calculates the amount of acked bytes congestion controller needs
/// to collect before increasing its cwnd by `MAX_DATAGRAM_SIZE`.
fn bytes_for_cwnd_increase(
&mut self,
curr_cwnd: usize,
new_acked_bytes: usize,
min_rtt: Duration,
max_datagram_size: usize,
now: Instant,
) -> usize;
/// This function is called when a congestion event has been detected and it
/// returns new (decreased) values of `curr_cwnd` and `acked_bytes`.
/// This value can be very small; the calling code is responsible for ensuring that the
/// congestion window doesn't drop below the minimum of `CWND_MIN`.
fn reduce_cwnd(
&mut self,
curr_cwnd: usize,
acked_bytes: usize,
max_datagram_size: usize,
congestion_trigger: CongestionTrigger,
cc_stats: &mut CongestionControlStats,
) -> (usize, usize);
/// Cubic needs this signal to reset its epoch.
fn on_app_limited(&mut self);
/// Store the current congestion controller state, to be recovered in the case of a spurious
/// congestion event.
fn save_undo_state(&mut self);
/// Restore the previously stored congestion controller state, to recover from a spurious
/// congestion event.
fn restore_undo_state(&mut self, cc_stats: &mut CongestionControlStats);
}
/// Trait for slow start exit algorithms.
///
/// Implementations define when and if to exit from slow start, how the slow start threshold
/// (`ssthresh`) is set on exit and they can influence how fast the exponential congestion window
/// growth rate during slow start is.
pub trait SlowStart: Display + Debug {
/// Enables a trait implementor to ingest info about sent packets.
fn on_packet_sent(&mut self, _sent_pn: packet::Number, _sent_bytes: usize) {}
/// This is needed by SEARCH to keep its cumulative byte counters in sync during app-limited
/// periods, when [`SlowStart::on_packets_acked`] is not called.
fn record_acked_bytes(&mut self, _new_acked_bytes: usize) {}
/// Handle packets being acknowledged during slow start. Returns the congestion window in bytes
/// that slow start should be exited with. If slow start isn't exited returns `None`.
fn on_packets_acked(
&mut self,
rtt_est: &RttEstimate,
largest_acked: packet::Number,
curr_cwnd: usize,
cc_stats: &mut CongestionControlStats,
now: Instant,
) -> Option<usize>;
/// Calculates the congestion window increase in bytes during slow start. The default
/// implementation returns `new_acked`, i.e. classic exponential slow start growth.
fn calc_cwnd_increase(&self, new_acked: usize, _max_datagram_size: usize) -> usize {
new_acked
}
/// Resets slow start state. Is used after persistent congestion so slow start algorithms
/// perform cleanly in non-initial slow starts. Can also be used by the implementing algorithm
/// for internal state reset when needed.
fn reset(&mut self) {}
}
#[derive(Debug)]
struct MaybeLostPacket {
time_sent: Instant,
}
#[derive(Debug, Clone)]
struct State {
phase: Phase,
congestion_window: usize,
acked_bytes: usize,
ssthresh: usize,
/// Packet number of the first packet that was sent after a congestion event. When this one is
/// acked we will exit [`Phase::Recovery`] and enter [`Phase::CongestionAvoidance`].
recovery_start: Option<packet::Number>,
}
impl Display for State {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"State [phase: {:?}, cwnd: {}, ssthresh: {}, recovery_start: {:?}]",
self.phase, self.congestion_window, self.ssthresh, self.recovery_start
)
}
}
impl State {
pub const fn new(mtu: usize) -> Self {
Self {
phase: Phase::SlowStart,
congestion_window: cwnd_initial(mtu),
acked_bytes: 0,
ssthresh: usize::MAX,
recovery_start: None,
}
}
}
#[derive(Debug)]
pub struct ClassicCongestionController<S, T> {
slow_start: S,
congestion_control: T,
bytes_in_flight: usize,
/// Packets that have supposedly been lost. These are used for spurious congestion event
/// detection. Gets drained when the same packets are later acked and regularly purged from too
/// old packets in [`Self::cleanup_maybe_lost_packets`]. Needs a tuple of `(packet::Number,
/// packet::Type)` to identify packets across packet number spaces.
maybe_lost_packets: HashMap<(packet::Number, packet::Type), MaybeLostPacket>,
/// `first_app_limited` indicates the packet number after which the application might be
/// underutilizing the congestion window. When underutilizing the congestion window due to not
/// sending out enough data, we SHOULD NOT increase the congestion window.[1] Packets sent
/// before this point are deemed to fully utilize the congestion window and count towards
/// increasing the congestion window.
///
/// [1]: https://datatracker.ietf.org/doc/html/rfc9002#section-7.8
first_app_limited: packet::Number,
pmtud: Pmtud,
qlog: Qlog,
/// Current congestion controller parameters.
current: State,
/// Congestion controller parameters that were stored on a congestion event to restore prior
/// state in case the congestion event turns out to be spurious.
///
/// For reference:
/// - [`State::acked_bytes`] is stored because that is where we accumulate our window increase
/// credit and it is also reduced on a congestion event.
/// - [`Self::bytes_in_flight`] is not stored because if it was to be restored it might get
/// out-of-sync with the actual number of bytes-in-flight on the path.
stored: Option<State>,
/// Whether to recover from spurious congestion events by restoring prior state.
spurious_recovery: bool,
}
impl<S: Display, T: Display> Display for ClassicCongestionController<S, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}/{} CongCtrl [bif: {}, {}]",
self.slow_start, self.congestion_control, self.bytes_in_flight, self.current
)
}
}
impl<S, T> ClassicCongestionController<S, T> {
pub const fn max_datagram_size(&self) -> usize {
self.pmtud.plpmtu()
}
#[cfg(test)]
pub const fn cwnd_initial(&self) -> usize {
cwnd_initial(self.pmtud.plpmtu())
}
}
impl<S, T> CongestionController for ClassicCongestionController<S, T>
where
S: SlowStart,
T: WindowAdjustment,
{
fn set_qlog(&mut self, qlog: Qlog) {
self.pmtud.set_qlog(qlog.clone());
self.qlog = qlog;
}
fn cwnd(&self) -> usize {
self.current.congestion_window
}
fn bytes_in_flight(&self) -> usize {
self.bytes_in_flight
}
fn cwnd_avail(&self) -> usize {
// BIF can be higher than cwnd due to PTO packets, which are sent even
// if avail is 0, but still count towards BIF.
self.current
.congestion_window
.saturating_sub(self.bytes_in_flight)
}
fn cwnd_min(&self) -> usize {
self.max_datagram_size() * 2
}
fn pmtud(&self) -> &Pmtud {
&self.pmtud
}
fn pmtud_mut(&mut self) -> &mut Pmtud {
&mut self.pmtud
}
#[expect(
clippy::too_many_lines,
reason = "The main congestion control function contains a lot of logic."
)]
fn on_packets_acked(
&mut self,
acked_pkts: &[sent::Packet],
rtt_est: &RttEstimate,
now: Instant,
cc_stats: &mut CongestionControlStats,
) {
let mut is_app_limited = true;
let mut new_acked = 0;
let largest_packet_acked = acked_pkts
.first()
.expect("`acked_pkts.first().is_some()` is checked in `Loss::on_ack_received`");
// Initialize the stat to the initial congestion window value. If we early return on
// `is_app_limited` the stat is never set on very short connections otherwise.
cc_stats.cwnd.get_or_insert(self.current.congestion_window);
// Supplying `true` for `rtt_est.pto(true)` here is best effort not to have to track
// `recovery::Loss::confirmed()` all the way down to the congestion controller. Having too
// big a PTO does no harm here.
self.cleanup_maybe_lost_packets(now, rtt_est.pto(true));
self.detect_spurious_congestion_event(acked_pkts, cc_stats);
for pkt in acked_pkts {
qtrace!(
"packet_acked this={self:p}, pn={}, ps={}, ignored={}, lost={}, rtt_est={rtt_est:?}",
pkt.pn(),
pkt.len(),
i32::from(!pkt.cc_outstanding()),
i32::from(pkt.lost()),
);
if !pkt.cc_outstanding() {
continue;
}
if pkt.pn() < self.first_app_limited {
is_app_limited = false;
}
// BIF is set to 0 on a path change, but in case that was because of a simple rebinding
// event, we may still get ACKs for packets sent before the rebinding.
self.bytes_in_flight = self.bytes_in_flight.saturating_sub(pkt.len());
if !self.after_recovery_start(pkt) {
// Do not increase congestion window for packets sent before
// recovery last started.
continue;
}
if self.current.phase.in_recovery() {
self.set_phase(Phase::CongestionAvoidance, None, now);
}
new_acked += pkt.len();
}
if self.current.phase.in_slow_start() {
self.slow_start.record_acked_bytes(new_acked);
}
if is_app_limited {
self.congestion_control.on_app_limited();
qdebug!(
"on_packets_acked this={self:p}, limited=1, bytes_in_flight={}, cwnd={}, phase={:?}, new_acked={new_acked}",
self.bytes_in_flight,
self.current.congestion_window,
self.current.phase
);
return;
}
// Slow start: grow up to ssthresh.
if self.current.congestion_window < self.current.ssthresh {
// Check if the slow start algorithm wants to exit.
if let Some(exit_cwnd) = self.slow_start.on_packets_acked(
rtt_est,
largest_packet_acked.pn(),
self.current.congestion_window,
cc_stats,
now,
) {
qdebug!("Exited slow start by algorithm");
self.current.congestion_window = exit_cwnd;
self.current.ssthresh = exit_cwnd;
cc_stats.slow_start_exit_cwnd = Some(exit_cwnd);
cc_stats.slow_start_exit_reason = Some(SlowStartExitReason::Heuristic);
self.set_phase(Phase::CongestionAvoidance, None, now);
} else {
let cwnd_increase = self
.slow_start
.calc_cwnd_increase(new_acked, self.max_datagram_size());
self.current.congestion_window += cwnd_increase;
qtrace!("[{self}] slow start += {cwnd_increase}");
// This can only happen after persistent congestion when we re-enter slow start
// while having a previously established `ssthresh` which has now
// been reached.
if self.current.congestion_window >= self.current.ssthresh {
qdebug!(
"Exited slow start because the threshold was reached, ssthresh: {}",
self.current.ssthresh
);
// Clamp congestion window to ssthresh.
self.current.congestion_window = self.current.ssthresh;
self.set_phase(Phase::CongestionAvoidance, None, now);
}
}
}
// Congestion avoidance, above the slow start threshold.
if self.current.congestion_window >= self.current.ssthresh {
// The following function return the amount acked bytes a controller needs
// to collect to be allowed to increase its cwnd by MAX_DATAGRAM_SIZE.
let bytes_for_increase = self.congestion_control.bytes_for_cwnd_increase(
self.current.congestion_window,
new_acked,
rtt_est.minimum(),
self.max_datagram_size(),
now,
);
debug_assert!(bytes_for_increase > 0);
// If enough credit has been accumulated already, apply them gradually.
// If we have sudden increase in allowed rate we actually increase cwnd gently.
if self.current.acked_bytes >= bytes_for_increase {
self.current.acked_bytes = 0;
self.current.congestion_window += self.max_datagram_size();
}
self.current.acked_bytes += new_acked;
if self.current.acked_bytes >= bytes_for_increase {
self.current.acked_bytes -= bytes_for_increase;
self.current.congestion_window += self.max_datagram_size(); // or is this the current MTU?
}
// The number of bytes we require can go down over time with Cubic.
// That might result in an excessive rate of increase, so limit the number of unused
// acknowledged bytes after increasing the congestion window twice.
self.current.acked_bytes = min(bytes_for_increase, self.current.acked_bytes);
}
cc_stats.cwnd = Some(self.current.congestion_window);
qlog::metrics_updated(
&mut self.qlog,
[
qlog::Metric::CongestionWindow(self.current.congestion_window),
qlog::Metric::BytesInFlight(self.bytes_in_flight),
],
now,
);
qdebug!(
"[{self}] on_packets_acked this={self:p}, limited=0, bytes_in_flight={}, cwnd={}, phase={:?}, new_acked={new_acked}",
self.bytes_in_flight,
self.current.congestion_window,
self.current.phase
);
}
/// Update congestion controller state based on lost packets.
fn on_packets_lost(
&mut self,
first_rtt_sample_time: Option<Instant>,
prev_largest_acked_sent: Option<Instant>,
pto: Duration,
lost_packets: &[sent::Packet],
now: Instant,
cc_stats: &mut CongestionControlStats,
) -> bool {
if lost_packets.is_empty() {
return false;
}
for pkt in lost_packets {
if pkt.cc_in_flight() {
qdebug!(
"packet_lost this={self:p}, pn={}, ps={}",
pkt.pn(),
pkt.len()
);
// bytes_in_flight is set to 0 on a path change, but in case that was because of a
// simple rebinding event, we may still declare packets lost that
// were sent before the rebinding.
self.bytes_in_flight = self.bytes_in_flight.saturating_sub(pkt.len());
if !pkt.is_pmtud_probe() {
let present = self.maybe_lost_packets.insert(
(pkt.pn(), pkt.packet_type()),
MaybeLostPacket {
time_sent: pkt.time_sent(),
},
);
qdebug!(
"Spurious detection: added MaybeLostPacket: pn {}, type {:?}, time_sent {:?}",
pkt.pn(),
pkt.packet_type(),
pkt.time_sent()
);
debug_assert!(present.is_none());
}
}
}
qlog::metrics_updated(
&mut self.qlog,
[qlog::Metric::BytesInFlight(self.bytes_in_flight)],
now,
);
// Lost PMTUD probes do not elicit congestion control reactions, so this closure filters
// them out.
let lost_packets_no_pmtud = || lost_packets.iter().filter(|pkt| !pkt.is_pmtud_probe());
// Packets not in flight don't elicit congestion control reactions either, so we early
// return if there is no lost in-flight packet left.
let Some(last_lost_packet) = lost_packets_no_pmtud().rfind(|pkt| pkt.cc_in_flight()) else {
return false;
};
let congestion = self.on_congestion_event(last_lost_packet, Loss, now, cc_stats);
// Persistent congestion checks still need to see lost packets that are not in-flight for
// continuity checks. That is why only the closure to filter out lost PMTUD probes is used.
let persistent_congestion = self.detect_persistent_congestion(
first_rtt_sample_time,
prev_largest_acked_sent,
pto,
lost_packets_no_pmtud(),
now,
cc_stats,
);
qdebug!(
"on_packets_lost this={self:p}, bytes_in_flight={}, cwnd={}, phase={:?}",
self.bytes_in_flight,
self.current.congestion_window,
self.current.phase
);
congestion || persistent_congestion
}
/// Report received ECN CE mark(s) to the congestion controller as a
/// congestion event.
///
/// See <https://datatracker.ietf.org/doc/html/rfc9002#section-b.7>.
fn on_ecn_ce_received(
&mut self,
largest_acked_pkt: &sent::Packet,
now: Instant,
cc_stats: &mut CongestionControlStats,
) -> bool {
self.on_congestion_event(largest_acked_pkt, Ecn, now, cc_stats)
}
fn discard(&mut self, pkt: &sent::Packet, now: Instant) {
if pkt.cc_outstanding() {
assert!(self.bytes_in_flight >= pkt.len());
self.bytes_in_flight -= pkt.len();
qlog::metrics_updated(
&mut self.qlog,
[qlog::Metric::BytesInFlight(self.bytes_in_flight)],
now,
);
qtrace!("[{self}] Ignore pkt with size {}", pkt.len());
}
}
fn discard_in_flight(&mut self, now: Instant) {
self.bytes_in_flight = 0;
qlog::metrics_updated(
&mut self.qlog,
[qlog::Metric::BytesInFlight(self.bytes_in_flight)],
now,
);
}
fn on_packet_sent(&mut self, pkt: &sent::Packet, now: Instant) {
// Record the recovery time and exit any transient phase.
if self.current.phase.transient() {
self.current.recovery_start = Some(pkt.pn());
qdebug!("set recovery_start to pn={}", pkt.pn());
self.current.phase.update();
}
if !pkt.cc_in_flight() {
return;
}
// Pass next packet number to send into slow start algorithm during slow start.
if self.current.phase.in_slow_start() {
self.slow_start.on_packet_sent(pkt.pn(), pkt.len());
}
if !self.app_limited() {
// Given the current non-app-limited condition, we're fully utilizing the congestion
// window. Assume that all in-flight packets up to this one are NOT app-limited.
// However, subsequent packets might be app-limited. Set `first_app_limited` to the
// next packet number.
self.first_app_limited = pkt.pn() + 1;
}
self.bytes_in_flight += pkt.len();
qdebug!(
"packet_sent this={self:p}, pn={}, ps={}",
pkt.pn(),
pkt.len()
);
qlog::metrics_updated(
&mut self.qlog,
[qlog::Metric::BytesInFlight(self.bytes_in_flight)],
now,
);
}
/// Whether a packet can be sent immediately as a result of entering recovery.
fn recovery_packet(&self) -> bool {
self.current.phase == Phase::RecoveryStart
}
}
const fn cwnd_initial(mtu: usize) -> usize {
const_min(CWND_INITIAL_PKTS * mtu, const_max(2 * mtu, 14_720))
}
impl<S, T> ClassicCongestionController<S, T>
where
S: SlowStart,
T: WindowAdjustment,
{
pub fn new(
slow_start: S,
congestion_control: T,
pmtud: Pmtud,
spurious_recovery: bool,
) -> Self {
let mtu = pmtud.plpmtu();
Self {
slow_start,
congestion_control,
bytes_in_flight: 0,
maybe_lost_packets: HashMap::default(),
qlog: Qlog::disabled(),
first_app_limited: 0,
pmtud,
current: State::new(mtu),
stored: None,
spurious_recovery,
}
}
#[cfg(test)]
#[must_use]
pub const fn ssthresh(&self) -> usize {
self.current.ssthresh
}
#[cfg(test)]
pub const fn set_ssthresh(&mut self, v: usize) {
self.current.ssthresh = v;
}
/// Accessor for [`ClassicCongestionController::congestion_control`]. Is used to call Cubic
/// getters in tests.
#[cfg(test)]
pub const fn congestion_control(&self) -> &T {
&self.congestion_control
}
/// Mutable accessor for [`ClassicCongestionController::congestion_control`]. Is used to call
/// Cubic setters in tests.
#[cfg(test)]
pub const fn congestion_control_mut(&mut self) -> &mut T {
&mut self.congestion_control
}
#[cfg(test)]
pub const fn acked_bytes(&self) -> usize {
self.current.acked_bytes
}
fn set_phase(
&mut self,
phase: Phase,
trigger: Option<qlog::CongestionStateTrigger>,
now: Instant,
) {
if self.current.phase == phase {
return;
}
qdebug!("[{self}] phase -> {phase:?}");
let old_state = self.current.phase;
// Only emit a qlog event when a transition changes the qlog state.
if old_state.to_qlog() != phase.to_qlog() {
qlog::congestion_state_updated(
&mut self.qlog,
old_state.to_qlog(),
phase.to_qlog(),
trigger,
now,
);
}
self.current.phase = phase;
}
// NOTE: Maybe do tracking of lost packets per congestion epoch. Right now if we get a spurious
// event and then before the first was recovered get another (or even a real congestion event
// because of random loss, path change, ...), it will only be detected as spurious once the old
// and new lost packets are recovered. This means we'd have two spurious events counted as one
// and would also only be able to recover to the cwnd prior to the second event.
fn detect_spurious_congestion_event(
&mut self,
acked_packets: &[sent::Packet],
cc_stats: &mut CongestionControlStats,
) {
if self.maybe_lost_packets.is_empty() {
return;
}
// Removes all newly acked packets that are late acks from `maybe_lost_packets`.
for acked_packet in acked_packets {
if self
.maybe_lost_packets
.remove(&(acked_packet.pn(), acked_packet.packet_type()))
.is_some()
{
qdebug!(
"Spurious detection: removed MaybeLostPacket with pn {}, type {:?}",
acked_packet.pn(),
acked_packet.packet_type(),
);
}
}
// If all of them have been removed we detected a spurious congestion event.
if self.maybe_lost_packets.is_empty() {
qdebug!(
"Spurious detection: maybe_lost_packets emptied -> calling on_spurious_congestion_event"
);
self.on_spurious_congestion_event(cc_stats);
}
}
/// Cleanup lost packets that we are fairly sure will never be getting a late acknowledgment
/// for.
fn cleanup_maybe_lost_packets(&mut self, now: Instant, pto: Duration) {
// The `pto * 2` maximum age of the lost packets is taken from msquic's implementation:
// <https://github.com/microsoft/msquic/blob/2623c07df62b4bd171f469fb29c2714b6735b676/src/core/loss_detection.c#L939-L943>
let max_age = pto * 2;
self.maybe_lost_packets.retain(|(pn, pt), packet| {
let keep = now.saturating_duration_since(packet.time_sent) <= max_age;
if !keep {
qdebug!(
"Spurious detection: cleaned up old MaybeLostPacket with pn {pn}, type {pt:?}"
);
}
keep
});
}
fn on_spurious_congestion_event(&mut self, cc_stats: &mut CongestionControlStats) {
let Some(stored) = self.stored.take() else {
qdebug!(
"[{self}] Spurious cong event -> ABORT, no stored params to restore available."
);
return;
};
// The stat is recorded for all cases below.
cc_stats.congestion_events.spurious += 1;
if stored.congestion_window <= self.current.congestion_window {
qinfo!(
"[{self}] Spurious cong event -> IGNORED because stored.cwnd {} < self.cwnd {};",
stored.congestion_window,
self.current.congestion_window
);
return;
}
if !self.spurious_recovery {
qinfo!("[{self}] Spurious cong event detected -> recovery disabled;");
return;
}
self.congestion_control.restore_undo_state(cc_stats);
qdebug!(
"Spurious cong event: recovering cc params from {} to {stored}",
self.current
);
self.current = stored;
// If we are restoring back to slow start then we should undo the stat recording.
if self.current.phase.in_slow_start() {
cc_stats.slow_start_exit_cwnd = None;
cc_stats.slow_start_exit_reason = None;
}
qinfo!("[{self}] Spurious cong event -> RESTORED;");
}
fn detect_persistent_congestion<'a>(
&mut self,
first_rtt_sample_time: Option<Instant>,
prev_largest_acked_sent: Option<Instant>,
pto: Duration,
lost_packets: impl IntoIterator<Item = &'a sent::Packet>,
now: Instant,
cc_stats: &mut CongestionControlStats,
) -> bool {
if first_rtt_sample_time.is_none() {
return false;
}
let pc_period = pto * PERSISTENT_CONG_THRESH;
let mut last_pn = 1 << 62; // Impossibly large, but not enough to overflow.
let mut start = None;
// Look for the first lost packet after the previous largest acknowledged.
// Ignore packets that weren't ack-eliciting for the start of this range.
// Also, make sure to ignore any packets sent before we got an RTT estimate
// as we might not have sent PTO packets soon enough after those.
let cutoff = max(first_rtt_sample_time, prev_largest_acked_sent);
for p in lost_packets
.into_iter()
.skip_while(|p| Some(p.time_sent()) < cutoff)
{
if p.pn() != last_pn + 1 {
// Not a contiguous range of lost packets, start over.
start = None;
}
last_pn = p.pn();
if !p.cc_in_flight() {
// Not interesting, keep looking.
continue;
}
if let Some(t) = start {
let elapsed = p
.time_sent()
.checked_duration_since(t)
.expect("time is monotonic");
if elapsed > pc_period {
qinfo!("[{self}] persistent congestion");
self.current.congestion_window = self.cwnd_min();
self.current.acked_bytes = 0;
self.set_phase(
Phase::PersistentCongestion,
Some(qlog::CongestionStateTrigger::PersistentCongestion),
now,
);
// We re-enter slow start after persistent congestion, so we need to reset any
// state leftover from initial slow start to have it perform correctly.
self.slow_start.reset();
cc_stats.cwnd = Some(self.current.congestion_window);
qlog::metrics_updated(
&mut self.qlog,
[
qlog::Metric::CongestionWindow(self.current.congestion_window),
qlog::Metric::SsThresh(self.current.ssthresh),
],
now,
);
return true;
}
} else {
start = Some(p.time_sent());
}
}
false
}
#[must_use]
fn after_recovery_start(&self, packet: &sent::Packet) -> bool {
// At the start of the recovery period, the phase is transient and
// all packets will have been sent before recovery. When sending out
// the first packet we transition to the non-transient `Recovery`
// phase and update the variable `self.recovery_start`. Before the
// first recovery, all packets were sent after the recovery event,
// allowing to reduce the cwnd on congestion events.
!self.current.phase.transient()
&& self
.current
.recovery_start
.is_none_or(|pn| packet.pn() >= pn)
}
/// Handle a congestion event.
/// Returns true if this was a true congestion event.
fn on_congestion_event(
&mut self,
last_packet: &sent::Packet,
congestion_trigger: CongestionTrigger,
now: Instant,
cc_stats: &mut CongestionControlStats,
) -> bool {
// Start a new congestion event if lost or ECN CE marked packet was sent
// after the start of the previous congestion recovery period.
if !self.after_recovery_start(last_packet) {
qdebug!(
"Called on_congestion_event during recovery -> don't react; last_packet {}, recovery_start {}",
last_packet.pn(),
self.current.recovery_start.unwrap_or(0)
);
return false;
}
if congestion_trigger != Ecn {
self.stored = Some(self.current.clone());
self.congestion_control.save_undo_state();
}
let (cwnd, acked_bytes) = self.congestion_control.reduce_cwnd(
self.current.congestion_window,
self.current.acked_bytes,
self.max_datagram_size(),
congestion_trigger,
cc_stats,
);
self.current.congestion_window = max(cwnd, self.cwnd_min());
self.current.acked_bytes = acked_bytes;
self.current.ssthresh = self.current.congestion_window;
qinfo!(
"[{self}] Cong event -> recovery; cwnd {}, ssthresh {}",
self.current.congestion_window,
self.current.ssthresh
);
match congestion_trigger {
Loss => cc_stats.congestion_events.loss += 1,
Ecn => cc_stats.congestion_events.ecn += 1,
}
cc_stats.cwnd = Some(self.current.congestion_window);
// If we were in slow start when `on_congestion_event` was called we will exit slow start
// and should record the exit congestion window.
if self.current.phase.in_slow_start() {
cc_stats.slow_start_exit_cwnd = Some(self.current.congestion_window);
cc_stats.slow_start_exit_reason = Some(SlowStartExitReason::CongestionEvent);
}
qlog::metrics_updated(
&mut self.qlog,
[
qlog::Metric::CongestionWindow(self.current.congestion_window),
qlog::Metric::SsThresh(self.current.ssthresh),
],
now,
);
let trigger = (congestion_trigger == Ecn).then_some(qlog::CongestionStateTrigger::Ecn);
self.set_phase(Phase::RecoveryStart, trigger, now);
true
}
fn app_limited(&self) -> bool {
if self.bytes_in_flight >= self.current.congestion_window {
false
} else if self.current.phase.in_slow_start() {
// Allow for potential doubling of the congestion window during slow start.
// That is, the application might not have been able to send enough to respond
// to increases to the congestion window.
self.bytes_in_flight < self.current.congestion_window / 2
} else {
// We're not limited if the in-flight data is within a single burst of the
// congestion window.
(self.bytes_in_flight + self.max_datagram_size() * PACING_BURST_SIZE)
< self.current.congestion_window
}
}
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use std::time::{Duration, Instant};
use neqo_common::qinfo;
use test_fixture::{new_neqo_qlog, now};
use super::{ClassicCongestionController, PERSISTENT_CONG_THRESH, SlowStart, WindowAdjustment};
use crate::{
MIN_INITIAL_PACKET_SIZE, Pmtud,
cc::{
CWND_INITIAL_PKTS, ClassicSlowStart, CongestionController,
CongestionTrigger::{self, Ecn, Loss},
classic_cc::Phase,
cubic::Cubic,
new_reno::NewReno,
tests::{IP_ADDR, MTU, RTT, make_cc_cubic, make_cc_hystart, make_cc_newreno},
},
packet,
recovery::{self, sent},
rtt::RttEstimate,
stats::{CongestionControlStats, SlowStartExitReason},
};
const PTO: Duration = RTT;
const ZERO: Duration = Duration::from_secs(0);
const EPSILON: Duration = Duration::from_nanos(1);
const GAP: Duration = Duration::from_secs(1);
/// The largest time between packets without causing persistent congestion.
const SUB_PC: Duration = Duration::from_millis(100 * PERSISTENT_CONG_THRESH as u64);
/// The minimum time between packets to cause persistent congestion.
/// Uses an odd expression because `Duration` arithmetic isn't `const`.
const PC: Duration = Duration::from_nanos(100_000_000 * (PERSISTENT_CONG_THRESH as u64) + 1);
fn cwnd_is_default(cc: &ClassicCongestionController<ClassicSlowStart, NewReno>) {
assert_eq!(cc.cwnd(), cc.cwnd_initial());
assert_eq!(cc.ssthresh(), usize::MAX);
}
fn cwnd_is_halved(cc: &ClassicCongestionController<ClassicSlowStart, NewReno>) {
assert_eq!(cc.cwnd(), cc.cwnd_initial() / 2);
assert_eq!(cc.ssthresh(), cc.cwnd_initial() / 2);
}
fn lost(pn: packet::Number, ack_eliciting: bool, t: Duration) -> sent::Packet {
sent::Packet::new(
packet::Type::Short,
pn,
now() + t,
ack_eliciting,