Debian Codegraph @

third_party/rust/neqo-transport/src/pmtud.rs

raw
1 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4 // option. This file may not be copied, modified, or distributed
5 // except according to those terms.
6
7 use std::{
8 iter::zip,
9 net::IpAddr,
10 time::{Duration, Instant},
11 };
12
13 use neqo_common::{qdebug, qinfo};
14 use static_assertions::const_assert;
15
16 use crate::{frame::FrameType, packet::PacketBuilder, recovery::SentPacket, Stats};
17
18 // Values <= 1500 based on: A. Custura, G. Fairhurst and I. Learmonth, "Exploring Usable Path MTU in
19 // the Internet," 2018 Network Traffic Measurement and Analysis Conference (TMA), Vienna, Austria,
20 // 2018, pp. 1-8, doi: 10.23919/TMA.2018.8506538. keywords:
21 // {Servers;Probes;Tools;Clamps;Middleboxes;Standards},
22 const MTU_SIZES_V4: &[usize] = &[
23 1280, 1380, 1420, 1472, 1500, 2047, 4095, 8191, 16383, 32767, 65535,
24 ];
25 const MTU_SIZES_V6: &[usize] = &[
26 1280, 1380,
27 1420, // 1420 is not in the paper for v6, but adding it makes the arrays the same length
28 1470, 1500, 2047, 4095, 8191, 16383, 32767, 65535,
29 ];
30 const_assert!(MTU_SIZES_V4.len() == MTU_SIZES_V6.len());
31 const SEARCH_TABLE_LEN: usize = MTU_SIZES_V4.len();
32
33 // From https://datatracker.ietf.org/doc/html/rfc8899#section-5.1
34 const MAX_PROBES: usize = 3;
35 const PMTU_RAISE_TIMER: Duration = Duration::from_secs(600);
36
37 #[derive(Debug, PartialEq, Clone, Copy)]
38 enum Probe {
39 NotNeeded,
40 Needed,
41 Sent,
42 }
43
44 #[derive(Debug)]
45 pub struct Pmtud {
46 search_table: &'static [usize],
47 header_size: usize,
48 mtu: usize,
49 iface_mtu: usize,
50 probe_index: usize,
51 probe_count: usize,
52 probe_state: Probe,
53 loss_counts: [usize; SEARCH_TABLE_LEN],
54 raise_timer: Option<Instant>,
55 }
56
57 impl Pmtud {
58 /// Returns the MTU search table for the given remote IP address family.
59 const fn search_table(remote_ip: IpAddr) -> &'static [usize] {
60 match remote_ip {
61 IpAddr::V4(_) => MTU_SIZES_V4,
62 IpAddr::V6(_) => MTU_SIZES_V6,
63 }
64 }
65
66 /// Size of the IPv4/IPv6 and UDP headers, in bytes.
67 const fn header_size(remote_ip: IpAddr) -> usize {
68 match remote_ip {
69 IpAddr::V4(_) => 20 + 8,
70 IpAddr::V6(_) => 40 + 8,
71 }
72 }
73
74 #[must_use]
75 pub fn new(remote_ip: IpAddr, iface_mtu: Option<usize>) -> Self {
76 let search_table = Self::search_table(remote_ip);
77 let probe_index = 0;
78 Self {
79 search_table,
80 header_size: Self::header_size(remote_ip),
81 mtu: search_table[probe_index],
82 iface_mtu: iface_mtu.unwrap_or(usize::MAX),
83 probe_index,
84 probe_count: 0,
85 probe_state: Probe::NotNeeded,
86 loss_counts: [0; SEARCH_TABLE_LEN],
87 raise_timer: None,
88 }
89 }
90
91 /// Checks whether the PMTUD raise timer should be fired, and does so if needed.
92 pub fn maybe_fire_raise_timer(&mut self, now: Instant, stats: &mut Stats) {
93 if self.probe_state == Probe::NotNeeded && self.raise_timer.is_some_and(|t| now >= t) {
94 qdebug!("PMTUD raise timer fired");
95 self.raise_timer = None;
96 self.start(now, stats);
97 }
98 }
99
100 /// Returns the current Packetization Layer Path MTU, i.e., the maximum UDP payload that can be
101 /// sent. During probing, this may be larger than the actual path MTU.
102 #[must_use]
103 pub const fn plpmtu(&self) -> usize {
104 self.mtu - self.header_size
105 }
106
107 /// Returns true if a PMTUD probe should be sent.
108 #[must_use]
109 pub fn needs_probe(&self) -> bool {
110 self.probe_state == Probe::Needed
111 }
112
113 /// Returns the size of the current PMTUD probe.
114 #[must_use]
115 pub const fn probe_size(&self) -> usize {
116 self.search_table[self.probe_index] - self.header_size
117 }
118
119 /// Sends a PMTUD probe.
120 pub fn send_probe(&mut self, builder: &mut PacketBuilder, stats: &mut Stats) {
121 // The packet may include ACK-eliciting data already, but rather than check for that, it
122 // seems OK to burn one byte here to simply include a PING.
123 builder.encode_varint(FrameType::Ping);
124 stats.frame_tx.ping += 1;
125 stats.pmtud_tx += 1;
126 self.probe_count += 1;
127 self.probe_state = Probe::Sent;
128 qdebug!(
129 "Sending PMTUD probe of size {}, count {}",
130 self.search_table[self.probe_index],
131 self.probe_count
132 );
133 }
134
135 #[expect(rustdoc::private_intra_doc_links, reason = "Nicer docs.")]
136 /// Provides a [`Fn`] that returns true if the packet is a PMTUD probe.
137 ///
138 /// Allows filtering packets without holding a reference to [`Pmtud`]. When
139 /// in doubt, use [`Pmtud::is_probe`].
140 pub fn is_probe_filter(&self) -> impl Fn(&SentPacket) -> bool {
141 let probe_state = self.probe_state;
142 let probe_size = self.probe_size();
143
144 move |p: &SentPacket| -> bool { probe_state == Probe::Sent && p.len() == probe_size }
145 }
146
147 /// Returns true if the packet is a PMTUD probe.
148 fn is_probe(&self, p: &SentPacket) -> bool {
149 self.is_probe_filter()(p)
150 }
151
152 /// Count the PMTUD probes included in `pkts`.
153 fn count_probes(&self, pkts: &[SentPacket]) -> usize {
154 pkts.iter().filter(|p| self.is_probe(p)).count()
155 }
156
157 /// Checks whether a PMTUD probe has been acknowledged, and if so, updates the PMTUD state.
158 /// May also initiate a new probe process for a larger MTU.
159 pub fn on_packets_acked(&mut self, acked_pkts: &[SentPacket], now: Instant, stats: &mut Stats) {
160 // Reset the loss counts for all packets sizes <= the size of the largest ACKed packet.
161 let Some(max_len) = acked_pkts.iter().map(SentPacket::len).max() else {
162 // No packets were ACKed, nothing to do.
163 return;
164 };
165
166 let idx = self
167 .search_table
168 .iter()
169 .position(|&mtu| mtu > max_len + self.header_size)
170 .unwrap_or(SEARCH_TABLE_LEN);
171 self.loss_counts.iter_mut().take(idx).for_each(|c| *c = 0);
172
173 let acked = self.count_probes(acked_pkts);
174 if acked == 0 {
175 return;
176 }
177
178 // A probe was ACKed, confirm the new MTU and try to probe upwards further.
179 //
180 // TODO: Maybe we should be tracking stats on a per-probe-size basis rather than just the
181 // total number of successful probes.
182 stats.pmtud_ack += acked;
183 self.mtu = self.search_table[self.probe_index];
184 stats.pmtud_pmtu = self.mtu;
185 qdebug!("PMTUD probe of size {} succeeded", self.mtu);
186 self.start(now, stats);
187 }
188
189 /// Stops the PMTUD process, setting the MTU to the largest successful probe size.
190 fn stop(&mut self, idx: usize, now: Instant, stats: &mut Stats) {
191 self.probe_state = Probe::NotNeeded; // We don't need to send any more probes
192 self.probe_index = idx; // Index of the last successful probe
193 self.mtu = self.search_table[idx]; // Leading to this MTU
194 stats.pmtud_pmtu = self.mtu;
195 self.probe_count = 0; // Reset the count
196 self.loss_counts.fill(0); // Reset the loss counts
197 self.raise_timer = Some(now + PMTU_RAISE_TIMER);
198 qinfo!(
199 "PMTUD stopped, PLPMTU is now {}, raise timer {:?}",
200 self.mtu,
201 self.raise_timer
202 );
203 }
204
205 /// Checks whether a PMTUD probe has been lost. If it has been lost more than `MAX_PROBES`
206 /// times, the PMTUD process is stopped.
207 pub fn on_packets_lost(
208 &mut self,
209 lost_packets: &[SentPacket],
210 stats: &mut Stats,
211 now: Instant,
212 ) {
213 if lost_packets.is_empty() {
214 return;
215 }
216
217 let mut increase = [0; SEARCH_TABLE_LEN];
218 let mut loss_counts_updated = false;
219 for p in lost_packets {
220 let Some(idx) = self
221 .search_table
222 .iter()
223 .position(|&mtu| p.len() + self.header_size <= mtu)
224 else {
225 continue;
226 };
227 // Count each lost packet size <= the current MTU only once. Otherwise a burst loss of
228 // >= MAX_PROBES MTU-sized packets triggers a PMTUD restart. Counting only one of them
229 // here requires three consecutive loss instances of such sizes to trigger a PMTUD
230 // restart.
231 //
232 // Also, ignore losses of packets <= the minimum QUIC packet size, (`searchtable[0]`),
233 // since they just increase loss counts across the board, adding to spurious
234 // PMTUD restarts.
235 if idx > 0 && (increase[idx] == 0 || p.len() > self.plpmtu()) {
236 loss_counts_updated = true;
237 increase[idx] += 1;
238 }
239 }
240
241 if !loss_counts_updated {
242 return;
243 }
244
245 let mut accum = 0;
246 for (c, incr) in zip(&mut self.loss_counts, increase) {
247 accum += incr;
248 *c += accum;
249 }
250
251 // Track lost probes
252 let lost = self.count_probes(lost_packets);
253 stats.pmtud_lost += lost;
254
255 // Check if any packet sizes have been lost MAX_PROBES times or more.
256 //
257 // TODO: It's not clear that MAX_PROBES is the right number for losses of packets that
258 // aren't PMTU probes. We might want to be more conservative, to avoid spurious PMTUD
259 // restarts.
260 let Some(first_failed) = self.loss_counts.iter().position(|&c| c >= MAX_PROBES) else {
261 // If not, keep going.
262 if lost > 0 {
263 // Don't stop the PMTUD process.
264 self.probe_state = Probe::Needed;
265 }
266 return;
267 };
268
269 let largest_ok_idx = first_failed - 1;
270 let largest_ok_mtu = self.search_table[largest_ok_idx];
271 qdebug!(
272 "PMTUD Packet of size > {largest_ok_mtu} lost >= {MAX_PROBES} times, state {:?}",
273 self.probe_state
274 );
275 if largest_ok_mtu < self.mtu {
276 // We saw multiple losses of packets <= the current MTU discovery,
277 // so we need to probe again. To limit connectivity disruptions, we
278 // start the PMTU discovery from the smallest packet up, rather than
279 // the failed packet size down.
280 //
281 // TODO: If we are declaring losses, that means that we're getting
282 // packets through. The size of those will put a floor on the MTU.
283 // We're currently conservative and start from scratch, but we don't
284 // strictly need to do that.
285 self.reset(stats);
286 qdebug!("PMTUD reset and restarting, PLPMTU is now {}", self.mtu);
287 self.start(now, stats);
288 } else {
289 self.stop(largest_ok_idx, now, stats);
290 }
291 }
292
293 /// Resets the PMTUD process, starting from the smallest probe size.
294 fn reset(&mut self, stats: &mut Stats) {
295 self.probe_index = 0;
296 self.mtu = self.search_table[self.probe_index];
297 stats.pmtud_pmtu = self.mtu;
298 self.loss_counts.fill(0);
299 self.raise_timer = None;
300 stats.pmtud_change += 1;
301 }
302
303 /// Starts the next upward PMTUD probe.
304 pub fn start(&mut self, now: Instant, stats: &mut Stats) {
305 if self.probe_index < SEARCH_TABLE_LEN - 1 // Not at the end of the search table
306 // Next size is <= iface MTU
307 && self.search_table[self.probe_index + 1] <= self.iface_mtu
308 {
309 self.probe_state = Probe::Needed; // We need to send a probe
310 self.probe_count = 0; // For the first time
311 self.probe_index += 1; // At this size
312 qdebug!(
313 "PMTUD started with probe size {}",
314 self.search_table[self.probe_index],
315 );
316 } else {
317 // If we're at the end of the search table or hit the local interface MTU, we're done.
318 self.stop(self.probe_index, now, stats);
319 }
320 }
321
322 /// Returns the default PLPMTU for the given remote IP address.
323 #[must_use]
324 pub const fn default_plpmtu(remote_ip: IpAddr) -> usize {
325 let search_table = Self::search_table(remote_ip);
326 search_table[0] - Self::header_size(remote_ip)
327 }
328 }
329
330 #[cfg(all(not(feature = "disable-encryption"), test))]
331 mod tests {
332 use std::{
333 cmp::min,
334 iter::zip,
335 net::{IpAddr, Ipv4Addr, Ipv6Addr},
336 time::Instant,
337 };
338
339 use neqo_common::{qdebug, qinfo, Encoder};
340 use test_fixture::{fixture_init, now};
341
342 use crate::{
343 crypto::CryptoDxState,
344 packet::{PacketBuilder, PacketType},
345 pmtud::{Probe, PMTU_RAISE_TIMER, SEARCH_TABLE_LEN},
346 recovery::{SendProfile, SentPacket},
347 Pmtud, Stats,
348 };
349
350 const V4: IpAddr = IpAddr::V4(Ipv4Addr::UNSPECIFIED);
351 const V6: IpAddr = IpAddr::V6(Ipv6Addr::UNSPECIFIED);
352 const IFACE_MTUS: &[Option<usize>] = &[
353 None,
354 Some(1300),
355 Some(1500),
356 Some(5000),
357 Some(u16::MAX as usize),
358 ];
359
360 const fn make_sentpacket(pn: u64, now: Instant, len: usize) -> SentPacket {
361 SentPacket::new(PacketType::Short, pn, now, true, Vec::new(), len)
362 }
363
364 /// Asserts that the PMTUD process has stopped at the given MTU.
365 #[cfg(test)]
366 fn assert_mtu(pmtud: &Pmtud, mtu: usize) {
367 let idx = pmtud
368 .search_table
369 .iter()
370 .position(|mtu| *mtu == pmtud.mtu)
371 .unwrap();
372 assert!((idx == 0 && mtu <= pmtud.search_table[idx]) || (mtu >= pmtud.search_table[idx]));
373 if idx < SEARCH_TABLE_LEN - 1 {
374 assert!(mtu < pmtud.search_table[idx + 1]);
375 }
376 assert_eq!(Probe::NotNeeded, pmtud.probe_state);
377 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
378 }
379
380 #[cfg(test)]
381 fn pmtud_step(
382 pmtud: &mut Pmtud,
383 stats: &mut Stats,
384 prot: &mut CryptoDxState,
385 addr: IpAddr,
386 mtu: usize,
387 now: Instant,
388 ) {
389 let stats_before = stats.clone();
390
391 // Fake a packet number, so the builder logic works.
392 let mut builder = PacketBuilder::short(Encoder::new(), false, None::<&[u8]>);
393 let pn = prot.next_pn();
394 builder.pn(pn, 4);
395 builder.set_initial_limit(&SendProfile::new_limited(pmtud.plpmtu()), 16, pmtud);
396 builder.enable_padding(true);
397 pmtud.send_probe(&mut builder, stats);
398 builder.pad();
399 let encoder = builder.build(prot).unwrap();
400 assert_eq!(encoder.len(), pmtud.probe_size());
401 assert!(!pmtud.needs_probe());
402 assert_eq!(stats_before.pmtud_tx + 1, stats.pmtud_tx);
403
404 let packet = make_sentpacket(pn, now, encoder.len());
405 if encoder.len() + Pmtud::header_size(addr) <= mtu {
406 pmtud.on_packets_acked(&[packet], now, stats);
407 assert_eq!(stats_before.pmtud_ack + 1, stats.pmtud_ack);
408 } else {
409 pmtud.on_packets_lost(&[packet], stats, now);
410 assert_eq!(stats_before.pmtud_lost + 1, stats.pmtud_lost);
411 }
412 }
413
414 fn find_pmtu(
415 addr: IpAddr,
416 mtu: usize,
417 iface_mtu: Option<usize>,
418 ) -> (Pmtud, Stats, CryptoDxState, Instant) {
419 fixture_init();
420 let now = now();
421 let mut pmtud = Pmtud::new(addr, iface_mtu);
422 let mut stats = Stats::default();
423 let mut prot = CryptoDxState::test_default();
424
425 pmtud.start(now, &mut stats);
426
427 if let Some(iface_mtu) = iface_mtu {
428 assert!(iface_mtu <= pmtud.search_table[1] || pmtud.needs_probe());
429 } else {
430 assert!(pmtud.needs_probe());
431 }
432
433 while pmtud.needs_probe() {
434 pmtud_step(&mut pmtud, &mut stats, &mut prot, addr, mtu, now);
435 }
436
437 let final_mtu = iface_mtu.map_or(mtu, |iface_mtu| min(mtu, iface_mtu));
438 assert_mtu(&pmtud, final_mtu);
439
440 (pmtud, stats, prot, now)
441 }
442
443 fn find_pmtu_with_reduction(addr: IpAddr, mtu: usize, smaller_mtu: usize) {
444 assert!(mtu > smaller_mtu);
445 let (mut pmtud, mut stats, mut prot, now) = find_pmtu(addr, mtu, None);
446
447 qdebug!("Reducing MTU to {smaller_mtu}");
448 while !pmtud.needs_probe() {
449 pmtud_step(&mut pmtud, &mut stats, &mut prot, addr, smaller_mtu, now);
450 }
451
452 // Drive second PMTUD process to completion.
453 while pmtud.needs_probe() {
454 pmtud_step(&mut pmtud, &mut stats, &mut prot, addr, smaller_mtu, now);
455 }
456 assert_mtu(&pmtud, smaller_mtu);
457 }
458
459 fn find_pmtu_with_increase(addr: IpAddr, mtu: usize, larger_mtu: usize) {
460 assert!(mtu < larger_mtu);
461 let (mut pmtud, mut stats, mut prot, now) = find_pmtu(addr, mtu, None);
462
463 assert!(larger_mtu >= pmtud.search_table[0]);
464 pmtud.start(now, &mut stats);
465 assert!(pmtud.needs_probe());
466
467 while pmtud.needs_probe() {
468 pmtud_step(&mut pmtud, &mut stats, &mut prot, addr, mtu, now);
469 }
470 assert_mtu(&pmtud, mtu);
471
472 qdebug!("Increasing MTU to {larger_mtu}");
473 let now = now + PMTU_RAISE_TIMER;
474 pmtud.maybe_fire_raise_timer(now, &mut stats);
475 while pmtud.needs_probe() {
476 pmtud_step(&mut pmtud, &mut stats, &mut prot, addr, larger_mtu, now);
477 }
478 assert_mtu(&pmtud, larger_mtu);
479 }
480
481 fn path_mtus() -> Vec<usize> {
482 IFACE_MTUS.iter().flatten().copied().collect()
483 }
484
485 #[test]
486 fn pmtud() {
487 for &addr in &[V4, V6] {
488 for path_mtu in path_mtus() {
489 for &iface_mtu in IFACE_MTUS {
490 qinfo!("PMTUD for {addr}, path MTU {path_mtu}, iface MTU {iface_mtu:?}");
491 find_pmtu(addr, path_mtu, iface_mtu);
492 }
493 }
494 }
495 }
496
497 #[test]
498 fn pmtud_with_reduction() {
499 for &addr in &[V4, V6] {
500 for path_mtu in path_mtus() {
501 let path_mtus = path_mtus();
502 let smaller_mtus = path_mtus.iter().filter(|&mtu| *mtu < path_mtu);
503 for &smaller_mtu in smaller_mtus {
504 qinfo!("PMTUD for {addr}, path MTU {path_mtu}, smaller path MTU {smaller_mtu}");
505 find_pmtu_with_reduction(addr, path_mtu, smaller_mtu);
506 }
507 }
508 }
509 }
510
511 #[test]
512 fn pmtud_with_increase() {
513 for &addr in &[V4, V6] {
514 for path_mtu in path_mtus() {
515 let path_mtus = path_mtus();
516 let larger_mtus = path_mtus.iter().filter(|&mtu| *mtu > path_mtu);
517 for &larger_mtu in larger_mtus {
518 qinfo!("PMTUD for {addr}, path MTU {path_mtu}, larger path MTU {larger_mtu}");
519 find_pmtu_with_increase(addr, path_mtu, larger_mtu);
520 }
521 }
522 }
523 }
524
525 /// Increments the loss counts for the given search table, based on the given packet size.
526 fn search_table_inc(pmtud: &Pmtud, loss_counts: &[usize], lost_size: usize) -> Vec<usize> {
527 zip(pmtud.search_table, loss_counts.iter())
528 .map(|(&size, &count)| {
529 if size >= lost_size + pmtud.header_size {
530 count + 1
531 } else {
532 count
533 }
534 })
535 .collect()
536 }
537
538 /// Asserts that the PMTUD process has restarted.
539 fn assert_pmtud_restarted(pmtud: &Pmtud) {
540 assert_eq!(Probe::Needed, pmtud.probe_state);
541 assert_eq!(pmtud.mtu, pmtud.search_table[0]);
542 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
543 }
544
545 #[test]
546 fn pmtud_on_packets_lost() {
547 const MTU: usize = 1500;
548 let now = now();
549 let mut pmtud = Pmtud::new(V4, Some(MTU));
550 let mut stats = Stats::default();
551 // Start with completed PMTUD with MTU 1500.
552 pmtud.stop(
553 pmtud
554 .search_table
555 .iter()
556 .position(|&mtu| mtu == MTU)
557 .unwrap(),
558 now,
559 &mut stats,
560 );
561 assert_mtu(&pmtud, MTU);
562
563 // No packets lost, nothing should change.
564 pmtud.on_packets_lost(&[], &mut stats, now);
565 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
566
567 // A packet of size 100 was lost, which is smaller than all probe sizes.
568 // Loss counts should be unchanged.
569 pmtud.on_packets_lost(&[make_sentpacket(0, now, 100)], &mut stats, now);
570 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
571
572 // A packet of size 100_000 was lost, which is larger than all probe sizes.
573 // Loss counts should be unchanged.
574 pmtud.on_packets_lost(&[make_sentpacket(0, now, 100_000)], &mut stats, now);
575 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
576
577 pmtud.loss_counts.fill(0); // Reset the loss counts.
578
579 // A packet of size 1500 was lost, which should increase loss counts >= 1500 by one.
580 let plen = MTU - pmtud.header_size;
581 let mut expected_lc = search_table_inc(&pmtud, &pmtud.loss_counts, plen);
582 pmtud.on_packets_lost(&[make_sentpacket(0, now, plen)], &mut stats, now);
583 assert_eq!(expected_lc, pmtud.loss_counts);
584
585 // A packet of size 2000 was lost, which should increase loss counts >= 2000 by one.
586 expected_lc = search_table_inc(&pmtud, &expected_lc, 2000);
587 pmtud.on_packets_lost(&[make_sentpacket(0, now, 2000)], &mut stats, now);
588 assert_eq!(expected_lc, pmtud.loss_counts);
589
590 // A packet of size 5000 was lost, which should increase loss counts >= 5000 by one. There
591 // have now been MAX_PROBES losses of packets >= 5000. That should stop PMTUD.
592 expected_lc = search_table_inc(&pmtud, &expected_lc, 5000);
593 pmtud.on_packets_lost(&[make_sentpacket(0, now, 5000)], &mut stats, now);
594 assert_mtu(&pmtud, 4095);
595 expected_lc.fill(0); // Reset the loss counts.
596
597 // Two packets of size 4000 were lost, which should increase loss counts >= 4000 by one.
598 expected_lc = search_table_inc(&pmtud, &expected_lc, 4000);
599 pmtud.on_packets_lost(
600 &[make_sentpacket(0, now, 4000), make_sentpacket(1, now, 4000)],
601 &mut stats,
602 now,
603 );
604 assert_eq!(expected_lc, pmtud.loss_counts);
605
606 // Two packets of size 2000 were lost, which should increase loss counts >= 2000 by one.
607 expected_lc = search_table_inc(&pmtud, &expected_lc, 2000);
608 pmtud.on_packets_lost(
609 &[make_sentpacket(0, now, 2000), make_sentpacket(1, now, 2000)],
610 &mut stats,
611 now,
612 );
613 assert_eq!(expected_lc, pmtud.loss_counts);
614
615 // Two more packet of size 1500 were lost. There have now been MAX_PROBES losses of packets
616 // >= 1500. That should restart PMTUD.
617 let plen = MTU - pmtud.header_size;
618 pmtud.on_packets_lost(
619 &[make_sentpacket(0, now, plen), make_sentpacket(1, now, plen)],
620 &mut stats,
621 now,
622 );
623 assert_pmtud_restarted(&pmtud);
624 }
625
626 /// Zeros the loss counts for the given search table, below the given packet size.
627 fn search_table_zero(pmtud: &Pmtud, loss_counts: &[usize], sz: usize) -> Vec<usize> {
628 zip(pmtud.search_table, loss_counts.iter())
629 .map(|(&s, &c)| if s <= sz + pmtud.header_size { 0 } else { c })
630 .collect()
631 }
632
633 #[test]
634 fn pmtud_on_packets_lost_and_acked() {
635 const MTU: usize = 1500;
636 let now = now();
637 let mut pmtud = Pmtud::new(V4, Some(MTU));
638 let mut stats = Stats::default();
639 // Start with completed PMTUD with MTU 1500.
640 pmtud.stop(
641 pmtud
642 .search_table
643 .iter()
644 .position(|&mtu| mtu == MTU)
645 .unwrap(),
646 now,
647 &mut stats,
648 );
649 assert_mtu(&pmtud, MTU);
650
651 // A packet of size 100 was ACKed, which is smaller than all probe sizes.
652 // Loss counts should be unchanged.
653 pmtud.on_packets_acked(&[make_sentpacket(0, now, 100)], now, &mut stats);
654 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
655
656 // A packet of size 100_000 was ACKed, which is larger than all probe sizes.
657 // Loss counts should be unchanged.
658 pmtud.on_packets_acked(&[make_sentpacket(0, now, 100_000)], now, &mut stats);
659 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
660
661 pmtud.loss_counts.fill(0); // Reset the loss counts.
662
663 // No packets ACKed, nothing should change.
664 pmtud.on_packets_acked(&[], now, &mut stats);
665 assert_eq!([0; SEARCH_TABLE_LEN], pmtud.loss_counts);
666
667 // One packet of size 4000 was lost, which should increase loss counts >= 4000 by one.
668 let mut expected_lc = search_table_inc(&pmtud, &pmtud.loss_counts, 4000);
669 pmtud.on_packets_lost(&[make_sentpacket(0, now, 4000)], &mut stats, now);
670 assert_eq!(expected_lc, pmtud.loss_counts);
671
672 // Now a packet of size 5000 is ACKed, which should reset all loss counts <= 5000.
673 pmtud.on_packets_acked(&[make_sentpacket(0, now, 5000)], now, &mut stats);
674 expected_lc = search_table_zero(&pmtud, &pmtud.loss_counts, 5000);
675 assert_eq!(expected_lc, pmtud.loss_counts);
676
677 // Now, one more packets of size 4000 was lost, which should increase loss counts >= 4000
678 // by one.
679 expected_lc = search_table_inc(&pmtud, &expected_lc, 4000);
680 pmtud.on_packets_lost(&[make_sentpacket(0, now, 4000)], &mut stats, now);
681 assert_eq!(expected_lc, pmtud.loss_counts);
682
683 // Now a packet of size 8000 is ACKed, which should reset all loss counts <= 8000.
684 pmtud.on_packets_acked(&[make_sentpacket(0, now, 8000)], now, &mut stats);
685 expected_lc = search_table_zero(&pmtud, &pmtud.loss_counts, 8000);
686 assert_eq!(expected_lc, pmtud.loss_counts);
687
688 // Now, one more packets of size 9000 was lost, which should increase loss counts >= 9000
689 // by one. There have now been MAX_PROBES losses of packets >= 8191, but that is larger than
690 // the current MTU, so nothing will happen.
691 pmtud.on_packets_lost(&[make_sentpacket(0, now, 9000)], &mut stats, now);
692
693 for _ in 0..2 {
694 // One packet of size 1400 was lost, which should increase loss counts >= 1400 by one.
695 expected_lc = search_table_inc(&pmtud, &pmtud.loss_counts, 1400);
696 pmtud.on_packets_lost(&[make_sentpacket(0, now, 1400)], &mut stats, now);
697 assert_eq!(expected_lc, pmtud.loss_counts);
698 }
699
700 // One packet of size 1400 was lost, which should increase loss counts >= 1400 by one.
701 pmtud.on_packets_lost(&[make_sentpacket(0, now, 1400)], &mut stats, now);
702
703 // This was the third loss of a packet <= the current MTU, which should trigger a PMTUD
704 // restart.
705 assert_pmtud_restarted(&pmtud);
706 }
707 }