rdmatop 0.1.30

A real-time TUI monitor for RDMA network interfaces
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
use crate::netlink::*;
use crate::rdma::*;
use std::io;

#[derive(Clone, Debug)]
/// A single hardware counter name/value pair.
pub struct HwCounter {
    pub name: String,
    pub value: u64,
}

#[derive(Clone, Debug)]
/// Per-port statistics snapshot with all hw counters.
pub struct PortStat {
    pub dev_name: String,
    pub port: u32,
    /// Port line rate in Gbps (from sysfs `rate`), None if unavailable.
    pub link_gbps: Option<f64>,
    /// Logical port state ("ACTIVE", "DOWN", "INIT", ...), None if unavailable.
    pub state: Option<String>,
    pub counters: Vec<HwCounter>,
}

impl PortStat {
    pub fn new(dev_name: String, port: u32) -> Self {
        Self {
            dev_name,
            port,
            link_gbps: None,
            state: None,
            counters: Vec::new(),
        }
    }

    /// Look up a counter value by name.
    pub fn counter_value(&self, name: &str) -> Option<u64> {
        self.counters
            .iter()
            .find(|c| c.name == name)
            .map(|c| c.value)
    }
}

#[cfg(test)]
pub(crate) fn port_stat(dev: &str, port: u32, counters: &[(&str, u64)]) -> PortStat {
    let mut stat = PortStat::new(dev.to_string(), port);
    for (name, value) in counters {
        stat.counters.push(HwCounter {
            name: name.to_string(),
            value: *value,
        });
    }
    stat
}

pub const THROUGHPUT_COUNTERS: &[&str] =
    &["tx_bytes", "rx_bytes", "tx_pkts", "rx_pkts", "rx_drops"];

/// All counter names that can be added as extra columns.
pub const EXTRA_COUNTERS: &[&str] = &[
    "send_bytes",
    "send_wrs",
    "recv_bytes",
    "recv_wrs",
    "rdma_write_bytes",
    "rdma_write_wrs",
    "rdma_write_wr_err",
    "rdma_write_recv_bytes",
    "rdma_read_bytes",
    "rdma_read_wrs",
    "rdma_read_wr_err",
    "rdma_read_resp_bytes",
    "retrans_bytes",
    "retrans_pkts",
    "retrans_timeout_events",
    "unresponsive_remote_events",
    "impaired_remote_conn_events",
];

struct RdmaDev {
    idx: u32,
    name: String,
    num_ports: u32,
}

fn parse_dev(nlmsg: &NlMsg) -> Option<RdmaDev> {
    let mut dev = RdmaDev {
        idx: 0,
        name: String::new(),
        num_ports: 1,
    };
    for nla in nlmsg.attrs() {
        match nla.attr_type {
            RDMA_NLDEV_ATTR_DEV_INDEX => dev.idx = nla.u32(),
            RDMA_NLDEV_ATTR_DEV_NAME => dev.name = nla.str().to_string(),
            RDMA_NLDEV_ATTR_PORT_INDEX => dev.num_ports = nla.u32(),
            _ => {}
        }
    }
    (!dev.name.is_empty()).then_some(dev)
}

fn parse_hw_counter(entry: &Nla) -> HwCounter {
    let mut name = String::new();
    let mut value = 0u64;
    for f in entry.nested() {
        match f.attr_type {
            RDMA_NLDEV_ATTR_STAT_HWCOUNTER_ENTRY_NAME => name = f.str().to_string(),
            RDMA_NLDEV_ATTR_STAT_HWCOUNTER_ENTRY_VALUE => value = f.u64(),
            _ => {}
        }
    }
    HwCounter { name, value }
}

fn parse_port_counters(nlmsg: &NlMsg) -> Option<PortStat> {
    let mut stat = PortStat::new(String::new(), 0);
    for nla in nlmsg.attrs() {
        match nla.attr_type {
            RDMA_NLDEV_ATTR_DEV_NAME => stat.dev_name = nla.str().to_string(),
            RDMA_NLDEV_ATTR_PORT_INDEX => stat.port = nla.u32(),
            RDMA_NLDEV_ATTR_STAT_HWCOUNTERS => {
                stat.counters = nla
                    .nested()
                    .filter(|e| e.attr_type == RDMA_NLDEV_ATTR_STAT_HWCOUNTER_ENTRY)
                    .map(|e| parse_hw_counter(&e))
                    .collect();
            }
            _ => {}
        }
    }
    if stat.dev_name.is_empty() {
        return None;
    }
    Some(stat)
}

