-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintercept_timer.cpp
More file actions
1831 lines (1699 loc) · 76.3 KB
/
Copy pathintercept_timer.cpp
File metadata and controls
1831 lines (1699 loc) · 76.3 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
/*
* intercept_timer — an example libfab-intercepter consumer that measures the
* latency of each initiator-side data-path op (issue ... CQ completion) and
* attributes it to the directed NIC->NIC link it ran on.
*
* Timed ops: fi_send, fi_tsend, fi_tsendmsg, fi_tsenddata, fi_write, fi_writemsg,
* the whole fi_read family (fi_read / fi_readv / fi_readmsg), and fi_trecv
* (receive-side; see "Receiver-side timing" below). The tagged sendmsg/senddata
* variants are how Cray MPICH sends; the fi_read family is how it services
* MPI_Get. (There is no fi_readdata op -- libfabric carries remote CQ data only
* on the write side; a read that wants it goes through fi_readmsg with
* FI_REMOTE_CQ_DATA, which is already covered here.)
*
* How it works
* ------------
* - On each issue (the send/write/read shims): claim a slot in a fixed ring,
* stamp the start time, the op kind, the transfer size, the issuing
* endpoint and the peer fi_addr_t, stash the application's original
* context, then forward the op with the context redirected at our slot so
* we can find it again at completion. For the plain ops `context` is a
* parameter we repoint directly; for the `msg` ops it lives in a const
* struct, so we forward a copy.
* - on_ep_bind: when the app binds an address vector to an endpoint, remember
* ep->av so we can turn an fi_addr_t (an AV-table index for cxi) back into a
* human-readable NIC address at report time.
* - cq_open: remember each CQ's entry format, so we know where the op_context
* lives in the completion structs cq_read fills in.
* - cq_read: for every completion whose op_context points back into our ring,
* stamp the end time, fold the latency into the per-link / per-(kind,size)
* stats, and restore the application's original context before it sees the
* completion. The first completion on a link resolves its local/remote NIC
* address strings (the endpoint and AV are still alive at that point).
* - cq_readerr: an op that failed completes here instead; we free its slot,
* restore the context and count it as an error rather than timing it.
*
* Output: each rank writes its own report file at exit so the per-rank reports
* never interleave. Path is
* ${INTERCEPT_TIMER_DIR:-.}/intercept_timer.<host>.r<rank>.p<pid>.txt
* (rank taken from SLURM_PROCID / OMPI_COMM_WORLD_RANK / PMIX_RANK / PMI_RANK /
* RANK). A single line to stderr points at each file. Set
* INTERCEPT_TIMER_DIR=stderr (or "-") to write straight to stderr instead
* (which will interleave across ranks). Each report contains:
* - Per NIC (local endpoint): a concurrency-aware achieved bandwidth =
* completed bytes / the wall-clock time the NIC had >=1 op in flight (the
* union of all its in-flight intervals). This is the number to read for
* "am I saturating the link"; it counts overlapping ops once, not summed.
* Attribution is per NIC, not per link, because when several peers share a
* NIC their intervals overlap and can't be split per link.
* - Per link (local NIC -> remote NIC): every distinct (op, message size)
* with its op count, latency (avg/min/max) and an implied per-op bandwidth,
* so you can see how close an individual large transfer gets to peak.
*
* Measurement caveat: "latency" is issue -> the moment we observe the
* completion in cq_read, so it includes however long the entry sat in the CQ
* before the app polled it. It is a faithful op turnaround time, not a
* hardware-only number; the per-link implied bandwidth is per-op (one op at a
* time), while the per-NIC achieved bandwidth is the concurrency-aware figure.
*
* Receiver-side timing (fi_trecv): post -> completion. Unlike the send-side
* ops this includes the wait for the peer to send at all, so its avg/min/max
* are NOT a network latency. The number to read is the [imm N%] tag on each
* fi_trecv row: the fraction of recvs that completed almost immediately
* (< 50 us) after being posted, i.e. the message had ALREADY arrived and was
* sitting in the provider's unexpected/overflow queue -- direct evidence the
* receiver posted late. trecvs are deliberately excluded from the per-NIC
* busy/achieved aggregate (their in-flight time is mostly idle wait), and the
* row's size is the actual bytes received (from the CQ entry), not the posted
* buffer size, when the CQ format carries a length.
*
* CQ poll gaps: every fi_cq_read/fi_cq_readfrom invocation is timestamped
* (one steady_clock read per poll) and the gap to the SAME CQ's previous poll
* is folded into a per-CQ histogram, reported as the "CQ#n" lines. A progress
* thread that is descheduled or stuck shows up as gaps in the ms+ buckets and
* a large max (with its time offset since the first fabric op, to correlate
* with benchmark phases). Legitimate idle phases (between benchmark sizes,
* init/teardown) also produce large gaps -- interpret counts, not totals, and
* compare nodes against nodes. Set INTERCEPT_TIMER_CQGAP=0 to disable the
* per-poll timestamping entirely.
*
* Per-op CSV mode (opt-in): logs EVERY completed op -- start, end, duration, op
* kind, bytes, and source->target NIC -- as a CSV at exit
* (intercept_timer_ops.<host>.r<rank>.p<pid>.csv in INTERCEPT_TIMER_DIR). The
* dumped op kinds are exactly the hooked initiator-side ops plus tagged recv:
* fi_send, fi_tsend, fi_tsendmsg, fi_tsenddata, fi_write, fi_writemsg, fi_read,
* fi_readv, fi_readmsg, fi_trecv. Two
* ways to scope it (set one):
* - INTERCEPT_TIMER_OPS_RANKS=<list/range> (e.g. "0,8,16" or "0-7,512"):
* dump every op on those ranks.
* - INTERCEPT_TIMER_OPS_NIC=<nic substring> (e.g. "0x01ad0407", taken from a
* NIC line of the aggregate report): dump on ALL ranks, but only ops
* touching that NIC -- sends/writes/reads aimed at it (remote NIC) and
* recvs posted by it (local NIC). The match is decided once per link, at
* address-resolution time, so the hot path stays a cached bool. If both
* vars are set, the NIC filter wins.
* Either way, only ops of at least INTERCEPT_TIMER_OPS_MIN_BYTES bytes are
* logged (default 65536, which keeps RCCL's 64/128 KiB data chunks and drops
* the small control/signaling messages that dominate op counts at scale; set
* 131072 for 128 KiB chunks only, 0 to log everything). Ops that complete in
* error are always logged regardless of size. The aggregate report is
* unaffected -- the filter scopes only the per-op CSV.
* Samples are buffered in a RAM buffer malloc'd once at startup for active
* ranks (INTERCEPT_TIMER_OPS_MB, default 1024 = 1 GiB/rank; ~33M ops; virtual
* until written, so ranks that match nothing pay ~no physical memory) and
* appended lock-free (one atomic bump + struct store), formatted to CSV only at
* exit. If the buffer fills, further ops are dropped and counted (raise the MB
* knob).
*
* NIC hardware-counter time series (on by default): a background thread samples
* the Cassini per-NIC counters every INTERCEPT_TIMER_NIC_MS ms (default 100) and
* writes them as a CSV at exit:
* ${INTERCEPT_TIMER_DIR:-.}/intercept_timer_nic.<host>.r<rank>.p<pid>.csv
* One row per sample: t_ns (ns since this rank's anchor -- the SAME anchor as the
* per-op CSV, so they line up), wall_ns (CLOCK_REALTIME, for cross-rank
* alignment), then one column per counter. Two sources are read: the sysfs
* telemetry under /sys/class/cxi/<dev>/device/telemetry/ (e.g. hni_sts_*_octets,
* pct_spt_timeouts, hni_pause_sent, ixe_pool_ecn_pkts_N) and the cxi_rh retry
* handler stats under /run/cxi/<dev>/ (e.g. nacks, parked_nids, pkts_cancelled_o),
* the latter as "rh:<name>" columns. The default selection favors the telemetry:
* the retry-handler timeouts/NACKs/occupancy all have pct_* twins that advance
* with the hardware instead of lagging the FUSE daemon that exports the rh: side,
* so by default only the rh stats WITHOUT a hardware twin (NID/switch parking,
* cancellations) are sampled; pass INTERCEPT_TIMER_NIC_COUNTERS=rh: for the full
* retry-handler set. By default each rank samples the NIC it drives
* (cxi$SLURM_LOCALID). The thread starts on the first fabric activity, not at
* load, so forked non-fabric children don't each emit a file. Knobs:
* INTERCEPT_TIMER_NIC=0 (off), INTERCEPT_TIMER_NIC_MS, INTERCEPT_TIMER_NIC_DEV
* (cxi list | all), INTERCEPT_TIMER_NIC_COUNTERS (all | rh: | <prefix>* | names;
* default = a wide curated telemetry set + a curated rh subset),
* INTERCEPT_TIMER_NIC_MAX_MB (default 256).
*
* Build (linked into your own LD_PRELOAD .so, see README.md):
* g++ -std=c++17 -fPIC -pthread -shared -I$LIBFABRIC_PREFIX/include \
* intercept_timer.cpp libfabintercept.a -o libtimer_preload.so -ldl
*/
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <atomic>
#include <cctype>
#include <chrono>
#include <condition_variable>
#include <ctime>
#include <limits>
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h> // gethostname, getpid
#include "libfabintercept.h"
#include "rdma/fabric.h"
#include "rdma/fi_cm.h" // fi_getname
using clock_type = std::chrono::steady_clock;
using time_point = clock_type::time_point;
namespace {
enum op_kind {
OP_SEND,
OP_TSEND,
OP_WRITE,
OP_WRITEMSG,
OP_READ,
OP_READMSG,
OP_TRECV,
// Appended (not inserted) so existing op_kind numeric values stay stable. The
// tagged-send variants Cray MPICH uses for its rendezvous/large path: bare
// fi_tsend (also hooked) never showed up, so its sends go through these.
OP_TSENDMSG,
OP_TSENDDATA,
// Completes the fi_read family: the scatter/gather read. Cray MPICH issues it
// when an MPI_Get lands on a non-contiguous origin buffer.
OP_READV,
OP_KIND_COUNT
};
const char* op_name(op_kind k) {
switch (k) {
case OP_SEND: return "fi_send";
case OP_TSEND: return "fi_tsend";
case OP_WRITE: return "fi_write";
case OP_WRITEMSG: return "fi_writemsg";
case OP_READ: return "fi_read";
case OP_READMSG: return "fi_readmsg";
case OP_TRECV: return "fi_trecv";
case OP_TSENDMSG: return "fi_tsendmsg";
case OP_TSENDDATA: return "fi_tsenddata";
case OP_READV: return "fi_readv";
default: return "?";
}
}
// Best-effort rank id for naming the per-rank output file. We have no MPI here,
// so read whichever launcher set its rank in the environment (srun, Open MPI,
// PMIx/PMI, torchrun); fall back to "NA" if none is present.
std::string detect_rank() {
static const char* const keys[] = {"SLURM_PROCID", "OMPI_COMM_WORLD_RANK",
"PMIX_RANK", "PMI_RANK", "RANK"};
for (const char* k : keys)
if (const char* v = getenv(k)) return v;
return "NA";
}
// ---- Per-op CSV logging (opt-in) ----------------------------------------
// One fixed-size sample per completed op, appended to a preallocated RAM buffer
// when this rank is selected by INTERCEPT_TIMER_OPS_RANKS and written out as CSV
// at exit. This is ADDITIVE to the aggregate report and entirely off otherwise.
struct op_sample {
uint64_t start_ns; // since state.anchor
uint64_t dur_ns; // issue -> completion; end = start_ns + dur_ns
uint32_t bytes; // bytes moved (received len for trecv)
uint32_t link_id; // -> (local_nic, remote_nic), resolved at dump time
uint16_t kind; // op_kind
uint16_t error; // 1 if the op completed in error, else 0
};
// Membership test for a rank spec like "0,8,16" or "0-7,16,32-40".
bool rank_selected(const char* spec, long rank) {
if (!spec || !*spec || rank < 0) return false;
for (const char* p = spec; *p;) {
char* e = nullptr;
long lo = std::strtol(p, &e, 10);
if (e == p) break; // not a number: stop
long hi = lo;
if (*e == '-') {
const char* q = e + 1;
hi = std::strtol(q, &e, 10);
if (e == q) hi = lo;
}
if (rank >= lo && rank <= hi) return true;
while (*e == ',' || *e == ' ') ++e;
p = e;
}
return false;
}
// True iff INTERCEPT_TIMER_OPS_RANKS is set and selects this rank. A rank string
// that is not a number (e.g. "NA" when no launcher env is present) is never
// selected -- we can't tell which process it is.
bool ops_selected_for(const std::string& rank_str) {
const char* spec = getenv("INTERCEPT_TIMER_OPS_RANKS");
if (!spec || !*spec) return false;
char* e = nullptr;
long r = std::strtol(rank_str.c_str(), &e, 10);
if (e == rank_str.c_str()) return false;
return rank_selected(spec, r);
}
// Capacity (in samples) of the per-rank buffer. INTERCEPT_TIMER_OPS_MB sizes it
// in MiB; default 1 GiB. The reservation is virtual (malloc), so the unused
// tail costs no physical memory.
uint64_t ops_capacity() {
uint64_t mb = 1024;
if (const char* v = getenv("INTERCEPT_TIMER_OPS_MB")) {
char* e = nullptr;
long m = std::strtol(v, &e, 10);
if (e != v && m > 0) mb = static_cast<uint64_t>(m);
}
return (mb * 1024ULL * 1024ULL) / sizeof(op_sample);
}
// NIC-targeted filter: the substring an op's NIC address must contain to be
// logged (empty = mode off). See ops_on / record().
std::string ops_nic_target() {
const char* v = getenv("INTERCEPT_TIMER_OPS_NIC");
return v ? std::string(v) : std::string();
}
// Size floor for the per-op log: ops smaller than this many bytes are not
// logged (errors always are). INTERCEPT_TIMER_OPS_MIN_BYTES, default 64 KiB.
uint64_t ops_min_bytes() {
uint64_t b = 65536;
if (const char* v = getenv("INTERCEPT_TIMER_OPS_MIN_BYTES")) {
char* e = nullptr;
long long m = std::strtoll(v, &e, 10);
if (e != v && m >= 0) b = static_cast<uint64_t>(m);
}
return b;
}
// One in-flight op we are timing. While the op is outstanding a pointer to this
// record lives in the op's context; `user_ctx` keeps the value we displaced so
// we can put it back before the app sees the completion. `busy` marks the slot
// as occupied from claim until its completion is processed, so claim never
// reuses a slot whose op is still outstanding (which would corrupt both the
// timing and the context we restore to the app). `ep`/`peer` carry the link
// identity from issue to completion.
//
// `scratch` MUST be the first member. Providers that negotiate FI_CONTEXT /
// FI_CONTEXT2 (aws-ofi-nccl requests both) treat the `context` pointer we hand
// them as provider-owned scratch and write up to a full fi_context2 (64B) into
// it for the lifetime of the op. By redirecting context at `&rec`, that scratch
// lands in `scratch` and leaves our bookkeeping fields below it intact; without
// it the provider would clobber `busy`/`user_ctx`/... and run off the end of the
// record into the next ring slot.
struct op_record {
fi_context2 scratch;
std::atomic<bool> busy{false};
void* user_ctx = nullptr;
struct fid_ep* ep = nullptr;
fi_addr_t peer = FI_ADDR_UNSPEC;
size_t bytes = 0;
op_kind kind = OP_SEND;
time_point start{};
};
// Fixed-size ring of in-flight records. A slot is claimed per op by an atomic
// increment of `seq` (lock-free, thread-safe) and only handed out if it is not
// still busy from an earlier, not-yet-completed op. Size the ring above the
// workload's queue depth so this normally never collides; if it does, the op is
// timed-through untouched and counted in `dropped` rather than overwriting a
// live slot.
//
// Caveat: a slot is freed only when its completion (success or error) is seen,
// so this assumes every timed op produces a CQ entry. Ops with suppressed
// completions (FI_INJECT / selective completion) would leak their slot -- but
// those wouldn't be timed meaningfully anyway.
// Sized for recvs too: NCCL preposts up to NCCL_STEPS recvs on every active
// connection (1000+ peers at scale), and each preposted trecv holds its slot
// until its message arrives.
constexpr size_t kMaxInflight = 16384;
// A trecv that completes faster than this after being posted found its message
// already waiting in the unexpected queue -> the receiver posted late.
constexpr double kImmNs = 50e3; // 50 us
// Latency stats for one (op kind, message size) within one link.
struct bucket {
uint64_t count = 0;
uint64_t errors = 0;
uint64_t imm = 0; // completions < kImmNs after issue (read for fi_trecv)
double total_ns = 0.0;
double min_ns = std::numeric_limits<double>::infinity();
double max_ns = 0.0;
void add(double ns) {
++count;
if (ns < kImmNs) ++imm;
total_ns += ns;
if (ns < min_ns) min_ns = ns;
if (ns > max_ns) max_ns = ns;
}
};
struct bucket_key {
op_kind kind;
size_t bytes;
bool operator==(const bucket_key& o) const {
return kind == o.kind && bytes == o.bytes;
}
};
struct bucket_key_hash {
size_t operator()(const bucket_key& k) const {
return std::hash<size_t>()(k.bytes) * 1099511628211ULL ^
static_cast<size_t>(k.kind);
}
};
// One directed link: a local endpoint sending/reading to/from a remote peer.
// Its address strings are resolved lazily, once, on the first completion seen
// for the link (the endpoint and AV are still alive at data time).
struct link_data {
std::mutex mtx;
bool resolved = false;
uint32_t id = 0; // stable per-link index for per-op CSV logging
// NIC-targeted mode (ops_nic): cached once at resolve time. A send/write/read
// on this link "targets" the NIC if remote == ops_nic; a recv is "posted by"
// the NIC if local == ops_nic.
bool nic_send = false;
bool nic_recv = false;
std::string local = "?";
std::string remote = "?";
std::unordered_map<bucket_key, bucket, bucket_key_hash> buckets;
};
struct link_id {
struct fid_ep* ep;
fi_addr_t peer;
bool operator==(const link_id& o) const {
return ep == o.ep && peer == o.peer;
}
};
struct link_id_hash {
size_t operator()(const link_id& k) const {
return std::hash<const void*>()(k.ep) * 1099511628211ULL ^
std::hash<uint64_t>()(static_cast<uint64_t>(k.peer));
}
};
// Concurrency-aware aggregate for one local NIC (endpoint). Per-op latency
// can't be summed into throughput, but the wall-clock time the NIC has >=1 op
// in flight can: achieved bandwidth = bytes / busy_ns. `inflight` rises on issue
// and falls on completion; `busy_start` is stamped on the 0->1 transition and a
// closed interval is folded into `busy_ns` on the 1->0 transition, so
// overlapping ops are counted once (union of their intervals), not summed.
// Attribution is per NIC rather than per link on purpose: when several peers
// share a NIC their intervals overlap and can't be split per link, but the
// NIC's own union is unambiguous.
struct nic_stats {
std::mutex mtx;
bool resolved = false;
std::string local = "?";
uint64_t inflight = 0;
time_point busy_start{};
double busy_ns = 0.0; // wall time with >=1 op in flight
uint64_t bytes = 0; // bytes of successfully completed ops
uint64_t ops = 0;
};
// Poll-gap accounting for one CQ. Lock-free: the polling hot path does one
// steady_clock read and a few relaxed atomics per fi_cq_read call. `last_ns`
// is the previous poll's timestamp (ns since the state's anchor; 0 = none yet);
// the gap between consecutive polls of the same CQ is folded into a fixed
// histogram. Multiple threads polling one CQ measure their combined cadence,
// which is the semantics we want ("was anyone servicing this CQ?").
struct cq_gap {
std::atomic<struct fid_cq*> cq{nullptr};
std::atomic<uint64_t> polls{0};
std::atomic<uint64_t> last_ns{0};
std::atomic<uint64_t> hist[6]{}; // <10us <100us <1ms <10ms <100ms >=100ms
std::atomic<uint64_t> max_gap_ns{0};
std::atomic<uint64_t> max_gap_at_ns{0}; // when the max gap ENDED (anchor-rel)
};
constexpr size_t kMaxCqs = 64;
constexpr uint64_t kGapEdgeNs[5] = {10'000, 100'000, 1'000'000, 10'000'000,
100'000'000};
bool cqgap_env_on() {
const char* e = getenv("INTERCEPT_TIMER_CQGAP");
return !(e && std::strcmp(e, "0") == 0);
}
// ===========================================================================
// NIC hardware-counter sampler
// ===========================================================================
//
// A background thread that snapshots Cassini per-NIC counters on a fixed cadence
// (default 100 ms) into a RAM time series and writes it as a CSV at exit, so the
// op-level timeline above can be lined up against what the hardware and the
// retry handler were doing (pause, NACKs, spt_timeouts, resource exhaustion).
//
// Two counter sources, both read the same way -- one unsigned integer at the
// head of the file; strtoull stops at the telemetry '@<timestamp>' suffix or the
// rh stat's trailing newline:
// * sysfs telemetry /sys/class/cxi/<dev>/device/telemetry/<name>
// "<count>@<unix_sec>.<nsec>" (pct_*, hni_*, ixe_*, cq_*)
// * retry handler /run/cxi/<dev>/<name> (cxi_rh FUSE, plain int:
// nacks, parked_nids, pkts_cancelled_o, ...)
// -> emitted as column "rh:<name>"
// The rh source is exported by a userspace FUSE daemon and updates a beat behind
// the hardware, so most of its stats (timeouts, NACK types, *_in_use occupancy)
// are sampled from their pct_* telemetry twins instead; the default rh subset is
// only what the hardware doesn't expose (kCuratedRh -- NID/switch parking,
// cancellations). See kCuratedTelem / kCuratedRh.
//
// Which NIC: by default the one this rank drives, cxi$SLURM_LOCALID (a node runs
// one rank per NIC), so each rank's CSV covers a distinct NIC on that rank's own
// clock anchor -- the SAME anchor as its per-op CSV, so the two line up directly.
// If the local id is unknown or its device is absent, every cxi present is
// sampled. Override with INTERCEPT_TIMER_NIC_DEV=cxi0,cxi2 | all.
//
// The thread is started LAZILY, on the first fabric activity we see (cq_open /
// ep_bind), not at library load: the preload is inherited by every process the
// job forks (ninja, python workers, the launcher); starting at load would have
// each of them spin a sampler and emit a duplicate counter file. A process that
// never touches the fabric never starts one.
//
// Env:
// INTERCEPT_TIMER_NIC=0 disable entirely (default on)
// INTERCEPT_TIMER_NIC_MS=<ms> sample interval, default 100
// INTERCEPT_TIMER_NIC_DEV=<list> cxi devices (default cxi$LOCALID, else every
// cxi present); "all" = every cxi present
// INTERCEPT_TIMER_NIC_COUNTERS=... comma-separated selection (default = a wide
// curated telemetry set + a curated rh subset:
// only the rh stats with no hardware twin, the
// rest superseded by their pct_* counters which
// don't lag the FUSE daemon).
// Tokens: "all" (every telemetry counter +
// every rh stat), "rh:" / "rh:*" (every rh
// stat), "rh:<name>" (one rh stat),
// "<prefix>*" (telemetry prefix glob),
// "<name>" (one telemetry counter).
// INTERCEPT_TIMER_NIC_MAX_MB=<mb> cap the RAM time series, default 256
// A wide, research-oriented default telemetry set. Names that are absent on a
// given NIC are silently skipped at open time, so this can over-list safely. The
// retry-handler side (NACKs, timeouts, resource occupancy) is covered here by the
// pct_* counters -- the hardware twins of the cxi_rh stats, read from sysfs so
// they don't lag the FUSE daemon -- and the default rh subset (kCuratedRh) adds
// back only what has no hardware equivalent.
static const char* const kCuratedTelem[] = {
// throughput: bytes (octets), tx flits, packets per traffic class
"hni_sts_tx_ok_octets", "hni_sts_rx_ok_octets", "cq_cq_oxe_num_flits",
"cq_cq_tou_num_flits", "hni_pkts_sent_by_tc_0", "hni_pkts_sent_by_tc_1",
"hni_pkts_sent_by_tc_2", "hni_pkts_sent_by_tc_3", "hni_pkts_sent_by_tc_4",
"hni_pkts_sent_by_tc_5", "hni_pkts_sent_by_tc_6", "hni_pkts_sent_by_tc_7",
"hni_pkts_recv_by_tc_0", "hni_pkts_recv_by_tc_1", "hni_pkts_recv_by_tc_2",
"hni_pkts_recv_by_tc_3", "hni_pkts_recv_by_tc_4", "hni_pkts_recv_by_tc_5",
"hni_pkts_recv_by_tc_6", "hni_pkts_recv_by_tc_7",
// pause / fine-grain flow control
"hni_pause_sent", "hni_pause_refresh", "hni_fgfc_event_xoff",
"hni_fgfc_event_xon", "hni_fgfc_discard",
// ECN marking
"ixe_pool_ecn_pkts_0", "ixe_pool_ecn_pkts_1", "ixe_pool_ecn_pkts_2",
"ixe_pool_ecn_pkts_3", "ixe_pool_no_ecn_pkts_0", "ixe_pool_no_ecn_pkts_1",
"ixe_pool_no_ecn_pkts_2", "ixe_pool_no_ecn_pkts_3",
// link-level retry (LLR)
"hni_llr_tx_replay_event", "hni_llr_rx_replay_event",
"hni_llr_tx_nack_ctl_os", "hni_llr_rx_nack_ctl_os",
"hni_llr_rx_ack_nack_seq_err",
// PCT timeouts / NACKs / retries. These are the hardware-side equivalents of
// the cxi_rh retry-handler stats (rh:spt_timeouts, rh:nack_sequence_error,
// rh:nack_resource_busy, ...) -- read straight from the NIC's sysfs telemetry,
// so they advance with the hardware instead of lagging behind the FUSE daemon
// that exports the rh: side. Prefer these over the rh: columns.
"pct_spt_timeouts", "pct_sct_timeouts", "pct_tct_timeouts",
"pct_rsp_dropped_timeout", "pct_bad_seq_nacks", "pct_no_mst_nacks",
"pct_no_tct_nacks", "pct_no_trs_nacks", "pct_resource_busy",
"pct_trs_rsp_nack_drops",
"pct_trs_replay_pend_drops", "pct_req_blocked_retry", "pct_req_no_response",
"pct_req_blocked_clearing", "pct_req_blocked_closing",
"pct_retry_srb_requests", "pct_retry_mst_get", "pct_retry_trs_put",
// PCT connection lifecycle & retry-recovery -- the edge that ENDS a stall and
// the replay-after-timeout path, the half the timeout/NACK counters above don't
// show. sct_stall_state = an ordered request (RCCL rendezvous) hit a stalled
// SCT and had to wait (head-of-line-stall onset); conn_*_open / close_sent /
// clear_sent = the teardown+reopen that recovers; clear_close_drop = the
// recovery path itself dropped to outbound-FIFO congestion (same family as
// trs_rsp_nack_drops, would explain a freeze outlasting one timeout);
// no_matching_tct / err_no_matching_{trs,mst} = a replay that landed after the
// target state was freed; req_tct_tmout_drops = the target's view of the freeze.
"pct_sct_stall_state", "pct_conn_sct_open", "pct_conn_tct_open",
"pct_close_sent", "pct_clear_sent", "pct_clear_close_drop",
"pct_no_matching_tct", "pct_err_no_matching_trs", "pct_err_no_matching_mst",
"pct_req_tct_tmout_drops",
// PCT resource occupancy (instantaneous + high-water). The hardware twins of
// the rh:*_in_use stats (spt/mst/sct/trs/tct/smt/srb).
"pct_prf_spt_status_spt_in_use", "pct_prf_spt_status_max_spt_in_use",
"pct_prf_mst_status_mst_in_use", "pct_prf_mst_status_max_mst_in_use",
"pct_prf_sct_status_sct_in_use", "pct_prf_sct_status_max_sct_in_use",
"pct_prf_trs_status_trs_in_use", "pct_prf_trs_status_max_trs_in_use",
"pct_prf_tct_status_tct_in_use", "pct_prf_tct_status_max_tct_in_use",
"pct_prf_smt_status_smt_in_use", "pct_prf_smt_status_max_smt_in_use",
"pct_prf_srb_status_srb_in_use", "pct_prf_srb_status_max_srb_in_use",
// inbound drops
"ixe_rx_pkt_drop_pct", "hni_discard_cntr_0", "hni_discard_cntr_1",
"hni_discard_cntr_2", "hni_discard_cntr_3", "hni_discard_cntr_4",
"hni_discard_cntr_5", "hni_discard_cntr_6", "hni_discard_cntr_7",
};
// The cxi_rh retry-handler stats worth keeping by default: the ones with NO
// hardware-telemetry twin. Timeouts, NACK types and resource occupancy are all
// covered by the pct_* counters above (which advance with the hardware instead
// of lagging the FUSE daemon, so we prefer them); what is left here -- the retry
// handler PARKING destinations after persistent failure, and its cancellations --
// is the retry handler's own reaction to congestion and exists nowhere else.
// Emitted as "rh:<name>" columns. The full rh set is still reachable on demand
// via INTERCEPT_TIMER_NIC_COUNTERS=rh: (or =all).
static const char* const kCuratedRh[] = {
"parked_nids", "max_parked_nids", "parked_switches",
"max_parked_switches", "connections_cancelled", "pkts_cancelled_o",
"pkts_cancelled_u", "nacks",
};
bool path_is_dir(const std::string& p) {
struct stat st;
return stat(p.c_str(), &st) == 0 && S_ISDIR(st.st_mode);
}
// Sorted regular-file names directly under `dir` (no recursion; subdirectories
// such as /run/cxi/<dev>/config are skipped). Empty if `dir` can't be opened.
std::vector<std::string> list_regular_files(const std::string& dir) {
std::vector<std::string> out;
DIR* d = opendir(dir.c_str());
if (!d) return out;
while (struct dirent* e = readdir(d)) {
if (e->d_name[0] == '.') continue;
if (path_is_dir(dir + "/" + e->d_name)) continue;
out.emplace_back(e->d_name);
}
closedir(d);
std::sort(out.begin(), out.end());
return out;
}
// The cxi devices present, "cxi<N>" (digits only, excludes e.g. cxi_user).
std::vector<std::string> list_cxi_devices() {
std::vector<std::string> out;
DIR* d = opendir("/sys/class/cxi");
if (!d) return out;
while (struct dirent* e = readdir(d)) {
const char* n = e->d_name;
if (std::strncmp(n, "cxi", 3) != 0 || !n[3]) continue;
bool digits = true;
for (const char* p = n + 3; *p; ++p)
if (!std::isdigit(static_cast<unsigned char>(*p))) { digits = false; break; }
if (digits) out.emplace_back(n);
}
closedir(d);
std::sort(out.begin(), out.end());
return out;
}
class nic_sampler {
public:
nic_sampler() {
const char* e = getenv("INTERCEPT_TIMER_NIC");
enabled_ = !(e && std::strcmp(e, "0") == 0);
if (const char* v = getenv("INTERCEPT_TIMER_NIC_MS")) {
char* end;
long m = std::strtol(v, &end, 10);
if (end != v && m > 0) interval_ms_ = static_cast<int>(m);
}
if (const char* v = getenv("INTERCEPT_TIMER_NIC_MAX_MB")) {
char* end;
long m = std::strtol(v, &end, 10);
if (end != v && m > 0) max_mb_ = static_cast<uint64_t>(m);
}
}
// Start the sampling thread exactly once, sharing the tool's clock anchor so
// sample timestamps line up with the per-op CSV. Idempotent and thread-safe:
// the first caller wins the CAS and spawns the thread; everyone else returns.
void start(time_point anchor, uint64_t anchor_wall_ns) {
bool expected = false;
if (!started_.compare_exchange_strong(expected, true)) return;
if (!enabled_) return;
anchor_ = anchor;
anchor_wall_ns_ = anchor_wall_ns;
open_counters();
if (labels_.empty()) return;
// Reserve the WHOLE cap up front rather than growing. At the default 100 ms
// the growth reallocs are invisible, but at a 1 ms cadence the series passes
// 16k samples in 16 s and every later realloc copies (and so touches) up to
// MAX_MB of pages inside a sample period -- a self-inflicted gap in the very
// time series you are sampling. The reservation is virtual; only the samples
// actually taken are ever touched.
rows_.reserve(max_samples_ * stride_);
thread_ = std::thread([this] { run(); });
}
~nic_sampler() {
if (thread_.joinable()) {
{
std::lock_guard<std::mutex> lk(mtx_);
stop_ = true;
}
cv_.notify_all();
thread_.join();
}
dump();
for (int fd : fds_)
if (fd >= 0) close(fd);
}
private:
static uint64_t realtime_ns() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return static_cast<uint64_t>(ts.tv_sec) * 1000000000ULL + ts.tv_nsec;
}
uint64_t ns_since_anchor(time_point t) {
return static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(t - anchor_)
.count());
}
static std::string read_first_line(const std::string& path) {
int fd = open(path.c_str(), O_RDONLY);
if (fd < 0) return "";
char buf[128];
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) return "";
buf[n] = '\0';
if (char* nl = std::strchr(buf, '\n')) *nl = '\0';
return buf;
}
static long local_id() {
static const char* const keys[] = {
"SLURM_LOCALID", "MPI_LOCALRANKID", "OMPI_COMM_WORLD_LOCAL_RANK",
"PMI_LOCAL_RANK", "FLUX_TASK_LOCAL_ID"};
for (const char* k : keys)
if (const char* v = getenv(k)) {
char* e;
long r = std::strtol(v, &e, 10);
if (e != v) return r;
}
return -1;
}
static std::vector<std::string> split_csv(const std::string& s) {
std::vector<std::string> out;
size_t i = 0;
while (i < s.size()) {
size_t j = s.find(',', i);
if (j == std::string::npos) j = s.size();
size_t a = i, b = j;
while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;
while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;
if (b > a) out.push_back(s.substr(a, b - a));
i = j + 1;
}
return out;
}
std::vector<std::string> resolve_devices() {
std::vector<std::string> all = list_cxi_devices();
const char* spec = getenv("INTERCEPT_TIMER_NIC_DEV");
if (spec && *spec) {
std::string s = spec;
if (s == "all") return all;
std::vector<std::string> out;
for (const std::string& tok : split_csv(s))
if (path_is_dir("/sys/class/cxi/" + tok)) out.push_back(tok);
if (!out.empty()) return out;
return all; // nothing matched: fall back to every NIC present
}
long lid = local_id();
if (lid >= 0) {
std::string dev = "cxi" + std::to_string(lid);
if (path_is_dir("/sys/class/cxi/" + dev)) return {dev};
}
return all; // no local id (or its device absent): sample every NIC present
}
// Open one counter file and register its column. Deduped by label, and skipped
// silently if the file is missing/unreadable (a curated name absent on this
// NIC, an rh stat with the daemon down, ...).
void add_counter(const std::string& label, const std::string& path) {
if (!seen_.insert(label).second) return;
int fd = open(path.c_str(), O_RDONLY);
if (fd < 0) return;
labels_.push_back(label);
fds_.push_back(fd);
}
void open_counters() {
devices_ = resolve_devices();
const char* spec = getenv("INTERCEPT_TIMER_NIC_COUNTERS");
std::string sel = spec ? spec : "";
for (const std::string& dev : devices_) {
const std::string tdir = "/sys/class/cxi/" + dev + "/device/telemetry";
const std::string rdir = "/run/cxi/" + dev;
if (sel.empty()) { // default: wide curated telemetry + curated rh stats
for (const char* name : kCuratedTelem)
add_counter(dev + ":" + name, tdir + "/" + name);
for (const char* name : kCuratedRh)
add_counter(dev + ":rh:" + name, rdir + "/" + name);
continue;
}
for (const std::string& tok : split_csv(sel)) {
if (tok == "all") {
for (const std::string& n : list_regular_files(tdir))
add_counter(dev + ":" + n, tdir + "/" + n);
for (const std::string& n : list_regular_files(rdir))
add_counter(dev + ":rh:" + n, rdir + "/" + n);
} else if (tok == "rh:" || tok == "rh:*") {
for (const std::string& n : list_regular_files(rdir))
add_counter(dev + ":rh:" + n, rdir + "/" + n);
} else if (tok.rfind("rh:", 0) == 0) {
add_counter(dev + ":" + tok, rdir + "/" + tok.substr(3));
} else if (tok.back() == '*') {
std::string pre = tok.substr(0, tok.size() - 1);
for (const std::string& n : list_regular_files(tdir))
if (n.rfind(pre, 0) == 0) add_counter(dev + ":" + n, tdir + "/" + n);
} else {
add_counter(dev + ":" + tok, tdir + "/" + tok);
}
}
}
stride_ = labels_.size() + 2; // t_ns, wall_ns, then one column per counter
uint64_t cap_bytes = max_mb_ << 20;
max_samples_ =
stride_ ? std::max<uint64_t>(1, cap_bytes / (stride_ * sizeof(uint64_t)))
: 0;
}
void sample_once() {
if (nsamples_ >= max_samples_) {
++dropped_;
return;
}
uint64_t t = ns_since_anchor(clock_type::now());
uint64_t w = realtime_ns();
size_t base = rows_.size();
rows_.resize(base + stride_);
rows_[base] = t;
rows_[base + 1] = w;
char buf[64];
for (size_t i = 0; i < fds_.size(); ++i) {
uint64_t v = 0;
ssize_t n = pread(fds_[i], buf, sizeof(buf) - 1, 0);
if (n > 0) {
buf[n] = '\0';
v = std::strtoull(buf, nullptr, 10); // stops at '@' or '\n'
}
rows_[base + 2 + i] = v;
}
++nsamples_;
}
void run() {
auto period = std::chrono::milliseconds(interval_ms_);
auto next = clock_type::now();
std::unique_lock<std::mutex> lk(mtx_);
while (!stop_) {
lk.unlock();
sample_once(); // only this thread writes the series; no lock needed
lk.lock();
next += period;
cv_.wait_until(lk, next, [this] { return stop_; });
}
}
void dump() {
if (!enabled_ || labels_.empty() || nsamples_ == 0) return;
char host[65] = {0};
if (gethostname(host, sizeof(host) - 1) != 0) std::strcpy(host, "?");
std::string rank = detect_rank();
long pid = static_cast<long>(getpid());
const char* dir = getenv("INTERCEPT_TIMER_DIR");
bool to_stderr =
dir && (std::strcmp(dir, "stderr") == 0 || std::strcmp(dir, "-") == 0);
char path[600];
snprintf(path, sizeof(path), "%s/intercept_timer_nic.%s.r%s.p%ld.csv",
(dir && !to_stderr) ? dir : ".", host, rank.c_str(), pid);
FILE* f = fopen(path, "w");
if (!f) {
fprintf(stderr, "[intercept_timer] could not open %s for NIC counters\n",
path);
return;
}
static char iobuf[1 << 20];
setvbuf(f, iobuf, _IOFBF, sizeof(iobuf));
std::string devs;
for (size_t i = 0; i < devices_.size(); ++i)
devs += (i ? "," : "") + devices_[i];
fprintf(f, "# intercept_timer NIC counters host=%s rank=%s pid=%ld\n", host,
rank.c_str(), pid);
// Achieved cadence: one sample costs a pread per counter (each sysfs
// telemetry read is a fresh hardware read), so a small interval_ms_ can be
// unmeetable. Compare requested vs achieved before reading the series as a
// fixed-rate signal -- if achieved > requested the thread is running flat
// out and the real cadence is whatever this line says.
double span_ms = nsamples_ > 1
? (rows_[(nsamples_ - 1) * stride_] - rows_[0]) / 1e6
: 0.0;
fprintf(f,
"# interval_ms=%d achieved_mean_ms=%.3f devices=%s counters=%zu "
"samples=%llu\n",
interval_ms_, nsamples_ > 1 ? span_ms / (nsamples_ - 1) : 0.0,
devs.c_str(), labels_.size(),
static_cast<unsigned long long>(nsamples_));
fprintf(f,
"# t_ns = ns since this rank's clock anchor (same anchor as the "
"per-op CSV); wall_ns = CLOCK_REALTIME for cross-rank alignment\n");
fprintf(f,
"# anchor_mono_ns=%llu anchor_wall_ns=%llu (t_ns clock = "
"std::chrono::steady_clock; t_ns = steady_ns - anchor_mono_ns; "
"wall = steady_ns + (anchor_wall_ns - anchor_mono_ns))\n",
static_cast<unsigned long long>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
anchor_.time_since_epoch())
.count()),
static_cast<unsigned long long>(anchor_wall_ns_));
for (const std::string& dev : devices_) {
std::string na =
read_first_line("/sys/class/cxi/" + dev + "/device/properties/nic_addr");
std::string nid =
read_first_line("/sys/class/cxi/" + dev + "/device/properties/nid");
fprintf(f, "# dev %s nic_addr=%s nid=%s\n", dev.c_str(),
na.empty() ? "?" : na.c_str(), nid.empty() ? "?" : nid.c_str());
}
fputs("t_ns,wall_ns", f);
for (const std::string& l : labels_) {
fputc(',', f);
fputs(l.c_str(), f);
}
fputc('\n', f);
for (uint64_t s = 0; s < nsamples_; ++s) {
const uint64_t* row = &rows_[s * stride_];
fprintf(f, "%llu,%llu", static_cast<unsigned long long>(row[0]),
static_cast<unsigned long long>(row[1]));
for (size_t i = 0; i < labels_.size(); ++i)
fprintf(f, ",%llu", static_cast<unsigned long long>(row[2 + i]));
fputc('\n', f);
}
fclose(f);
fprintf(stderr,
"[intercept_timer] %s rank %s NIC counters -> %s "
"(%llu samples x %zu counters)\n",
host, rank.c_str(), path,
static_cast<unsigned long long>(nsamples_), labels_.size());
if (dropped_)
fprintf(stderr,
"[intercept_timer] WARNING: %llu NIC samples dropped (RAM cap); "
"raise INTERCEPT_TIMER_NIC_MAX_MB\n",
static_cast<unsigned long long>(dropped_));
}
// ---- config (read in the constructor) ----
bool enabled_ = true;
int interval_ms_ = 100;
uint64_t max_mb_ = 256;
// ---- resolved at start() ----
time_point anchor_{};
uint64_t anchor_wall_ns_ = 0;
std::vector<std::string> devices_;
std::vector<std::string> labels_; // column names, parallel to fds_
std::vector<int> fds_;
std::unordered_set<std::string> seen_; // label dedup during open
size_t stride_ = 0; // uint64s per sample (2 + #counters)
uint64_t max_samples_ = 0;
// ---- time series: sample-major, stride_ uint64s each (t_ns, wall_ns, ...) ----
std::vector<uint64_t> rows_;
uint64_t nsamples_ = 0;
uint64_t dropped_ = 0;
// ---- thread control ----
std::atomic<bool> started_{false};
bool stop_ = false;
std::mutex mtx_;
std::condition_variable cv_;
std::thread thread_;
};
struct state {
std::atomic<uint64_t> seq{0};
std::atomic<uint64_t> dropped{0};
op_record ring[kMaxInflight];
// CQ poll-gap registry. Slots are appended (never freed) by cq_open or on
// first sight of an unknown CQ in a poll; lookup is a short linear scan.
const time_point anchor = clock_type::now();
// CLOCK_REALTIME captured at (essentially) the same instant as `anchor`. We
// publish BOTH the steady-clock anchor (anchor_mono_ns) and this wall value in
// the CSV headers -- "recording the anchor" -- so a SAME-PROCESS consumer that
// stamps events with the identical std::chrono::steady_clock (e.g. the
// iter_timeline all-to-all boundaries) maps them onto t_ns by exact subtraction:
// t_ns(event) = event_steady_ns - anchor_mono_ns()
// and onto the global wall clock (cross-rank) by adding the constant
// (anchor_wall_ns - anchor_mono_ns). No NIC-sample fitting, no NTP slew.
const uint64_t anchor_wall_ns = [] {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return static_cast<uint64_t>(ts.tv_sec) * 1000000000ULL + ts.tv_nsec;
}();
uint64_t anchor_mono_ns() const {
return static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(
anchor.time_since_epoch())
.count());
}
const bool cqgap_on = cqgap_env_on();
cq_gap cq_gaps[kMaxCqs];
std::atomic<size_t> ncqs{0};
uint64_t ns_since_anchor(time_point t) {
return static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::nanoseconds>(t - anchor)
.count());
}
cq_gap* gap_for(struct fid_cq* cq) {
size_t n = ncqs.load(std::memory_order_acquire);
for (size_t i = 0; i < n; ++i)
if (cq_gaps[i].cq.load(std::memory_order_relaxed) == cq)
return &cq_gaps[i];
// Unknown CQ: append (first poll of a CQ races benignly; one slot wins,
// losers find it on their next scan and this poll goes uncounted).
size_t i = ncqs.load(std::memory_order_relaxed);
if (i >= kMaxCqs) return nullptr;
struct fid_cq* expected = nullptr;
if (cq_gaps[i].cq.compare_exchange_strong(expected, cq,
std::memory_order_relaxed)) {
ncqs.store(i + 1, std::memory_order_release);
return &cq_gaps[i];
}