-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgpu_pcie_validator.cu
More file actions
2063 lines (1794 loc) · 72.7 KB
/
gpu_pcie_validator.cu
File metadata and controls
2063 lines (1794 loc) · 72.7 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
/*
* =============================================================================
* GPU PCIe Validator
* =============================================================================
*
* Author : Joe McLaren (Human-AI Collaborative Engineering)
* Repository : https://github.com/parallelArchitect
* File : gpu_pcie_validator.cu
* Version : 4.1
*
* DESCRIPTION
* -----------
* Production-grade PCIe path validation and diagnostics for NVIDIA GPUs.
* Measures bandwidth, link latency, thermal response, power draw, PCIe replay
* errors, AER counters, GPU clock/P-state, persistence mode, ASPM policy,
* IOMMU state, and MPS/MRRS configuration. All values sourced from live
* hardware — no hardcoded defaults or synthetic estimates.
*
* Designed for universal use across all NVIDIA GPU generations (Kepler through
* Blackwell) and all PCIe generations (Gen1–Gen6). Suitable for field
* diagnostics, data center health checks, and automated CI integration.
*
* KEY FEATURES
* ------------
* - AER (Advanced Error Reporting) correctable/non-fatal/fatal delta counters
* - GPU clock snapshot pre/post load: SM, memory, graphics + P-state
* - PCIe MPS (Max Payload Size) and MRRS (Max Read Request Size) from sysfs
* - Persistence mode and ASPM policy from NVML/sysfs
* - IOMMU state detection from kernel sysfs
* - NUMA affinity validation (CPU NUMA node matches GPU NUMA node)
* - Dual latency measurement: bulk transfer (1 GiB) and link latency (64 KB)
* - Pinned and unpinned memory mode support
* - PCIe replay counter with integer delta
* - Multi-GPU: --all-devices sweeps all GPUs, JSON array output
* - Non-zero exit code on UNHEALTHY/DEGRADED (Kubernetes/Nagios/CI ready)
* - Structured JSON output with full derived assessment fields
* - CUDA event-based microsecond timing precision
* - Driver/NVML version captured in JSON
*
* MEASUREMENT SOURCES
* -------------------
* All values queried at runtime from hardware or kernel:
* - PCIe Gen/Width: nvmlDeviceGetMaxPcieLinkGeneration/Width
* - Bandwidth: cudaMemcpyAsync + CUDA event timing
* - Latency: CUDA events (bulk 1024 MiB + 64 KB transfers)
* - Replay counter: nvmlDeviceGetPcieReplayCounter
* - AER counters: /sys/bus/pci/devices/<bdf>/aer_dev_correctable etc.
* - Clocks/P-state: nvmlDeviceGetClockInfo + nvmlDeviceGetPerformanceState
* - Power/Temp: nvmlDeviceGetPowerUsage/Temperature
* - Persistence mode: nvmlDeviceGetPersistenceMode
* - MPS/MRRS: /sys/bus/pci/devices/<bdf>/max_payload_size etc.
* - ASPM policy: /sys/bus/pci/devices/<bdf>/power/control
* - IOMMU: /sys/kernel/iommu_groups/ + /proc/cmdline
* - NUMA node: /sys/bus/pci/devices/<bdf>/numa_node
* - NUMA CPU affinity: /sys/bus/pci/devices/<bdf>/local_cpulist
* - Scheduler: sched_getscheduler(0) + sched_getparam()
* - Topology: sysfs symlink walk from endpoint to root port
* - NVML version: nvmlSystemGetNVMLVersion
*
* BUILD
* -----
* nvcc -O3 -std=c++14 -lnvidia-ml -Xcompiler -pthread \
* gpu_pcie_validator.cu -o gpu_pcie_validator
*
* USAGE
* -----
* List available GPUs:
* ./gpu_pcie_validator --list-devices
*
* Run validation on device 0 with pinned memory:
* ./gpu_pcie_validator --device 0 --memory-mode pinned
*
* Run validation on all GPUs (sequential, JSON array output):
* ./gpu_pcie_validator --all-devices
*
* Full parameter example:
* ./gpu_pcie_validator --device 0 --memory-mode pinned \
* --window-ms 2000 --interval-ms 100 --size-mib 1024
*
* OPTIONS
* -------
* --list-devices List all GPUs (index, BDF, NUMA, PCIe link, name)
* --device N CUDA device index to validate (default: 0)
* --all-devices Validate all GPUs sequentially
* --memory-mode MODE pinned (default) or unpinned
* --window-ms MS NVML telemetry window in ms (default: 2000)
* --interval-ms MS NVML poll interval in ms (default: 100)
* --size-mib MiB Transfer buffer size in MiB (default: 1024)
*
* OUTPUT
* ------
* Single device:
* ./logs/runs/<timestamp>_GPU<N>/report.txt — human-readable
* ./logs/runs/<timestamp>_GPU<N>/report.json — machine-readable
*
* All devices (--all-devices):
* ./logs/runs/<timestamp>_ALL/report.txt — all GPUs human-readable
* ./logs/runs/<timestamp>_ALL/report.json — JSON array of all GPU objects
* ./logs/runs/<timestamp>_ALL/gpu<N>.json — per-GPU JSON
*
* EXIT CODES
* ----------
* 0 — All validated GPUs HEALTHY
* 1 — Runtime error (NVML/CUDA failure, invalid arguments)
* 2 — One or more GPUs DEGRADED or LINK_DEGRADED
*
* =============================================================================
*/
#include <cuda_runtime.h>
#include <nvml.h>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include <dirent.h>
#include <sched.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
// =============================================================================
// UTILITY FUNCTIONS
// Timestamp formatting, sysfs string/int readers, BDF normalization, path join.
// =============================================================================
static std::string NowStamp()
{
std::time_t t = std::time(nullptr);
std::tm tm{};
localtime_r(&t, &tm);
char buf[64];
std::snprintf(buf, sizeof(buf), "%04d%02d%02d_%02d%02d%02d",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
return std::string(buf);
}
static std::string NowISO8601()
{
std::time_t t = std::time(nullptr);
std::tm tm{};
gmtime_r(&t, &tm);
char buf[64];
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02dT%02d:%02d:%02dZ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec);
return std::string(buf);
}
static std::string NormalizeBDF(const std::string& s)
{
if (s.size() >= 12)
{
std::string tail = s.substr(s.size() - 12);
if (tail[4] == ':' && tail[7] == ':' && tail[10] == '.')
return tail;
}
return s;
}
static bool ExistsDir(const std::string& p)
{
struct stat st;
return (stat(p.c_str(), &st) == 0) && S_ISDIR(st.st_mode);
}
static std::string Join(const std::string& a, const std::string& b)
{
if (a.empty()) return b;
return (a.back() == '/') ? a + b : a + "/" + b;
}
static std::string ReadSysfsStr(const std::string& path)
{
std::ifstream f(path);
if (!f.good()) return "";
std::string s;
std::getline(f, s);
while (!s.empty() &&
(s.back() == '\n' || s.back() == '\r' || s.back() == ' '))
s.pop_back();
return s;
}
static int ReadSysfsInt(const std::string& path, int default_val = -1)
{
std::string s = ReadSysfsStr(path);
if (s.empty()) return default_val;
try { return std::stoi(s); }
catch (...) { return default_val; }
}
static std::string NVML_Err(nvmlReturn_t r)
{
return std::string(nvmlErrorString(r));
}
// =============================================================================
// SYSTEM ENVIRONMENT QUERIES
// Scheduler policy, NUMA node count, GPU NUMA node, OS name from /etc/os-release.
// =============================================================================
static std::string QuerySchedulerPolicy()
{
int policy = sched_getscheduler(0);
struct sched_param sp{};
sched_getparam(0, &sp);
std::ostringstream ss;
switch (policy)
{
case SCHED_OTHER: ss << "SCHED_OTHER"; break;
case SCHED_FIFO: ss << "SCHED_FIFO"; break;
case SCHED_RR: ss << "SCHED_RR"; break;
#ifdef SCHED_BATCH
case SCHED_BATCH: ss << "SCHED_BATCH"; break;
#endif
#ifdef SCHED_IDLE
case SCHED_IDLE: ss << "SCHED_IDLE"; break;
#endif
#ifdef SCHED_DEADLINE
case SCHED_DEADLINE: ss << "SCHED_DEADLINE"; break;
#endif
default: ss << "SCHED_UNKNOWN(" << policy << ")"; break;
}
ss << " (priority " << sp.sched_priority << ")";
return ss.str();
}
static int QueryNumaNodeCount()
{
DIR* d = opendir("/sys/devices/system/node");
if (!d) return 1;
int count = 0;
struct dirent* ent;
while ((ent = readdir(d)) != nullptr)
{
if (ent->d_type != DT_DIR) continue;
if (std::strncmp(ent->d_name, "node", 4) != 0) continue;
bool all_digit = true;
for (int i = 4; ent->d_name[i] != '\0'; i++)
if (!std::isdigit((unsigned char)ent->d_name[i]))
{ all_digit = false; break; }
if (all_digit && ent->d_name[4] != '\0') count++;
}
closedir(d);
return (count > 0) ? count : 1;
}
// On single-node systems kernel reports -1. Normalize to 0.
static int QueryGpuNumaNode(const std::string& bdf, int numa_node_count)
{
int raw = ReadSysfsInt("/sys/bus/pci/devices/" + bdf + "/numa_node", -1);
if (raw == -1 && numa_node_count == 1) return 0;
return raw;
}
static std::string QueryOSName(const struct utsname& un)
{
std::ifstream f("/etc/os-release");
if (f.good())
{
std::string line;
while (std::getline(f, line))
{
if (line.rfind("PRETTY_NAME=", 0) != 0) continue;
std::string val = line.substr(12);
if (val.size() >= 2 && val.front() == '"' && val.back() == '"')
val = val.substr(1, val.size() - 2);
return val;
}
}
return std::string(un.sysname) + " " + std::string(un.release);
}
// =============================================================================
// IOMMU DETECTION
// Reads /sys/kernel/iommu_groups and /proc/cmdline to identify Intel VT-d,
// AMD-Vi, passthrough, or strict mode. Returns human-readable state string.
// =============================================================================
static std::string QueryIommuState()
{
DIR* d = opendir("/sys/kernel/iommu_groups");
if (!d) return "disabled or unavailable";
int count = 0;
struct dirent* ent;
while ((ent = readdir(d)) != nullptr)
{
if (ent->d_name[0] == '.') continue;
count++;
}
closedir(d);
if (count == 0) return "no groups (passthrough or disabled)";
std::ifstream f("/proc/cmdline");
if (f.good())
{
std::string line;
std::getline(f, line);
bool intel = (line.find("intel_iommu=on") != std::string::npos);
bool amd = (line.find("amd_iommu=on") != std::string::npos);
bool pt = (line.find("iommu=pt") != std::string::npos);
bool strict = (line.find("iommu=strict") != std::string::npos);
std::string flag = "enabled";
if (pt) flag = "passthrough";
else if (strict) flag = "strict";
if (intel) return "Intel VT-d (" + flag + ", " + std::to_string(count) + " groups)";
else if (amd) return "AMD-Vi (" + flag + ", " + std::to_string(count) + " groups)";
else return flag + " (" + std::to_string(count) + " groups)";
}
return std::to_string(count) + " groups (active)";
}
// =============================================================================
// PCIe MPS / MRRS QUERY
// Max Payload Size and Max Read Request Size from PCIe config space.
// Primary: sysfs /sys/bus/pci/devices/<bdf>/max_payload_size
// Fallback: lspci -vvv DevCtl line (requires root for full config space access).
// =============================================================================
struct MpsMrrs
{
int mps_bytes = -1;
int mrrs_bytes = -1;
bool valid = false;
};
// Parse "256 bytes" or "512 bytes" style string -> integer bytes
static int ParseBytesStr(const std::string& s)
{
if (s.empty()) return -1;
try
{
size_t pos = 0;
int val = std::stoi(s, &pos);
return (val > 0) ? val : -1;
}
catch (...) { return -1; }
}
// Parse lspci -vvv output for MaxPayload and MaxReadReq.
// Looks for lines like:
// MaxPayload 256 bytes, MaxReadReq 512 bytes
static MpsMrrs ParseLspciOutput(const std::string& output)
{
MpsMrrs r;
std::istringstream ss(output);
std::string line;
while (std::getline(ss, line))
{
// Look for the DevCtl line which has both MaxPayload and MaxReadReq
if (line.find("MaxPayload") != std::string::npos &&
line.find("MaxReadReq") != std::string::npos)
{
// "MaxPayload 256 bytes, MaxReadReq 512 bytes"
auto extract = [&](const std::string& key) -> int
{
size_t p = line.find(key);
if (p == std::string::npos) return -1;
p += key.size();
while (p < line.size() && line[p] == ' ') p++;
std::string num;
while (p < line.size() && std::isdigit((unsigned char)line[p]))
num += line[p++];
return ParseBytesStr(num);
};
int mps = extract("MaxPayload ");
int mrrs = extract("MaxReadReq ");
if (mps > 0) r.mps_bytes = mps;
if (mrrs > 0) r.mrrs_bytes = mrrs;
if (r.mps_bytes > 0 && r.mrrs_bytes > 0) { r.valid = true; return r; }
}
}
return r;
}
static MpsMrrs QueryMpsMrrs(const std::string& bdf)
{
MpsMrrs r;
// Try sysfs first (kernel 4.0+ on some platforms)
std::string base = "/sys/bus/pci/devices/" + bdf;
r.mps_bytes = ReadSysfsInt(base + "/max_payload_size", -1);
r.mrrs_bytes = ReadSysfsInt(base + "/max_read_request_size", -1);
r.valid = (r.mps_bytes > 0 && r.mrrs_bytes > 0);
if (r.valid) return r;
// Fallback: parse lspci -s <bdf> -vvv
// BDF is normalized to "XXXX:XX:XX.X" -- safe to pass to popen
// Without root, lspci omits DevCtl config space fields -- retry with sudo
auto RunLspci = [&](const std::string& pfx) -> std::string
{
std::string cmd = pfx + "lspci -s " + bdf + " -vvv 2>/dev/null";
FILE* fp2 = popen(cmd.c_str(), "r");
if (!fp2) return std::string();
std::string out;
char buf2[256];
while (fgets(buf2, sizeof(buf2), fp2)) out += buf2;
pclose(fp2);
return out;
};
std::string output = RunLspci("");
if (output.find("MaxReadReq") == std::string::npos)
output = RunLspci("sudo ");
return ParseLspciOutput(output);
}
static std::string BytesToStr(int b)
{
if (b <= 0) return "unavailable";
return std::to_string(b) + " bytes";
}
// =============================================================================
// ASPM POLICY QUERY
// Reads /sys/bus/pci/devices/<bdf>/power/control.
// 'on' = runtime PM disabled (link stays active). 'auto' = kernel may allow
// low-power states between transfers. Relevant for latency-sensitive workloads.
// =============================================================================
static std::string QueryAspmPolicy(const std::string& bdf)
{
std::string ctrl = ReadSysfsStr("/sys/bus/pci/devices/" + bdf + "/power/control");
if (ctrl.empty()) return "unavailable";
if (ctrl == "on") return "disabled (runtime PM off)";
if (ctrl == "auto") return "auto (runtime PM enabled)";
return ctrl;
}
// =============================================================================
// AER COUNTER QUERY
// PCIe Advanced Error Reporting counters from sysfs.
// Reads pre-load and post-load snapshots of aer_dev_correctable,
// aer_dev_nonfatal, aer_dev_fatal. Reports per-counter deltas.
// Counter wrap-guard applied: negative deltas clamped to zero.
// =============================================================================
struct AerCounters
{
std::map<std::string, long long> correctable;
std::map<std::string, long long> nonfatal;
std::map<std::string, long long> fatal;
bool corr_valid = false;
bool nonfatal_valid = false;
bool fatal_valid = false;
};
static std::map<std::string, long long> ParseAerFile(const std::string& path)
{
std::map<std::string, long long> m;
std::ifstream f(path);
if (!f.good()) return m;
std::string line;
while (std::getline(f, line))
{
if (line.empty()) continue;
std::istringstream ss(line);
std::string name;
long long val = 0;
if (ss >> name >> val) m[name] = val;
}
return m;
}
static AerCounters ReadAerCounters(const std::string& bdf)
{
AerCounters a;
std::string base = "/sys/bus/pci/devices/" + bdf;
auto mc = ParseAerFile(base + "/aer_dev_correctable");
if (!mc.empty()) { a.correctable = mc; a.corr_valid = true; }
auto mn = ParseAerFile(base + "/aer_dev_nonfatal");
if (!mn.empty()) { a.nonfatal = mn; a.nonfatal_valid = true; }
auto mf = ParseAerFile(base + "/aer_dev_fatal");
if (!mf.empty()) { a.fatal = mf; a.fatal_valid = true; }
return a;
}
static std::map<std::string, long long> AerDelta(
const std::map<std::string, long long>& pre,
const std::map<std::string, long long>& post)
{
std::map<std::string, long long> d;
for (const auto& kv : post)
{
long long pre_val = 0;
auto it = pre.find(kv.first);
if (it != pre.end()) pre_val = it->second;
long long delta = kv.second - pre_val;
d[kv.first] = (delta < 0) ? 0 : delta; // counter wrap-guard
}
return d;
}
static long long AerTotalDelta(const std::map<std::string, long long>& delta)
{
long long total = 0;
for (const auto& kv : delta) total += kv.second;
return total;
}
// =============================================================================
// GPU CLOCK / P-STATE QUERY
// SM, memory, and graphics clocks + performance state captured via NVML
// before and after the transfer window. Correlates bandwidth measurements
// with GPU boost state and thermal throttle events.
// =============================================================================
struct ClockSnapshot
{
unsigned int sm_mhz = 0;
unsigned int mem_mhz = 0;
unsigned int gr_mhz = 0;
nvmlPstates_t pstate = NVML_PSTATE_UNKNOWN;
bool sm_valid = false;
bool mem_valid = false;
bool gr_valid = false;
bool pstate_valid = false;
};
static ClockSnapshot QueryClocks(nvmlDevice_t dev)
{
ClockSnapshot c;
c.sm_valid = (nvmlDeviceGetClockInfo(dev, NVML_CLOCK_SM, &c.sm_mhz) == NVML_SUCCESS);
c.mem_valid = (nvmlDeviceGetClockInfo(dev, NVML_CLOCK_MEM, &c.mem_mhz) == NVML_SUCCESS);
c.gr_valid = (nvmlDeviceGetClockInfo(dev, NVML_CLOCK_GRAPHICS, &c.gr_mhz) == NVML_SUCCESS);
c.pstate_valid = (nvmlDeviceGetPerformanceState(dev, &c.pstate) == NVML_SUCCESS);
return c;
}
static std::string PstateStr(nvmlPstates_t p)
{
if (p == NVML_PSTATE_UNKNOWN) return "unknown";
if ((int)p >= 0 && (int)p <= 15)
{
char buf[8];
std::snprintf(buf, sizeof(buf), "P%d", (int)p);
return std::string(buf);
}
return "unknown";
}
// =============================================================================
// PERSISTENCE MODE QUERY
// Persistence mode keeps the driver loaded between client connections.
// When disabled, the GPU may drop to low-power state (P8) between runs,
// affecting pre-load clock readings and first-transfer latency.
// =============================================================================
static std::string QueryPersistenceMode(nvmlDevice_t dev)
{
nvmlEnableState_t mode = NVML_FEATURE_DISABLED;
if (nvmlDeviceGetPersistenceMode(dev, &mode) != NVML_SUCCESS)
return "unavailable";
return (mode == NVML_FEATURE_ENABLED) ? "Enabled" : "Disabled";
}
// =============================================================================
// PCIe TOPOLOGY RESOLUTION
// Walks sysfs symlinks from the GPU endpoint up to the root port.
// Builds the full PCIe chain (root -> upstream -> endpoint), chain depth,
// and BDF identifiers for each hop. Used for slot identification and
// NUMA affinity correlation.
// =============================================================================
struct TopologyInfo
{
std::string endpoint_bdf;
std::string upstream_bdf;
std::string root_bdf;
std::string chain_str;
int depth = 0;
int numa_node = -1;
};
static std::string SysfsDevPath(const std::string& bdf)
{
return Join("/sys/bus/pci/devices", bdf);
}
static bool ResolveSysfsLink(const std::string& path, std::string& out)
{
char buf[4096];
ssize_t n = readlink(path.c_str(), buf, sizeof(buf) - 1);
if (n <= 0) return false;
buf[n] = '\0';
out = std::string(buf);
return true;
}
static bool GetParentBDF(const std::string& bdf, std::string& parent_bdf)
{
std::string dev = SysfsDevPath(bdf);
if (!ExistsDir(dev)) return false;
std::string link;
if (!ResolveSysfsLink(dev, link)) return false;
std::vector<std::string> segs;
std::stringstream ss(link);
std::string seg;
while (std::getline(ss, seg, '/'))
if (!seg.empty()
&& seg.find(':') != std::string::npos
&& seg.find('.') != std::string::npos)
segs.push_back(seg);
if (segs.size() < 2) return false;
parent_bdf = segs[segs.size() - 2];
return true;
}
static TopologyInfo BuildTopology(const std::string& raw_bdf, int numa_node_count)
{
TopologyInfo t;
t.endpoint_bdf = NormalizeBDF(raw_bdf);
t.numa_node = QueryGpuNumaNode(t.endpoint_bdf, numa_node_count);
std::vector<std::string> chain;
chain.push_back(t.endpoint_bdf);
std::string cur = t.endpoint_bdf, parent;
while (GetParentBDF(cur, parent))
{
if (parent == cur) break;
chain.push_back(parent);
cur = parent;
if ((int)chain.size() > 32) break;
}
std::reverse(chain.begin(), chain.end());
t.depth = (int)chain.size() - 1;
if (chain.size() >= 2)
{
t.root_bdf = chain.front();
t.upstream_bdf = chain[chain.size() - 2];
}
else
{
t.root_bdf = chain.front();
t.upstream_bdf = "";
}
std::ostringstream cs;
for (size_t i = 0; i < chain.size(); i++)
{
if (i) cs << " -> ";
cs << chain[i];
}
t.chain_str = cs.str();
return t;
}
// =============================================================================
// CUDA BANDWIDTH + LATENCY MEASUREMENT
// Two transfer profiles:
// Bulk: user-defined buffer size (default 1 GiB) -- measures sustained DMA
// throughput as payload GB/s per direction.
// Link: fixed 64 KiB x 100 iterations -- measures PCIe transaction latency
// (control-path overhead, not payload rate).
// All timing uses CUDA events for microsecond precision.
// Warmup pass executed before measurement to bring link to negotiated state.
// =============================================================================
struct BandwidthResult
{
double bulk_h2d_gbs = 0.0;
double bulk_d2h_gbs = 0.0;
double bulk_avg_gbs = 0.0;
double bulk_h2d_latency_us = 0.0;
double bulk_d2h_latency_us = 0.0;
double bulk_avg_latency_us = 0.0;
double link_h2d_latency_us = 0.0;
double link_d2h_latency_us = 0.0;
double link_avg_latency_us = 0.0;
};
static BandwidthResult RunMemcpyBandwidth(int device, size_t bulk_bytes,
int bulk_iters, bool use_pinned)
{
cudaSetDevice(device);
void* dptr = nullptr;
void* hptr = nullptr;
if (cudaMalloc(&dptr, bulk_bytes) != cudaSuccess)
throw std::runtime_error("cudaMalloc failed");
if (use_pinned)
{
if (cudaMallocHost(&hptr, bulk_bytes) != cudaSuccess)
{ cudaFree(dptr); throw std::runtime_error("cudaMallocHost failed"); }
}
else
{
if (cudaHostAlloc(&hptr, bulk_bytes, cudaHostAllocDefault) != cudaSuccess)
{ cudaFree(dptr); throw std::runtime_error("cudaHostAlloc failed"); }
}
std::memset(hptr, 0xA5, bulk_bytes);
cudaStream_t st;
cudaStreamCreate(&st);
cudaEvent_t ev_start, ev_stop;
cudaEventCreate(&ev_start);
cudaEventCreate(&ev_stop);
// Warmup: bring link to full negotiated Gen
for (int i = 0; i < 3; i++)
{
cudaMemcpyAsync(dptr, hptr, bulk_bytes, cudaMemcpyHostToDevice, st);
cudaMemcpyAsync(hptr, dptr, bulk_bytes, cudaMemcpyDeviceToHost, st);
}
cudaStreamSynchronize(st);
// H2D bulk bandwidth
cudaEventRecord(ev_start, st);
for (int i = 0; i < bulk_iters; i++)
cudaMemcpyAsync(dptr, hptr, bulk_bytes, cudaMemcpyHostToDevice, st);
cudaEventRecord(ev_stop, st);
cudaEventSynchronize(ev_stop);
float h2d_ms = 0.0f;
cudaEventElapsedTime(&h2d_ms, ev_start, ev_stop);
double h2d_gb = (double)bulk_bytes * bulk_iters / (1024.0 * 1024.0 * 1024.0);
double h2d_gbs = h2d_gb / std::max(1e-9, (double)h2d_ms / 1000.0);
double h2d_lat = ((double)h2d_ms / bulk_iters) * 1000.0;
// D2H bulk bandwidth
cudaEventRecord(ev_start, st);
for (int i = 0; i < bulk_iters; i++)
cudaMemcpyAsync(hptr, dptr, bulk_bytes, cudaMemcpyDeviceToHost, st);
cudaEventRecord(ev_stop, st);
cudaEventSynchronize(ev_stop);
float d2h_ms = 0.0f;
cudaEventElapsedTime(&d2h_ms, ev_start, ev_stop);
double d2h_gb = (double)bulk_bytes * bulk_iters / (1024.0 * 1024.0 * 1024.0);
double d2h_gbs = d2h_gb / std::max(1e-9, (double)d2h_ms / 1000.0);
double d2h_lat = ((double)d2h_ms / bulk_iters) * 1000.0;
// Link latency: fixed 64 KiB transfer repeated 100 times.
// 64 KiB sits below the max TLP payload on all PCIe generations --
// measures per-transaction overhead (control path), not payload rate.
// 100 iterations amortizes CUDA event and stream launch overhead
// while keeping the test well under 1 second.
const size_t link_bytes = 64 * 1024; // 64 KiB -- sub-TLP payload
const int link_iters = 100; // iterations for stable average
cudaEventRecord(ev_start, st);
for (int i = 0; i < link_iters; i++)
cudaMemcpyAsync(dptr, hptr, link_bytes, cudaMemcpyHostToDevice, st);
cudaEventRecord(ev_stop, st);
cudaEventSynchronize(ev_stop);
float link_h2d_ms = 0.0f;
cudaEventElapsedTime(&link_h2d_ms, ev_start, ev_stop);
double link_h2d_lat = ((double)link_h2d_ms / link_iters) * 1000.0;
cudaEventRecord(ev_start, st);
for (int i = 0; i < link_iters; i++)
cudaMemcpyAsync(hptr, dptr, link_bytes, cudaMemcpyDeviceToHost, st);
cudaEventRecord(ev_stop, st);
cudaEventSynchronize(ev_stop);
float link_d2h_ms = 0.0f;
cudaEventElapsedTime(&link_d2h_ms, ev_start, ev_stop);
double link_d2h_lat = ((double)link_d2h_ms / link_iters) * 1000.0;
cudaEventDestroy(ev_stop);
cudaEventDestroy(ev_start);
cudaStreamDestroy(st);
cudaFreeHost(hptr);
cudaFree(dptr);
BandwidthResult r;
r.bulk_h2d_gbs = h2d_gbs;
r.bulk_d2h_gbs = d2h_gbs;
r.bulk_avg_gbs = 0.5 * (h2d_gbs + d2h_gbs);
r.bulk_h2d_latency_us = h2d_lat;
r.bulk_d2h_latency_us = d2h_lat;
r.bulk_avg_latency_us = 0.5 * (h2d_lat + d2h_lat);
r.link_h2d_latency_us = link_h2d_lat;
r.link_d2h_latency_us = link_d2h_lat;
r.link_avg_latency_us = 0.5 * (link_h2d_lat + link_d2h_lat);
return r;
}
// =============================================================================
// NVML TELEMETRY SAMPLING
// Background thread drives continuous DMA traffic during the measurement window.
// Main thread polls NVML at cfg.interval_ms for PCIe RX/TX counters,
// power draw (mW -> W), and GPU temperature. Samples aggregated post-window
// for average, peak, and delta calculations.
// =============================================================================
struct Sample
{
double t_ms = 0.0;
double rx_gbs = 0.0;
double tx_gbs = 0.0;
double power_w = 0.0;
double temp_c = 0.0;
};
struct RunConfig
{
int device_index = 0;
int window_ms = 2000;
int interval_ms = 100;
int size_mib = 1024;
bool list_devices = false;
bool all_devices = false;
std::string memory_mode = "pinned";
};
static double ClampPos(double x) { return x < 0.0 ? 0.0 : x; }
// =============================================================================
// PROGRESS REPORTER
// Prints timestamped status lines to stderr during validation so the operator
// always knows what phase the tool is in. Single-device mode prints per-sample
// ticker lines during the NVML window. Multi-GPU (all_devices) mode prints
// only phase summaries per GPU to avoid flooding the screen.
// All progress output goes to stderr — stdout and log files remain clean.
// =============================================================================
static void ProgressInit()
{
}
// Phase announcements suppressed — one bar only.
static void Progress(int gpu_idx, const std::string& msg)
{
(void)gpu_idx; (void)msg; // silent
}
// Sampling tick: overwrites the same line using \r so the progress bar
// stays as a single updating line. When the run finishes, ProgressDone()
// clears it with spaces so the report prints on a clean screen.
static void ProgressTick(int gpu_idx, long long elapsed_s, long long total_s,
double rx, double tx, double power_w, double temp_c)
{
// Build the bar: [=========> ] 25/30s
int bar_width = 20;
int filled = (total_s > 0) ? (int)((elapsed_s * bar_width) / total_s) : 0;
if (filled > bar_width) filled = bar_width;
char bar[32];
for (int i = 0; i < bar_width; i++)
bar[i] = (i < filled) ? '=' : ' ';
bar[bar_width] = '\0';
char buf[200];
std::snprintf(buf, sizeof(buf),
"\r[%s>%s] %lld/%llds | RX %5.2f TX %5.2f GB/s | %5.1fW %3.0fC ",
bar, (filled < bar_width ? "" : ""), elapsed_s, total_s,
rx, tx, power_w, temp_c);
std::fprintf(stderr, "%s", buf);
std::fflush(stderr);
}
// Call once when sampling is done — clears the progress bar line
static void ProgressDone()
{
std::fprintf(stderr, "\r%80s\r", "");
std::fflush(stderr);
}
static void TrafficWorker(std::atomic<bool>& go, int device,
size_t bytes, int window_ms)
{
cudaSetDevice(device);
void* dptr = nullptr;
void* hptr = nullptr;
cudaMalloc(&dptr, bytes);
cudaMallocHost(&hptr, bytes);
std::memset(hptr, 0x5A, bytes);
cudaStream_t st;
cudaStreamCreate(&st);
while (!go.load(std::memory_order_acquire))
std::this_thread::sleep_for(std::chrono::milliseconds(1));
auto end_t = std::chrono::steady_clock::now() + std::chrono::milliseconds(window_ms);
bool dir = true;
while (std::chrono::steady_clock::now() < end_t)
{
if (dir) cudaMemcpyAsync(dptr, hptr, bytes, cudaMemcpyHostToDevice, st);
else cudaMemcpyAsync(hptr, dptr, bytes, cudaMemcpyDeviceToHost, st);
dir = !dir;
cudaStreamSynchronize(st);
}
cudaStreamDestroy(st);
cudaFreeHost(hptr);
cudaFree(dptr);
}
static bool NVML_GetThroughputGBs(nvmlDevice_t dev, double& rx, double& tx)
{
unsigned int rx_kbs = 0, tx_kbs = 0;
if (nvmlDeviceGetPcieThroughput(dev, NVML_PCIE_UTIL_RX_BYTES, &rx_kbs) != NVML_SUCCESS) return false;
if (nvmlDeviceGetPcieThroughput(dev, NVML_PCIE_UTIL_TX_BYTES, &tx_kbs) != NVML_SUCCESS) return false;
rx = ClampPos((double)rx_kbs / (1024.0 * 1024.0));
tx = ClampPos((double)tx_kbs / (1024.0 * 1024.0));
return true;
}
static bool NVML_GetPowerTemp(nvmlDevice_t dev, double& power_w, double& temp_c)
{
unsigned int mw = 0, tc = 0;
if (nvmlDeviceGetPowerUsage(dev, &mw) != NVML_SUCCESS) return false;
if (nvmlDeviceGetTemperature(dev, NVML_TEMPERATURE_GPU, &tc) != NVML_SUCCESS) return false;
power_w = (double)mw / 1000.0;
temp_c = (double)tc;
return true;
}
struct LinkInfo
{
int max_gen = 0;
int max_width = 0;
int cur_gen = 0;
int cur_width = 0;
};
static bool NVML_GetLinkInfo(nvmlDevice_t dev, LinkInfo& out)
{
if (nvmlDeviceGetMaxPcieLinkGeneration (dev, (unsigned int*)&out.max_gen) != NVML_SUCCESS) return false;
if (nvmlDeviceGetMaxPcieLinkWidth (dev, (unsigned int*)&out.max_width) != NVML_SUCCESS) return false;
if (nvmlDeviceGetCurrPcieLinkGeneration(dev, (unsigned int*)&out.cur_gen) != NVML_SUCCESS) return false;
if (nvmlDeviceGetCurrPcieLinkWidth (dev, (unsigned int*)&out.cur_width) != NVML_SUCCESS) return false;
return true;
}
static std::string LinkStr(int gen, int width)
{
std::ostringstream ss;
ss << "PCIe Gen" << gen << " x" << width;
return ss.str();
}
// Per-lane effective payload rates (encoding overhead applied).
// Covers all PCIe generations including Gen5 (H100/A100) and Gen6 (B200/GB200/B300 Ultra).
static double TheoreticalPayloadGBsPerDir(int gen, int width)
{
double per_lane = 0.0;
switch (gen)
{
case 1: per_lane = 0.250; break; // 2.5 GT/s 8b/10b
case 2: per_lane = 0.500; break; // 5.0 GT/s 8b/10b
case 3: per_lane = 0.985; break; // 8.0 GT/s 128b/130b
case 4: per_lane = 1.969; break; // 16.0 GT/s 128b/130b
case 5: per_lane = 3.938; break; // 32.0 GT/s 128b/130b
case 6: per_lane = 7.877; break; // 64.0 GT/s FLIT (Blackwell)
default: per_lane = 0.0; break;
}
return per_lane * (double)width;
}
// =============================================================================
// JSON SERIALIZATION
// Minimal JSON string escaping for report output. All numeric fields written
// as raw values (no quotes). String fields escaped for special characters.
// =============================================================================
static std::string JsonEscape(const std::string& s)
{
std::ostringstream o;
o << '"';
for (char c : s)
{
if (c == '"') o << "\\\"";
else if (c == '\\') o << "\\\\";
else if (c == '\n') o << "\\n";
else if (c == '\r') o << "\\r";
else o << c;