ergon-tune 0.1.45

Start-up and housekeeping checks of a host's low-latency settings (CPU isolation, NIC interrupts, transparent hugepages, the Aeron directory, NUMA, scheduling policy, SMT siblings, a CPU quota and its throttling, how CLOCK_REALTIME is kept and the kernel's clock source, background noise on the hot CPUs (unbound workqueues, compaction, other processes' tasks, kernel instrumentation, KSM, steal), a hot thread's page faults, the IRQ CPUs' idle depth and TCP autocorking, and with `nic` the NIC's moderation, deferral, VF and ring): pure functions returning findings, with no threads or statics, and one audited unsafe call (a read-only adjtimex)
Documentation
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
//! The NIC checks (feature `nic`): N1 ENA adaptive RX moderation, N2
//! deferred interrupts without a busy poller, N3 the accelerated-networking
//! VF, N4 the kernel RX ring, N5 IRQ-CPU headroom with moderation off.
//!
//! N1, N4 and N5 ask the kernel through [`Ethtool`]: [`Netlink`] sends
//! ethtool's generic-netlink `COALESCE_GET` and `RINGS_GET`, which need no
//! privilege and work from any network namespace. [`EthtoolCache`], owned
//! by the caller, keeps the answers per (interface index, `carrier_changes`),
//! so a reset (an ENA reset turns adaptive moderation back on and re-hints
//! the IRQs) makes the next check ask again.

mod genl;

use std::fmt;
use std::time::Duration;

use crate::finding::{Finding, HotSet, Severity};
use crate::host::{Host, ReadError};
use crate::net::{
    Nic, carrier_changes, check_interface, interface_device, lower_interfaces, nic_irqs, no_device,
};
use crate::platform::Platform;

/// A NIC's interrupt coalescing, as ethtool's `COALESCE_GET` reports it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Coalesce {
    /// Adaptive RX moderation; `None` when the driver does not offer it.
    pub use_adaptive_rx: Option<bool>,
    /// The RX interrupt delay (µs); `None` when not offered.
    pub rx_usecs: Option<u32>,
}

/// A NIC's ring sizes, as ethtool's `RINGS_GET` reports them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Rings {
    /// RX ring entries; `None` when not reported.
    pub rx: Option<u32>,
    /// The most RX ring entries the NIC takes; `None` when not reported.
    pub rx_max: Option<u32>,
}

/// Why an ethtool query has no answer.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EthtoolError {
    /// Not Linux.
    NotLinux,
    /// The host is a tree standing for one ([`Host::at`]): the kernel
    /// answers only for the running host.
    NotLive,
    /// The interface's index or `carrier_changes` could not be read.
    Interface(ReadError),
    /// The netlink socket failed (the error number).
    Socket(i32),
    /// The kernel did not answer in time.
    Timeout,
    /// The kernel has no ethtool netlink family (before Linux 5.6, or built
    /// without `CONFIG_ETHTOOL_NETLINK`).
    NoFamily,
    /// The kernel refused (the error number): `EOPNOTSUPP` when the driver
    /// has no such settings, `ENODEV` when the interface went away.
    Kernel(i32),
    /// The answer did not parse.
    Malformed(&'static str),
}

impl fmt::Display for EthtoolError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotLinux => f.write_str("ethtool netlink: only Linux has it"),
            Self::NotLive => f.write_str("ethtool netlink: not the running host"),
            Self::Interface(e) => write!(f, "{e}"),
            Self::Socket(errno) => write!(f, "ethtool netlink: socket error (errno {errno})"),
            Self::Timeout => write!(
                f,
                "ethtool netlink: no answer within {} ms",
                TIMEOUT.as_millis()
            ),
            Self::NoFamily => f.write_str(
                "ethtool netlink: the kernel has no ethtool family (Linux 5.6 or later with CONFIG_ETHTOOL_NETLINK)",
            ),
            Self::Kernel(errno) => {
                write!(f, "ethtool netlink: the kernel refused (errno {errno})")
            }
            Self::Malformed(what) => write!(f, "ethtool netlink: {what}"),
        }
    }
}