fn parse_port_stat(nlmsg: &NlMsg) -> Option<PortStat> {
    let mut stat = parse_port_counters(nlmsg)?;
    fill_missing_from_sysfs(&mut stat);
    stat.link_gbps = read_port_link_gbps(&stat.dev_name, stat.port);
    Some(stat)
}

/// A fixed port's counter reader for recording without repeated discovery.
pub struct CounterReader {
    sock: NlSocket,
    dev_name: String,
    dev_idx: u32,
    port: u32,
    seq: u32,
}

impl CounterReader {
    pub fn open(dev_name: &str, port: u32) -> io::Result<Self> {
        let sock = NlSocket::open(NETLINK_RDMA)?;
        let dev = enumerate_devices(&sock)?
            .into_iter()
            .find(|dev| dev.name == dev_name && (1..=dev.num_ports).contains(&port))
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::NotFound,
                    format!("RDMA port {dev_name}/{port}"),
                )
            })?;
        Ok(Self {
            sock,
            dev_name: dev.name,
            dev_idx: dev.idx,
            port,
            seq: 2,
        })
    }

    pub fn read(&mut self) -> io::Result<PortStat> {
        self.seq = self.seq.wrapping_add(1);
        let msg = port_request(RDMA_NLDEV_CMD_STAT_GET, self.dev_idx, self.port, self.seq);
        let mut stat = None;
        for buf in self.sock.request(msg)? {
            for response in NlMsgIter::new(&buf) {
                if response.is_error() {
                    counter_response_error(response.payload)?;
                } else if !response.is_done() {
                    stat = parse_port_counters(&response).or(stat);
                }
            }
        }
        finish_counter_sample(stat, &self.dev_name, self.port, fill_missing_from_sysfs)
    }
}

fn counter_response_error(payload: &[u8]) -> io::Result<()> {
    let code = payload
        .get(..4)
        .map(|bytes| i32::from_ne_bytes(bytes.try_into().unwrap()))
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "truncated netlink error"))?;
    // Some providers expose port counters only in sysfs.
    if code == 0 || code == -libc::EOPNOTSUPP {
        Ok(())
    } else {
        Err(io::Error::from_raw_os_error(code.saturating_neg()))
    }
}

fn finish_counter_sample(
    stat: Option<PortStat>,
    dev_name: &str,
    port: u32,
    fallback: impl FnOnce(&mut PortStat),
) -> io::Result<PortStat> {
    let mut stat = stat.unwrap_or_else(|| PortStat::new(dev_name.to_string(), port));
    // EFA exposes these directly. Providers such as mlx5 need sysfs fallback.
    if stat.counter_value("tx_bytes").is_none() || stat.counter_value("rx_bytes").is_none() {
        fallback(&mut stat);
    }
    if stat.counters.is_empty() {
        return Err(io::Error::other(format!(
            "no counters for {dev_name}/{port}"
        )));
    }
    Ok(stat)
}

/// Map the IB port state enum (ib_verbs.h `ib_port_state`) to its name.
fn port_state_name(v: u8) -> Option<String> {
    let s = match v {
        1 => "DOWN",
        2 => "INIT",
        3 => "ARMED",
        4 => "ACTIVE",
        5 => "ACTIVE_DEFER",
        _ => return None,
    };
    Some(s.to_string())
}

/// Parse the logical port state from sysfs, e.g. "4: ACTIVE" -> "ACTIVE".
fn read_port_state_sysfs(dev_name: &str, port: u32) -> Option<String> {
    let path = format!("/sys/class/infiniband/{}/ports/{}/state", dev_name, port);
    let raw = std::fs::read_to_string(path).ok()?;
    Some(raw.trim().rsplit(": ").next()?.to_string())
}

fn parse_port_state(nlmsg: &NlMsg) -> Option<String> {
    nlmsg
        .attrs()
        .find(|nla| nla.attr_type == RDMA_NLDEV_ATTR_PORT_STATE)
        .and_then(|nla| port_state_name(nla.u8()))
}

fn port_request(cmd: u32, dev_idx: u32, port: u32, seq: u32) -> Vec<u8> {
    NlMsgBuilder::new(
        rdma_nl_get_type(RDMA_NL_NLDEV, cmd),
        NLM_F_REQUEST | NLM_F_ACK,
        seq,
    )
    .put_u32(RDMA_NLDEV_ATTR_DEV_INDEX, dev_idx)
    .put_u32(RDMA_NLDEV_ATTR_PORT_INDEX, port)
    .build()
}