impl std::error::Error for EthtoolError {}

/// `EOPNOTSUPP` as this architecture's kernel numbers it (95 on x86-64 and
/// arm64; Alpha, MIPS, PA-RISC and SPARC differ).
#[cfg(target_os = "linux")]
const EOPNOTSUPP: i32 = rustix::io::Errno::OPNOTSUPP.raw_os_error();
/// Elsewhere no kernel answers ([`EthtoolError::NotLinux`]); Linux's
/// x86-64 and arm64 number, for stand-in sources in tests.
#[cfg(not(target_os = "linux"))]
const EOPNOTSUPP: i32 = 95;

/// How long one netlink exchange may wait, as for an rtnetlink route lookup.
const TIMEOUT: Duration = Duration::from_millis(100);

/// Where ethtool settings come from: [`Netlink`] on the running host, or a
/// stand-in in tests.
pub trait Ethtool {
    /// The coalescing settings of interface `ifindex` on `host`.
    ///
    /// # Errors
    /// No answer: see [`EthtoolError`].
    fn coalesce(&mut self, host: &Host, ifindex: u32) -> Result<Coalesce, EthtoolError>;

    /// The ring sizes of interface `ifindex` on `host`.
    ///
    /// # Errors
    /// No answer: see [`EthtoolError`].
    fn rings(&mut self, host: &Host, ifindex: u32) -> Result<Rings, EthtoolError>;
}

/// Ethtool over generic netlink, unprivileged.
///
/// One request and its reply on a fresh `NETLINK_GENERIC` socket per
/// query, with 100 ms send and receive timeouts on each exchange. Resolves
/// the `ethtool` family once, in an exchange of its own, and keeps its id.
#[derive(Clone, Debug, Default)]
pub struct Netlink {
    family: Option<u16>,
    seq: u32,
}

impl Netlink {
    /// A client that has not yet resolved the family.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            family: None,
            seq: 0,
        }
    }

    const fn next_seq(&mut self) -> u32 {
        self.seq = self.seq.wrapping_add(1);
        self.seq
    }

    fn family(&mut self) -> Result<u16, EthtoolError> {
        if let Some(f) = self.family {
            return Ok(f);
        }
        let seq = self.next_seq();
        let mut reply = vec![0u8; 8192];
        let n = exchange(&genl::get_family(seq), &mut reply)?;
        let f = genl::decode_family(&reply[..n], seq)?;
        self.family = Some(f);
        Ok(f)
    }

    fn query(
        &mut self,
        host: &Host,
        cmd: u8,
        ifindex: u32,
    ) -> Result<(Vec<u8>, u32, u16), EthtoolError> {
        if !host.is_live() {
            return Err(EthtoolError::NotLive);
        }
        let family = self.family()?;
        let seq = self.next_seq();
        let mut reply = vec![0u8; 4096];
        let n = exchange(&genl::ethtool_get(family, cmd, ifindex, seq), &mut reply)?;
        reply.truncate(n);
        Ok((reply, seq, family))
    }
}

impl Ethtool for Netlink {
    fn coalesce(&mut self, host: &Host, ifindex: u32) -> Result<Coalesce, EthtoolError> {
        let (reply, seq, family) = self.query(host, genl::ETHTOOL_MSG_COALESCE_GET, ifindex)?;
        genl::decode_coalesce(&reply, seq, family, ifindex)
    }

    fn rings(&mut self, host: &Host, ifindex: u32) -> Result<Rings, EthtoolError> {
        let (reply, seq, family) = self.query(host, genl::ETHTOOL_MSG_RINGS_GET, ifindex)?;
        genl::decode_rings(&reply, seq, family, ifindex)
    }
}