/// Port state from RDMA netlink, falling back to sysfs.
fn query_port_state(sock: &NlSocket, dev: &RdmaDev, port: u32, seq: u32) -> Option<String> {
    let msg = port_request(RDMA_NLDEV_CMD_PORT_GET, dev.idx, port, seq);
    collect_responses(sock, msg, parse_port_state)
        .ok()
        .and_then(|v| v.into_iter().next())
        .or_else(|| read_port_state_sysfs(&dev.name, port))
}

/// Parse the port line rate from sysfs, e.g. "400 Gb/sec (4X NDR)" -> 400.0.
/// Read fresh every poll on purpose: a down port reports an SDR placeholder
/// and links can retrain at a different speed, so caching would freeze a
/// wrong utilization denominator for the process lifetime.
fn read_port_link_gbps(dev_name: &str, port: u32) -> Option<f64> {
    let path = format!("/sys/class/infiniband/{}/ports/{}/rate", dev_name, port);
    let raw = std::fs::read_to_string(path).ok()?;
    raw.split_whitespace().next()?.parse::<f64>().ok()
}

// Names whose values in /sys/.../counters/ are in 4-byte words per IB spec.
const SYSFS_DATA_COUNTERS: &[&str] = &["port_xmit_data", "port_rcv_data"];

// rdmatop-canonical names synthesized from the standard sysfs counters so the
// throughput row works for providers that don't expose tx_bytes/rx_bytes as
// hw_counters (e.g., Mellanox mlx5).
const SYSFS_SYNTH: &[(&str, &str, u64)] = &[
    ("tx_bytes", "port_xmit_data", 4),
    ("rx_bytes", "port_rcv_data", 4),
    ("tx_pkts", "port_xmit_packets", 1),
    ("rx_pkts", "port_rcv_packets", 1),
];

// Alias mapping for erdma which exposes hw counters under names like
// hw_tx_bytes_cnt instead of the canonical tx_bytes. Both naming forms exist:
// the original 2023 patch / Alibaba Cloud kernel use the hw_ prefix, mainline
// erdma_descs dropped it (tx_bytes_cnt). Match either.
// hw_ form:  https://www.spinics.net/lists/linux-rdma/msg121550.html
// mainline:  https://github.com/torvalds/linux/blob/v6.12/drivers/infiniband/hw/erdma/erdma_verbs.c#L1770 (erdma_descs)
const HW_COUNTER_ALIASES: &[(&str, &str)] = &[
    ("tx_bytes", "hw_tx_bytes_cnt"),
    ("rx_bytes", "hw_rx_bytes_cnt"),
    ("tx_pkts", "hw_tx_packets_cnt"),
    ("rx_pkts", "hw_rx_packets_cnt"),
    ("rx_drops", "hw_rx_disable_drop_cnt"),
    ("tx_bytes", "tx_bytes_cnt"),
    ("rx_bytes", "rx_bytes_cnt"),
    ("tx_pkts", "tx_packets_cnt"),
    ("rx_pkts", "rx_packets_cnt"),
    ("rx_drops", "rx_disable_drop_cnt"),
];

fn fill_missing_from_sysfs(stat: &mut PortStat) {
    let dir = format!(
        "/sys/class/infiniband/{}/ports/{}/counters",
        stat.dev_name, stat.port
    );

    // Ingest every standard IB port counter that the driver exposes via sysfs
    // (link_downed, port_xmit_discards, port_xmit_wait, port_rcv_errors, ...).
    // These are not surfaced by RDMA netlink, so iproute2's `rdma statistic`
    // misses them too.
    if let Ok(entries) = std::fs::read_dir(&dir) {
        for entry in entries.flatten() {
            let Some(name) = entry.file_name().to_str().map(String::from) else {
                continue;
            };
            if stat.counters.iter().any(|c| c.name == name) {
                continue;
            }
            let Ok(raw) = std::fs::read_to_string(entry.path()) else {
                continue;
            };
            let Ok(v) = raw.trim().parse::<u64>() else {
                continue;
            };
            let value = if SYSFS_DATA_COUNTERS.contains(&name.as_str()) {
                v.saturating_mul(4)
            } else {
                v
            };
            stat.counters.push(HwCounter { name, value });
        }
    }

    // Synthesize canonical {tx,rx}_{bytes,pkts} from the standard names so the
    // top-level throughput row lights up even when the driver doesn't publish
    // them under those names.
    for (synth_name, src_name, mult) in SYSFS_SYNTH {
        if stat.counters.iter().any(|c| c.name == *synth_name) {
            continue;
        }
        let Some(src) = stat.counters.iter().find(|c| c.name == *src_name) else {
            continue;
        };
        // src value is already in bytes (we converted port_*_data above), so
        // for bytes counters mult is 1 in effect. Keep the mult only for
        // names whose source hasn't been pre-converted.
        let base = if SYSFS_DATA_COUNTERS.contains(src_name) {
            src.value
        } else {
            src.value.saturating_mul(*mult)
        };
        stat.counters.push(HwCounter {
            name: (*synth_name).to_string(),
            value: base,
        });
    }

    // Alias hw_counter names for providers like erdma that use
    // hw_tx_bytes_cnt instead of the canonical tx_bytes.
    for (canonical, alias) in HW_COUNTER_ALIASES {
        if stat.counters.iter().any(|c| c.name == *canonical) {
            continue;
        }
        if let Some(src) = stat.counters.iter().find(|c| c.name == *alias) {
            let value = src.value;
            stat.counters.push(HwCounter {
                name: canonical.to_string(),
                value,
            });
        }
    }
}