/// One request and its reply on a fresh `NETLINK_GENERIC` socket, as an
/// rtnetlink exchange: the kernel answers inside `sendto`, a
/// signal is the only reason to look twice, and a reply must come from the
/// kernel (port 0) and fit the buffer.
#[cfg(target_os = "linux")]
fn exchange(req: &[u8], reply: &mut [u8]) -> Result<usize, EthtoolError> {
    use rustix::io::Errno;
    use rustix::net::netlink::{self, SocketAddrNetlink};
    use rustix::net::sockopt::{self, Timeout};
    use rustix::net::{AddressFamily, RecvFlags, SendFlags, SocketFlags, SocketType};

    let failed = |e: Errno| {
        if e == Errno::AGAIN || e == Errno::WOULDBLOCK {
            EthtoolError::Timeout
        } else {
            EthtoolError::Socket(e.raw_os_error())
        }
    };
    let fd = rustix::net::socket_with(
        AddressFamily::NETLINK,
        SocketType::RAW,
        SocketFlags::CLOEXEC,
        Some(netlink::GENERIC),
    )
    .map_err(failed)?;
    sockopt::set_socket_timeout(&fd, Timeout::Recv, Some(TIMEOUT)).map_err(failed)?;
    sockopt::set_socket_timeout(&fd, Timeout::Send, Some(TIMEOUT)).map_err(failed)?;
    let kernel = SocketAddrNetlink::new(0, 0);
    let sent = rustix::net::sendto(&fd, req, SendFlags::empty(), &kernel).map_err(failed)?;
    if sent != req.len() {
        return Err(EthtoolError::Malformed("netlink request cut short"));
    }
    for _ in 0..3 {
        match rustix::net::recvfrom(&fd, &mut *reply, RecvFlags::TRUNC) {
            Ok((_, n, from)) => {
                let from = from
                    .and_then(|a| SocketAddrNetlink::try_from(a).ok())
                    .ok_or(EthtoolError::Malformed("netlink reply without its sender"))?;
                if from.pid() != 0 {
                    return Err(EthtoolError::Malformed("netlink reply not from the kernel"));
                }
                if n > reply.len() {
                    return Err(EthtoolError::Malformed(
                        "netlink reply larger than the buffer",
                    ));
                }
                return Ok(n);
            }
            Err(Errno::INTR) => {}
            Err(e) => return Err(failed(e)),
        }
    }
    Err(EthtoolError::Socket(Errno::INTR.raw_os_error()))
}

#[cfg(not(target_os = "linux"))]
const fn exchange(req: &[u8], reply: &mut [u8]) -> Result<usize, EthtoolError> {
    let _ = (req, reply);
    Err(EthtoolError::NotLinux)
}

/// What is kept for one interface.
#[derive(Debug)]
struct Entry {
    ifindex: u32,
    carrier_changes: u64,
    coalesce: Option<Result<Coalesce, EthtoolError>>,
    rings: Option<Result<Rings, EthtoolError>>,
}

/// Ethtool answers per interface, valid while its index and
/// `carrier_changes` stay the same.
///
/// Owned by the caller (no global state): a network I/O layer's warning thread or the
/// media driver's housekeeping keeps one. Timeouts and socket errors are
/// not kept.
#[derive(Debug, Default)]
pub struct EthtoolCache<E: Ethtool = Netlink> {
    source: E,
    entries: Vec<Entry>,
    queries: u64,
}

impl EthtoolCache<Netlink> {
    /// An empty cache over [`Netlink`].
    #[must_use]
    pub const fn new() -> Self {
        Self::with_source(Netlink::new())
    }
}

/// Whether an answer may be kept: not a transient failure.
const fn keep<T>(r: &Result<T, EthtoolError>) -> bool {
    !matches!(
        r,
        Err(EthtoolError::Timeout
            | EthtoolError::Socket(_)
            | EthtoolError::Interface(_)
            | EthtoolError::NotLive
            | EthtoolError::NotLinux)
    )
}

impl<E: Ethtool> EthtoolCache<E> {
    /// An empty cache over `source`.
    #[must_use]
    pub const fn with_source(source: E) -> Self {
        Self {
            source,
            entries: Vec::new(),
            queries: 0,
        }
    }

    /// How many queries reached the source.
    #[must_use]
    pub const fn queries(&self) -> u64 {
        self.queries
    }

    /// The source, to change a stand-in's answers.
    pub const fn source_mut(&mut self) -> &mut E {
        &mut self.source
    }