fn enumerate_devices(sock: &NlSocket) -> io::Result<Vec<RdmaDev>> {
    let msg = NlMsgBuilder::new(
        rdma_nl_get_type(RDMA_NL_NLDEV, RDMA_NLDEV_CMD_GET),
        NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP,
        1,
    )
    .build();
    collect_responses(sock, msg, parse_dev)
}

fn query_port_stats(
    sock: &NlSocket,
    dev_idx: u32,
    port: u32,
    seq: u32,
) -> io::Result<Vec<PortStat>> {
    let msg = port_request(RDMA_NLDEV_CMD_STAT_GET, dev_idx, port, seq);
    collect_responses(sock, msg, parse_port_stat)
}

/// Query all RDMA device/port hw counters via netlink.
pub fn read_all_stats() -> io::Result<Vec<PortStat>> {
    let sock = NlSocket::open(NETLINK_RDMA)?;
    let devs = enumerate_devices(&sock)?;

    let sock = NlSocket::open(NETLINK_RDMA)?;
    let mut all = Vec::new();
    let mut seq = 100u32;
    for dev in &devs {
        for port in 1..=dev.num_ports {
            let state = query_port_state(&sock, dev, port, seq);
            seq += 1;
            for mut stat in query_port_stats(&sock, dev.idx, port, seq)? {
                stat.state = state.clone();
                all.push(stat);
            }
            seq += 1;
        }
    }
    Ok(all)
}

#[derive(Clone, Debug)]
/// Queue pair info with device, PID, and process name.
pub struct QpInfo {
    pub dev_name: String,
    pub lqpn: u32,
    pub qp_type: u8,
    pub state: u8,
    pub pid: u32,
    pub comm: String,
}

// This matches iproute2's res_qp_idx_parse_cb which reads from tb[] directly.

fn parse_qp_response(nlmsg: &NlMsg, dev_name: &str) -> Vec<QpInfo> {
    let mut name = dev_name.to_string();
    let mut qps = Vec::new();
    for nla in nlmsg.attrs() {
        match nla.attr_type {
            RDMA_NLDEV_ATTR_DEV_NAME => name = nla.str().to_string(),
            RDMA_NLDEV_ATTR_RES_QP => {
                for entry in nla.nested() {
                    if entry.attr_type == RDMA_NLDEV_ATTR_RES_QP_ENTRY {
                        if let Some(qp) = parse_single_qp(&entry, &name) {
                            qps.push(qp);
                        }
                    }
                }
            }
            _ => {}
        }
    }
    qps
}

fn parse_single_qp(nla: &Nla, dev_name: &str) -> Option<QpInfo> {
    let mut qp = QpInfo {
        dev_name: dev_name.to_string(),
        lqpn: 0,
        qp_type: 0,
        state: 0,
        pid: 0,
        comm: String::new(),
    };
    for attr in nla.nested() {
        match attr.attr_type {
            RDMA_NLDEV_ATTR_RES_LQPN => qp.lqpn = attr.u32(),
            RDMA_NLDEV_ATTR_RES_TYPE if !attr.data.is_empty() => {
                qp.qp_type = attr.data[0];
            }
            RDMA_NLDEV_ATTR_RES_STATE if !attr.data.is_empty() => {
                qp.state = attr.data[0];
            }
            RDMA_NLDEV_ATTR_RES_PID => {
                qp.pid = attr.u32();
                qp.comm = read_proc_comm(qp.pid);
            }
            RDMA_NLDEV_ATTR_RES_KERN_NAME => qp.comm = attr.str().to_string(),
            _ => {}
        }
    }
    (qp.pid > 0).then_some(qp)
}