    /// The entry for `interface`, emptied when its `carrier_changes` moved.
    fn entry(&mut self, host: &Host, interface: &str) -> Result<usize, EthtoolError> {
        check_interface(interface).map_err(EthtoolError::Interface)?;
        let path = format!("/sys/class/net/{interface}/ifindex");
        let ifindex = host
            .read_i64(&path)
            .and_then(|i| {
                u32::try_from(i).map_err(|_| ReadError::Malformed {
                    path,
                    detail: "not an interface index",
                })
            })
            .map_err(EthtoolError::Interface)?;
        let carrier = carrier_changes(host, interface).map_err(EthtoolError::Interface)?;
        if let Some(i) = self.entries.iter().position(|e| e.ifindex == ifindex) {
            let e = &mut self.entries[i];
            if e.carrier_changes != carrier {
                e.carrier_changes = carrier;
                e.coalesce = None;
                e.rings = None;
            }
            return Ok(i);
        }
        self.entries.push(Entry {
            ifindex,
            carrier_changes: carrier,
            coalesce: None,
            rings: None,
        });
        Ok(self.entries.len() - 1)
    }

    /// `interface`'s coalescing settings, asked once per (index,
    /// `carrier_changes`).
    ///
    /// # Errors
    /// No answer: see [`EthtoolError`].
    pub fn coalesce(&mut self, host: &Host, interface: &str) -> Result<Coalesce, EthtoolError> {
        let i = self.entry(host, interface)?;
        if let Some(r) = &self.entries[i].coalesce {
            return r.clone();
        }
        self.queries += 1;
        let r = self.source.coalesce(host, self.entries[i].ifindex);
        if keep(&r) {
            self.entries[i].coalesce = Some(r.clone());
        }
        r
    }

    /// `interface`'s ring sizes, asked once per (index, `carrier_changes`).
    ///
    /// # Errors
    /// No answer: see [`EthtoolError`].
    pub fn rings(&mut self, host: &Host, interface: &str) -> Result<Rings, EthtoolError> {
        let i = self.entry(host, interface)?;
        if let Some(r) = &self.entries[i].rings {
            return r.clone();
        }
        self.queries += 1;
        let r = self.source.rings(host, self.entries[i].ifindex);
        if keep(&r) {
            self.entries[i].rings = Some(r.clone());
        }
        r
    }
}

/// `interface`'s driver, or the unknown finding when its device is not
/// visible.
fn driver_of(
    host: &Host,
    interface: &str,
    id: &'static str,
    evidence: &'static str,
    what: &str,
) -> Result<String, Finding> {
    match interface_device(host, interface) {
        Ok(Some(d)) => Ok(d.driver.unwrap_or_else(|| "none".to_owned())),
        Ok(None) => Err(Finding::unknown(
            id,
            Severity::Warn,
            evidence,
            format!("cannot tell {what}"),
            no_device(interface),
        )),
        Err(e) => Err(Finding::unknown(
            id,
            Severity::Warn,
            evidence,
            format!("cannot tell {what}"),
            e,
        )),
    }
}

const N1_EVIDENCE: &str = "Linux \
     drivers/net/ethernet/amazon/ena/ena_netdev.c (ena_up enables adaptive moderation); \
     aws-graviton-getting-started perfrunbook (adaptive-rx off for latency-sensitive work)";

/// N1: ENA's adaptive RX interrupt moderation is off on `interface`. For
/// kernel-socket paths on AWS, x86 and Graviton; other drivers are not
/// checked.
#[must_use]
pub fn n1_adaptive_rx<E: Ethtool>(
    host: &Host,
    interface: &str,
    cache: &mut EthtoolCache<E>,
) -> Finding {
    let id = "N1";
    let sev = Severity::Warn;
    let what = format!("whether {interface}'s adaptive RX moderation is on");
    let driver = match driver_of(host, interface, id, N1_EVIDENCE, &what) {
        Ok(d) => d,
        Err(f) => return f,
    };
    if driver != "ena" {
        return Finding::ok(
            id,
            sev,
            N1_EVIDENCE,
            format!("{interface}'s driver is {driver}: N1 is for AWS's ENA"),
        );
    }
    match cache.coalesce(host, interface) {
        Ok(Coalesce {
            use_adaptive_rx: Some(true),
            ..
        }) => {
            let platform = if Platform::detect(host).is_graviton() {
                " AWS's Graviton performance runbook says to turn it off for latency-sensitive \
                 work."
            } else {
                ""
            };
            Finding::found(
                id,
                sev,
                N1_EVIDENCE,
                format!(
                    "{interface}: adaptive RX interrupt moderation is on: the driver re-tunes \
                     the interrupt delay from a kernel worker on the CPU that polls the queue, \
                     which for a busy-polling loop is the loop's own CPU (not measured \
                     here).{platform} Fix: `ethtool -C {interface} adaptive-rx off rx-usecs 0`; ENA \
                     turns adaptive moderation back on at every reset, so apply it again after one \
                     (when carrier_changes moves)"
                ),
            )
        }
        Ok(Coalesce {
            use_adaptive_rx: Some(false),
            rx_usecs,
        }) => Finding::ok(
            id,
            sev,
            N1_EVIDENCE,
            format!(
                "{interface}: adaptive RX moderation is off{}",
                rx_usecs.map_or_else(String::new, |u| format!(" (rx-usecs {u})"))
            ),
        ),
        Ok(Coalesce {
            use_adaptive_rx: None,
            ..
        }) => Finding::ok(
            id,
            sev,
            N1_EVIDENCE,
            format!("{interface}: the driver does not offer adaptive RX moderation"),
        ),
        Err(EthtoolError::Kernel(EOPNOTSUPP)) => Finding::ok(
            id,
            sev,
            N1_EVIDENCE,
            format!("{interface}: the driver reports no interrupt coalescing (EOPNOTSUPP)"),
        ),
        Err(e) => Finding::unknown(id, sev, N1_EVIDENCE, format!("cannot tell {what}"), e),
    }
}

const N2_EVIDENCE: &str = "Linux Documentation/networking/napi.rst; not measured here";

/// One sysfs NAPI setting: absent (an older kernel) is 0.
fn napi_setting(host: &Host, interface: &str, name: &str) -> Result<u64, ReadError> {
    let path = format!("/sys/class/net/{interface}/{name}");
    host.read_optional(&path)?.map_or(Ok(0), |t| {
        crate::host::first_line(&t)
            .parse()
            .map_err(|_| ReadError::Malformed {
                path,
                detail: "not a number",
            })
    })
}