fn read_proc_comm(pid: u32) -> String {
    std::fs::read_to_string(format!("/proc/{}/comm", pid))
        .unwrap_or_default()
        .trim()
        .to_string()
}

/// Query all RDMA QPs via netlink (like `rdma resource show qp`).
/// Query all RDMA QPs via netlink, returning PID and device mappings.
pub fn read_all_qps() -> io::Result<Vec<QpInfo>> {
    let sock = NlSocket::open(NETLINK_RDMA)?;
    let devs = enumerate_devices(&sock)?;
    drop(sock);

    let mut all = Vec::new();
    let mut seq = 200u32;
    for dev in &devs {
        let sock = NlSocket::open(NETLINK_RDMA)?;
        let msg = NlMsgBuilder::new(
            rdma_nl_get_type(RDMA_NL_NLDEV, RDMA_NLDEV_CMD_RES_QP_GET),
            NLM_F_REQUEST | NLM_F_ACK | NLM_F_DUMP,
            seq,
        )
        .put_u32(RDMA_NLDEV_ATTR_DEV_INDEX, dev.idx)
        .build();

        if let Ok(bufs) = sock.request(msg) {
            for buf in bufs {
                for nlmsg in NlMsgIter::new(&buf) {
                    if nlmsg.is_done() || nlmsg.is_error() {
                        continue;
                    }
                    all.extend(parse_qp_response(&nlmsg, &dev.name));
                }
            }
        }
        seq += 1;
    }
    Ok(all)
}

/// Aggregate QPs by (pid, comm, dev_name), enriched with /proc data.
#[derive(Clone, Debug)]
/// Process info enriched with /proc data for htop-style display.
pub struct ProcessRdmaInfo {
    pub pid: u32,
    pub dev_name: String,
    pub qp_count: usize,
    pub user: String,
    pub nice: i32,
    pub state: char,
    pub virt_kb: u64,
    pub res_kb: u64,
    pub shr_kb: u64,
    pub mem_pct: f32,
    pub threads: u32,
    pub cmdline: String,
}

/// Raw fields from /proc/<pid>/stat
struct ProcStat {
    state: char,
    nice: i32,
    vsize: u64,
    rss_pages: u64,
    num_threads: u32,
}

fn read_proc_stat(pid: u32) -> Option<ProcStat> {
    let data = std::fs::read_to_string(format!("/proc/{}/stat", pid)).ok()?;
    // Fields after last ')' to avoid comm with spaces
    let rest = data.rsplit_once(')')?.1;
    let fields: Vec<&str> = rest.split_whitespace().collect();
    // fields[0]=state, [1]=ppid, ..., [11]=utime, [12]=stime, ..., [16]=nice, ..., [17]=num_threads, ..., [20]=vsize, [21]=rss
    if fields.len() < 22 {
        return None;
    }
    Some(ProcStat {
        state: fields[0].chars().next().unwrap_or('?'),
        nice: fields[16].parse().unwrap_or(0),
        num_threads: fields[17].parse().unwrap_or(1),
        vsize: fields[20].parse().unwrap_or(0),
        rss_pages: fields[21].parse().unwrap_or(0),
    })
}

fn read_proc_shr_kb(pid: u32) -> u64 {
    // /proc/<pid>/statm: size resident shared ...
    std::fs::read_to_string(format!("/proc/{}/statm", pid))
        .ok()
        .and_then(|s| s.split_whitespace().nth(2)?.parse::<u64>().ok())
        .unwrap_or(0)
        * 4 // pages to KB
}

fn read_proc_uid(pid: u32) -> u32 {
    std::fs::read_to_string(format!("/proc/{}/status", pid))
        .ok()
        .and_then(|s| {
            s.lines()
                .find(|l| l.starts_with("Uid:"))
                .and_then(|l| l.split_whitespace().nth(1)?.parse().ok())
        })
        .unwrap_or(0)
}

fn uid_to_name(uid: u32) -> String {
    std::fs::read_to_string("/etc/passwd")
        .ok()
        .and_then(|s| {
            s.lines()
                .find(|l| l.split(':').nth(2) == Some(&uid.to_string()))
                .map(|l| l.split(':').next().unwrap_or("?").to_string())
        })
        .unwrap_or_else(|| uid.to_string())
}