/// N2: `interface` (and on Azure its VF) defers no interrupts when no
/// socket on it busy-polls.
///
/// Deferral is `napi_defer_hard_irqs` and `gro_flush_timeout` both above 0.
/// `busy_polls` is whether the caller's sockets on it busy-poll: `None`
/// when that is not known (`net.core.busy_read` unreadable in a pod), which
/// makes a deferring device unknown (one that defers nothing is ok either
/// way).
#[must_use]
pub fn n2_deferred_irqs(host: &Host, interface: &str, busy_polls: Option<bool>) -> Vec<Finding> {
    let id = "N2";
    let sev = Severity::Warn;
    let what = format!("whether {interface} defers its interrupts");
    if let Err(f) = driver_of(host, interface, id, N2_EVIDENCE, &what) {
        return vec![f];
    }
    if busy_polls == Some(true) {
        return vec![Finding::ok(
            id,
            sev,
            N2_EVIDENCE,
            format!("{interface}'s sockets busy-poll: deferred interrupts are how that is set up"),
        )];
    }
    let mut targets = vec![interface.to_owned()];
    match lower_interfaces(host, interface) {
        Ok(l) => targets.extend(l),
        Err(e) => {
            return vec![Finding::unknown(
                id,
                sev,
                N2_EVIDENCE,
                format!("cannot tell {what}"),
                e,
            )];
        }
    }
    let graviton = Platform::detect(host).is_graviton();
    let mut out = Vec::new();
    for t in &targets {
        let read = napi_setting(host, t, "napi_defer_hard_irqs")
            .and_then(|n| napi_setting(host, t, "gro_flush_timeout").map(|ns| (n, ns)));
        let (defer, timeout) = match read {
            Ok(v) => v,
            Err(e) => {
                out.push(Finding::unknown(
                    id,
                    sev,
                    N2_EVIDENCE,
                    format!("cannot tell whether {t} defers its interrupts"),
                    e,
                ));
                continue;
            }
        };
        if defer == 0 || timeout == 0 {
            continue;
        }
        if busy_polls.is_none() {
            out.push(Finding::unknown(
                id,
                sev,
                N2_EVIDENCE,
                format!(
                    "cannot tell whether {t}'s deferred interrupts (napi_defer_hard_irqs {defer}, \
                     gro_flush_timeout {timeout} ns) matter"
                ),
                "whether its sockets busy-poll is not known",
            ));
            continue;
        }
        let wait = if timeout % 1000 == 0 {
            format!("{} µs", timeout / 1000)
        } else {
            format!("{timeout} ns")
        };
        let alternative = if graviton {
            " (on Graviton, busy polling is not suggested: no archived run supports it there)"
        } else {
            ", or turn busy polling on"
        };
        out.push(Finding::found(
            id,
            sev,
            N2_EVIDENCE,
            format!(
                "{t}: interrupts are deferred (napi_defer_hard_irqs {defer}, gro_flush_timeout \
                 {timeout} ns) but no socket on it busy-polls: packets wait for the {wait} timer. \
                 Fix: `echo 0 > /sys/class/net/{t}/napi_defer_hard_irqs; echo 0 > \
                 /sys/class/net/{t}/gro_flush_timeout`{alternative}"
            ),
        ));
    }
    if out.is_empty() {
        out.push(Finding::ok(
            id,
            sev,
            N2_EVIDENCE,
            format!("{}: no deferred interrupts", targets.join(", ")),
        ));
    }
    out
}

const N3_EVIDENCE: &str = "Azure's accelerated networking documentation; not measured here";

/// N3: a `hv_netvsc` interface (Hyper-V's synthetic NIC) has an
/// accelerated-networking VF (`lower_*`) that is up. Other drivers are not
/// checked.
#[must_use]
pub fn n3_azure_vf(host: &Host, interface: &str) -> Finding {
    let id = "N3";
    let sev = Severity::Warn;
    let what = format!("whether {interface} has an accelerated-networking VF");
    let driver = match driver_of(host, interface, id, N3_EVIDENCE, &what) {
        Ok(d) => d,
        Err(f) => return f,
    };
    if driver != "hv_netvsc" {
        return Finding::ok(
            id,
            sev,
            N3_EVIDENCE,
            format!(
                "{interface}'s driver is {driver}: N3 is for hv_netvsc (Hyper-V's synthetic NIC)"
            ),
        );
    }
    let lowers = match lower_interfaces(host, interface) {
        Ok(l) => l,
        Err(e) => return Finding::unknown(id, sev, N3_EVIDENCE, format!("cannot tell {what}"), e),
    };
    let mut states = Vec::new();
    let mut unreadable = None;
    for vf in &lowers {
        match host.read_line(&format!("/sys/class/net/{vf}/operstate")) {
            Ok(s) if s == "up" => {
                return Finding::ok(id, sev, N3_EVIDENCE, format!("{interface}'s VF {vf} is up"));
            }
            Ok(s) => states.push(format!("{vf} is {s}")),
            Err(e) => unreadable = Some(e),
        }
    }
    if let Some(e) = unreadable {
        return Finding::unknown(id, sev, N3_EVIDENCE, format!("cannot tell {what}"), e);
    }
    let detail = if states.is_empty() {
        "no accelerated-networking VF".to_owned()
    } else {
        format!("no accelerated-networking VF up ({})", states.join(", "))
    };
    Finding::found(
        id,
        sev,
        N3_EVIDENCE,
        format!(
            "{interface} has {detail}: its traffic takes the synthetic VMBus path. Fix: enable \
             SR-IOV / accelerated networking on the virtual machine through the provider's \
             console or API, with the VM stopped"
        ),
    )
}