fn read_proc_cmdline(pid: u32) -> String {
    std::fs::read_to_string(format!("/proc/{}/cmdline", pid))
        .unwrap_or_default()
        .replace('\0', " ")
        .trim()
        .to_string()
}

fn total_memory_kb() -> u64 {
    std::fs::read_to_string("/proc/meminfo")
        .ok()
        .and_then(|s| {
            s.lines()
                .find(|l| l.starts_with("MemTotal:"))
                .and_then(|l| l.split_whitespace().nth(1)?.parse().ok())
        })
        .unwrap_or(1)
}

fn proc_mem_stats(ps: &Option<ProcStat>) -> (char, i32, u64, u64, u32) {
    match ps {
        Some(s) => (
            s.state,
            s.nice,
            s.vsize / 1024,
            s.rss_pages * 4,
            s.num_threads,
        ),
        None => ('?', 0, 0, 0, 0),
    }
}

fn mem_percent(res_kb: u64) -> f32 {
    let total = total_memory_kb();
    if total > 0 {
        (res_kb as f32 / total as f32) * 100.0
    } else {
        0.0
    }
}

fn resolve_user(uid: u32, ps: &Option<ProcStat>) -> String {
    if uid > 0 || ps.is_some() {
        uid_to_name(uid)
    } else {
        "?".into()
    }
}

fn resolve_cmdline(pid: u32, comm: &str) -> String {
    let cmdline = read_proc_cmdline(pid);
    if !cmdline.is_empty() {
        cmdline
    } else {
        comm.to_string()
    }
}

fn enrich_process(pid: u32, comm: &str, dev_name: &str, qp_count: usize) -> ProcessRdmaInfo {
    let ps = read_proc_stat(pid);
    let (state, nice, virt_kb, res_kb, threads) = proc_mem_stats(&ps);

    ProcessRdmaInfo {
        pid,
        dev_name: dev_name.to_string(),
        qp_count,
        user: resolve_user(read_proc_uid(pid), &ps),
        nice,
        state,
        virt_kb,
        res_kb,
        shr_kb: read_proc_shr_kb(pid),
        mem_pct: mem_percent(res_kb),
        threads,
        cmdline: resolve_cmdline(pid, comm),
    }
}

/// Aggregate QPs by (pid, device), enriched with /proc data.
pub fn aggregate_by_process(qps: &[QpInfo]) -> Vec<ProcessRdmaInfo> {
    use std::collections::HashMap;
    let mut counts: HashMap<(u32, String), (&QpInfo, usize)> = HashMap::new();
    for qp in qps {
        if qp.pid == 0 {
            continue;
        }
        let key = (qp.pid, qp.dev_name.clone());
        let entry = counts.entry(key).or_insert((qp, 0));
        entry.1 += 1;
    }
    let mut result: Vec<ProcessRdmaInfo> = counts
        .into_values()
        .map(|(qp, count)| enrich_process(qp.pid, &qp.comm, &qp.dev_name, count))
        .collect();
    result.sort_by(|a, b| b.qp_count.cmp(&a.qp_count).then(a.pid.cmp(&b.pid)));
    result
}

#[cfg(test)]
mod counter_recording_tests {
    use super::*;

    #[test]
    fn empty_netlink_response_can_use_sysfs_counters() {
        let stat = finish_counter_sample(None, "test0", 1, |stat| {
            assert_eq!(stat.dev_name, "test0");
            assert_eq!(stat.port, 1);
            stat.counters.push(HwCounter {
                name: "tx_bytes".into(),
                value: 42,
            });
        })
        .unwrap();
        assert_eq!(stat.counter_value("tx_bytes"), Some(42));
        assert!(finish_counter_sample(None, "test0", 1, |_| {}).is_err());
    }

    #[test]
    fn unsupported_stats_allow_fallback_but_permission_errors_surface() {
        assert!(counter_response_error(&(-libc::EOPNOTSUPP).to_ne_bytes()).is_ok());
        assert!(counter_response_error(&0_i32.to_ne_bytes()).is_ok());
        assert_eq!(
            counter_response_error(&(-libc::EACCES).to_ne_bytes())
                .unwrap_err()
                .kind(),
            io::ErrorKind::PermissionDenied
        );
        assert!(counter_response_error(&[]).is_err());
    }
}