const N4_EVIDENCE: &str = "ethtool(8) (-G rx); not measured with archived data";

/// N4: the kernel RX ring of `interface` (on Azure its VF) holds at least
/// min(4096, its maximum) entries. For the media driver's socket transport
/// with busy polling.
#[must_use]
pub fn n4_rx_ring<E: Ethtool>(
    host: &Host,
    interface: &str,
    cache: &mut EthtoolCache<E>,
) -> Finding {
    let id = "N4";
    let sev = Severity::Warn;
    let what = format!("{interface}'s RX ring");
    let driver = match driver_of(host, interface, id, N4_EVIDENCE, &what) {
        Ok(d) => d,
        Err(f) => return f,
    };
    let (target, via) = if driver == "hv_netvsc" {
        match lower_interfaces(host, interface) {
            Ok(l) => match l.into_iter().next() {
                Some(vf) => (vf, format!(" ({interface}'s VF)")),
                None => {
                    return Finding::unknown(
                        id,
                        sev,
                        N4_EVIDENCE,
                        format!("cannot tell {what}"),
                        format!(
                            "{interface} has no VF: the synthetic path's ring is not the NIC's"
                        ),
                    );
                }
            },
            Err(e) => {
                return Finding::unknown(id, sev, N4_EVIDENCE, format!("cannot tell {what}"), e);
            }
        }
    } else {
        (interface.to_owned(), String::new())
    };
    let ena = interface_device(host, &target)
        .ok()
        .flatten()
        .and_then(|d| d.driver)
        .is_some_and(|d| d == "ena");
    match cache.rings(host, &target) {
        Ok(Rings {
            rx: Some(rx),
            rx_max: Some(max),
        }) => {
            let want = max.min(4096);
            if rx >= want {
                return Finding::ok(
                    id,
                    sev,
                    N4_EVIDENCE,
                    format!("{target}{via}: RX ring {rx} of at most {max}"),
                );
            }
            let reset = if ena {
                " (on ENA this resets the interface: re-pin its IRQs and turn adaptive-rx off again)"
            } else {
                ""
            };
            Finding::found(
                id,
                sev,
                N4_EVIDENCE,
                format!(
                    "{target}{via}: RX ring {rx} of at most {max}: a burst larger than the ring is \
                     dropped at the NIC, and an Aeron receiver asks for it again with a NAK (not \
                     measured here). Fix: `ethtool \
                     -G {target} rx {want}`{reset}"
                ),
            )
        }
        Ok(_) => Finding::unknown(
            id,
            sev,
            N4_EVIDENCE,
            format!("cannot tell {what}"),
            format!("{target}'s driver does not report its RX ring and maximum"),
        ),
        Err(e) => Finding::unknown(id, sev, N4_EVIDENCE, format!("cannot tell {what}"), e),
    }
}

const N5_EVIDENCE: &str = "aws-graviton-getting-started perfrunbook (interrupts need their own \
     core when moderation is off); Linux drivers/net/ethernet/amazon/ena/ena_netdev.c \
     (ena_up enables adaptive moderation); not measured here";

/// N5: with adaptive RX moderation off, `interface`'s interrupts do not
/// fire on a busy-spinning (receiver) CPU.
///
/// With moderation off every packet interrupts immediately: on the
/// receiver's own core that pauses the busy-polling loop for each one (not
/// measured here). N1 turns moderation off for latency; N5 keeps that
/// setting safe by requiring a spare IRQ core. Severity is higher on
/// Graviton, where a spare IRQ core was the recommended placement. Other
/// drivers are not checked (N1 covers ENA's moderation).
#[must_use]
#[allow(clippy::too_many_lines)] // one path per coalescing and placement outcome
pub fn n5_irq_headroom<E: Ethtool>(
    host: &Host,
    interface: &str,
    cache: &mut EthtoolCache<E>,
    cpus: &HotSet,
) -> Finding {
    let id = "N5";
    let sev = if Platform::detect(host).is_graviton() {
        Severity::Warn
    } else {
        Severity::Info
    };
    let what = format!("whether {interface}'s interrupts are off the hot CPUs");
    let driver = match driver_of(host, interface, id, N5_EVIDENCE, &what) {
        Ok(d) => d,
        Err(f) => return f,
    };
    if driver != "ena" {
        return Finding::ok(
            id,
            sev,
            N5_EVIDENCE,
            format!("{interface}'s driver is {driver}: N5 is for AWS's ENA"),
        );
    }
    match cache.coalesce(host, interface) {
        Ok(Coalesce {
            use_adaptive_rx: Some(true),
            ..
        }) => Finding::ok(
            id,
            sev,
            N5_EVIDENCE,
            format!(
                "{interface}: adaptive RX is on: N1 warns to turn it off; with moderation the \
                 interrupt delay is batched, so N5 does not fire"
            ),
        ),
        Ok(Coalesce {
            use_adaptive_rx: Some(false),
            ..
        }) => {
            let spinning = cpus.spinning();
            if spinning.is_empty() {
                return Finding::ok(
                    id,
                    sev,
                    N5_EVIDENCE,
                    format!("{interface}: adaptive RX is off, no busy-spinning CPU to check"),
                );
            }
            let irqs = match nic_irqs(host, &Nic::Interface(interface.to_owned())) {
                Ok(v) => v,
                Err(e) => {
                    return Finding::unknown(
                        id,
                        sev,
                        N5_EVIDENCE,
                        format!("cannot tell where {interface}'s interrupts may fire"),
                        e,
                    );
                }
            };
            if irqs.is_empty() {
                return Finding::ok(
                    id,
                    sev,
                    N5_EVIDENCE,
                    format!("{interface}: adaptive RX is off, no interrupts to place"),
                );
            }
            let mut hits = Vec::new();
            for irq in &irqs {
                let affinity =
                    match host.read_cpu_list(&format!("/proc/irq/{}/smp_affinity_list", irq.irq)) {
                        Ok(a) => a,
                        Err(e) => {
                            return Finding::unknown(
                                id,
                                sev,
                                N5_EVIDENCE,
                                format!("cannot tell where {} may fire", irq.label()),
                                e,
                            );
                        }
                    };
                let on = affinity.intersection(&spinning);
                if !on.is_empty() {
                    hits.push(format!("{} on {}", irq.label(), cpus.describe_all(&on)));
                }
            }
            if hits.is_empty() {
                return Finding::ok(
                    id,
                    sev,
                    N5_EVIDENCE,
                    format!(
                        "{interface}: adaptive RX is off and its interrupts are off the hot \
                         CPUs"
                    ),
                );
            }
            Finding::found(
                id,
                sev,
                N5_EVIDENCE,
                format!(
                    "{interface}: adaptive RX is off but {} — with moderation off each interrupt \
                     runs immediately, and on the receiver's own core it pauses the busy-polling \
                     loop for every packet (not measured here). Fix (node, root): pin the \
                     interrupts to a spare core (`echo <cpu> > /proc/irq/<n>/smp_affinity_list`, \
                     a CPU no app uses; re-pin after every ENA reset when carrier_changes \
                     moves), or re-enable moderation (`ethtool -C {interface} adaptive-rx on`). \
                     On Kubernetes both are node settings (a privileged DaemonSet that re-pins \
                     to a CPU outside every pod's exclusive CPUs, such as the kubelet's \
                     reservedSystemCPUs), never the pod's",
                    hits.join("; ")
                ),
            )
        }
        Ok(Coalesce {
            use_adaptive_rx: None,
            ..
        }) => Finding::ok(
            id,
            sev,
            N5_EVIDENCE,
            format!(
                "{interface}: the driver does not offer adaptive RX: interrupt placement is \
                 N2/T2's concern"
            ),
        ),
        Err(EthtoolError::Kernel(EOPNOTSUPP)) => Finding::ok(
            id,
            sev,
            N5_EVIDENCE,
            format!(
                "{interface}: the driver reports no interrupt coalescing (EOPNOTSUPP): \
                 interrupt placement is N2/T2's concern"
            ),
        ),
        Err(e) => Finding::unknown(id, sev, N5_EVIDENCE, format!("cannot tell {what}"), e),
    }
}