-
Notifications
You must be signed in to change notification settings - Fork 63
Expand file tree
/
Copy pathbackend_impl.cpp
More file actions
1552 lines (1374 loc) · 59.5 KB
/
Copy pathbackend_impl.cpp
File metadata and controls
1552 lines (1374 loc) · 59.5 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
// Copyright © Advanced Micro Devices, Inc. All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "src/io/rdma/backend_impl.hpp"
#include <infiniband/verbs.h> // dereferences ibvHandle.qp/cq/compCh (forward-declared in core)
#include <sys/epoll.h>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <memory>
#include <optional>
#include <shared_mutex>
#include <stdexcept>
#include <string>
#include "mori/io/env.hpp"
#include "mori/io/logging.hpp"
#include "src/io/rdma/protocol.hpp"
namespace mori {
namespace io {
static void ValidateRdmaNotificationConfig(const RdmaBackendConfig& config) {
if (config.enableNotification && config.notifPerQp == 0) {
MORI_IO_ERROR(
"Invalid RDMA config: notifPerQp must be >= 1 when notification is enabled; got {}",
config.notifPerQp);
throw std::runtime_error(
"Invalid RDMA config: notifPerQp must be >= 1 when notification is "
"enabled");
}
}
void ValidateRdmaTransferConfig(const RdmaBackendConfig& config) {
if (config.maxChunksPerTransfer < 1) {
MORI_IO_ERROR("Invalid RDMA config: maxChunksPerTransfer must be >= 1; got {}",
config.maxChunksPerTransfer);
throw std::runtime_error("Invalid RDMA config: maxChunksPerTransfer must be >= 1");
}
if (config.numNicsPerTransfer < 1) {
MORI_IO_ERROR("Invalid RDMA config: numNicsPerTransfer must be >= 1; got {}",
config.numNicsPerTransfer);
throw std::runtime_error("Invalid RDMA config: numNicsPerTransfer must be >= 1");
}
if (config.enableTransferChunking && config.chunkBytes < 4096) {
MORI_IO_ERROR(
"Invalid RDMA config: chunkBytes must be >= 4096 when chunking is enabled; got {}",
config.chunkBytes);
throw std::runtime_error(
"Invalid RDMA config: chunkBytes must be >= 4096 when chunking is enabled");
}
}
bool UsesInlineOnly(const RdmaBackendConfig& config) {
return config.enableTransferChunking || config.numNicsPerTransfer > 1;
}
// Parse MORI_IO_POLL_CQ_MODE: "0"/"polling" or "1"/"event" (case-insensitive).
// Returns nullopt for anything else so env::Override warns and keeps the
// config value (no silent fallback).
std::optional<PollCqMode> ParsePollCqMode(const char* raw) {
if (std::strcmp(raw, "0") == 0 || mori::env::detail::EqualsIgnoreCase(raw, "polling")) {
return PollCqMode::POLLING;
}
if (std::strcmp(raw, "1") == 0 || mori::env::detail::EqualsIgnoreCase(raw, "event")) {
return PollCqMode::EVENT;
}
return std::nullopt;
}
// Parse MORI_IO_POST_BATCH_SIZE: only -1 (auto) or a positive int are valid.
// Rejects 0 / negatives (which the post path would silently clamp to 1) so
// env::Override warns and keeps the config value.
std::optional<int> ParsePostBatchSize(const char* raw) {
if (std::strcmp(raw, "-1") == 0) return -1;
return mori::env::detail::ParsePositiveInt(raw);
}
int ResolveRequestedNics(const RdmaBackendConfig& config, const TopoKey& local,
const TopoKey& remote) {
if (local.loc == MemoryLocationType::GPU || remote.loc == MemoryLocationType::GPU) {
return 1;
}
return std::max(1, config.numNicsPerTransfer);
}
enum class CqeFailureOrigin : uint8_t {
BatchTransfer = 0,
NotificationSend,
NotificationRecv,
Unknown,
};
struct CqeFailureAdvice {
const char* statusText{nullptr};
std::string hint;
bool HasHint() const { return !hint.empty(); }
std::string ComposeStatusMessage() const {
std::string message = statusText != nullptr ? statusText : "unknown";
if (hint.empty()) return message;
message += " Hint: ";
message += hint;
return message;
}
};
static void LogAsyncTransferFailureIfNeeded(internal::IoCallDiagnostics* diagnostics, uint32_t code,
const std::string& message) {
if (diagnostics == nullptr || diagnostics->Label() == nullptr) return;
internal::IoFailureKind failureKind = diagnostics->CurrentFailureKind();
if (failureKind != internal::IoFailureKind::FlushCascade ||
!diagnostics->TryMarkLogged(failureKind)) {
return;
}
MORI_IO_DEBUG("{} error {} message {}", diagnostics->Label(), code, message);
}
static CqeFailureOrigin ClassifyCqeFailureOrigin(uint64_t wrId, uint32_t notifPerQp) {
if (IsNotifSendWrId(wrId)) return CqeFailureOrigin::NotificationSend;
if (wrId < notifPerQp) return CqeFailureOrigin::NotificationRecv;
return CqeFailureOrigin::BatchTransfer;
}
static CqeFailureAdvice DescribeCqeFailure(ibv_wc_status status, CqeFailureOrigin origin,
const RdmaBackendConfig& config) {
CqeFailureAdvice advice{ibv_wc_status_str(status), {}};
switch (status) {
case IBV_WC_RETRY_EXC_ERR:
advice.hint =
"transport retry limit exceeded; check peer liveness/connectivity, verify GID "
"selection (unset or correct MORI_IB_GID_INDEX), and if running RoCE verify QoS "
"settings such as MORI_IO_SL/MORI_IO_TC or MORI_RDMA_SL/MORI_RDMA_TC.";
break;
case IBV_WC_RNR_RETRY_EXC_ERR:
if (origin == CqeFailureOrigin::NotificationSend) {
advice.hint =
"receiver not ready for SEND completions; if notifications are enabled, ensure the "
"peer pre-posts enough RECV WRs. Try increasing notifPerQp / MORI_IO_QP_MAX_RECV_WR "
"(current notifPerQp=" +
std::to_string(config.notifPerQp) +
"), or set MORI_IO_ENABLE_NOTIFICATION=0 if inbound notification is not required.";
} else {
advice.hint =
"receiver not ready; check the peer receive path. If this is related to MORI "
"notifications, increase notifPerQp / MORI_IO_QP_MAX_RECV_WR or disable "
"MORI_IO_ENABLE_NOTIFICATION when inbound notification is not required.";
}
break;
case IBV_WC_LOC_PROT_ERR:
advice.hint =
"local protection error; verify the local buffer is still registered with MORI, lkey "
"matches the posted WR, and transfer offsets/lengths stay within the registered range.";
break;
case IBV_WC_LOC_LEN_ERR:
advice.hint =
"local length error; verify SGE lengths and transfer offsets stay within the registered "
"local MR bounds.";
break;
case IBV_WC_REM_ACCESS_ERR:
advice.hint =
"remote access error; verify the remote buffer is still registered, rkey/permissions "
"allow this operation, and remote offsets/lengths stay within the registered range.";
break;
case IBV_WC_REM_OP_ERR:
advice.hint =
"remote operation error; verify both peers use compatible verbs/QP state and the remote "
"endpoint supports the requested RDMA operation.";
break;
default:
break;
}
return advice;
}
/* ---------------------------------------------------------------------------------------------- */
/* RdmaManager */
/* ---------------------------------------------------------------------------------------------- */
RdmaManager::RdmaManager(const RdmaBackendConfig cfg, application::RdmaContext* ctx)
: config(cfg), ctx(ctx) {
application::RdmaDeviceList devices = ctx->GetRdmaDeviceList();
availDevices = GetActiveDevicePortList(devices);
if (availDevices.empty()) {
throw std::runtime_error("RdmaManager: no active RDMA device/port found");
}
deviceCtxs.resize(availDevices.size(), nullptr);
topo.reset(new application::TopoSystem());
}
RdmaManager::~RdmaManager() {
for (auto* devCtx : deviceCtxs) {
if (devCtx != nullptr) {
delete devCtx;
}
}
deviceCtxs.clear();
if (ctx != nullptr) {
delete ctx;
ctx = nullptr;
}
}
std::vector<std::pair<int, int>> RdmaManager::Search(TopoKey key, int requestedNics) {
if (requestedNics <= 0) {
requestedNics = std::max(1, config.numNicsPerTransfer);
}
if (key.loc == MemoryLocationType::GPU) {
std::vector<std::string> nicNames;
if (requestedNics == 1) {
std::string nicName = topo->MatchGpuAndNic(key.deviceId);
if (!nicName.empty()) nicNames.push_back(std::move(nicName));
} else {
nicNames = topo->MatchGpuAndNics(key.deviceId, requestedNics);
}
std::vector<std::pair<int, int>> matches;
matches.reserve(nicNames.size());
for (const auto& nicName : nicNames) {
for (int i = 0; i < availDevices.size(); i++) {
if (availDevices[i].first->Name() == nicName) {
matches.push_back({i, 1});
break;
}
}
}
if (!matches.empty()) return matches;
MORI_IO_WARN("No matching NIC found for GPU {}", key.deviceId);
} else if (key.loc == MemoryLocationType::CPU) {
if (availDevices.empty()) return {};
const char* envNic = std::getenv("MORI_IO_RDMA_NIC_IDX");
if (envNic) {
if (requestedNics > 1) {
MORI_IO_WARN("MORI_IO_RDMA_NIC_IDX pins a single NIC; multi-NIC selection is disabled");
}
int idx = std::atoi(envNic);
if (idx >= 0 && idx < static_cast<int>(availDevices.size())) {
return {{idx, 1}};
}
MORI_IO_WARN("MORI_IO_RDMA_NIC_IDX={} out of range [0, {}), falling back to round-robin", idx,
availDevices.size());
}
if (requestedNics == 1) {
int idx = (roundRobinCounter.fetch_add(1, std::memory_order_relaxed) % availDevices.size());
return {{idx, 1}};
}
std::vector<std::string> nicNames = topo->MatchCpuNics(key.numaNode, requestedNics);
std::vector<std::pair<int, int>> matches;
matches.reserve(nicNames.size());
for (const auto& nicName : nicNames) {
for (int i = 0; i < availDevices.size(); i++) {
if (availDevices[i].first->Name() == nicName) {
matches.push_back({i, 1});
break;
}
}
}
if (!matches.empty()) return matches;
MORI_IO_WARN("No matching NIC found for CPU numa node {}", key.numaNode);
}
MORI_IO_ERROR(
"topo searching for device other than CPU/GPU is not implemented yet, returning default "
"device 0");
return {{0, 1}};
}
/* ----------------------------------- Local Memory Management ---------------------------------- */
std::optional<application::RdmaMemoryRegion> RdmaManager::GetLocalMemory(int devId,
MemoryUniqueId id) {
std::shared_lock<std::shared_mutex> lock(mu);
MemoryKey key{devId, id};
if (mTable.find(key) == mTable.end()) return std::nullopt;
return mTable.at(key);
}
application::RdmaMemoryRegion RdmaManager::RegisterLocalMemory(int devId, const MemoryDesc& desc) {
std::unique_lock<std::shared_mutex> lock(mu);
MemoryKey key{devId, desc.id};
application::RdmaDeviceContext* devCtx = GetOrCreateDeviceContext(devId);
mTable[key] = devCtx->RegisterRdmaMemoryRegion(reinterpret_cast<void*>(desc.data), desc.size);
return mTable[key];
}
void RdmaManager::DeregisterLocalMemory(int devId, const MemoryDesc& desc) {
std::unique_lock<std::shared_mutex> lock(mu);
MemoryKey key{devId, desc.id};
if (mTable.find(key) != mTable.end()) {
deviceCtxs[devId]->DeregisterRdmaMemoryRegion(reinterpret_cast<void*>(desc.data));
mTable.erase(key);
}
}
void RdmaManager::DeregisterLocalMemory(const MemoryDesc& desc) {
std::unique_lock<std::shared_mutex> lock(mu);
std::vector<MemoryKey> keysToErase;
keysToErase.reserve(mTable.size());
for (const auto& [key, _] : mTable) {
if (key.id == desc.id) keysToErase.push_back(key);
}
for (const auto& key : keysToErase) {
auto it = mTable.find(key);
if (it == mTable.end()) continue;
if (key.devId >= 0 && key.devId < static_cast<int>(deviceCtxs.size()) &&
deviceCtxs[key.devId] != nullptr) {
deviceCtxs[key.devId]->DeregisterRdmaMemoryRegion(reinterpret_cast<void*>(desc.data));
}
mTable.erase(it);
}
}
/* ---------------------------------- Remote Memory Management ---------------------------------- */
std::optional<application::RdmaMemoryRegion> RdmaManager::GetRemoteMemory(EngineKey ekey,
int remRdmaDevId,
MemoryUniqueId id) {
std::shared_lock<std::shared_mutex> lock(mu);
auto remoteIt = remotes.find(ekey);
if (remoteIt == remotes.end()) return std::nullopt;
MemoryKey key{remRdmaDevId, id};
const RemoteEngineMeta& remote = remoteIt->second;
if (remote.mTable.find(key) == remote.mTable.end()) {
return std::nullopt;
}
return remote.mTable.at(key);
}
void RdmaManager::RegisterRemoteMemory(EngineKey ekey, int remRdmaDevId, MemoryUniqueId id,
application::RdmaMemoryRegion mr) {
std::unique_lock<std::shared_mutex> lock(mu);
MemoryKey key{remRdmaDevId, id};
RemoteEngineMeta& remote = remotes[ekey];
remote.mTable[key] = mr;
}
void RdmaManager::DeregisterRemoteMemory(EngineKey ekey, int remRdmaDevId, MemoryUniqueId id) {
std::unique_lock<std::shared_mutex> lock(mu);
RemoteEngineMeta& remote = remotes[ekey];
MemoryKey key{remRdmaDevId, id};
if (remote.mTable.find(key) != remote.mTable.end()) {
remote.mTable.erase(key);
}
}
/* ------------------------------------- Endpoint Management ------------------------------------ */
int RdmaManager::CountEndpoint(EngineKey engine, TopoKeyPair key) {
std::shared_lock<std::shared_mutex> lock(mu);
auto remoteIt = remotes.find(engine);
if (remoteIt == remotes.end()) return 0;
auto tableIt = remoteIt->second.rTable.find(key);
if (tableIt == remoteIt->second.rTable.end()) return 0;
return tableIt->second.size();
}
EpPairVec RdmaManager::GetAllEndpoint(EngineKey engine, TopoKeyPair key) {
std::shared_lock<std::shared_mutex> lock(mu);
auto remoteIt = remotes.find(engine);
if (remoteIt == remotes.end()) return {};
auto tableIt = remoteIt->second.rTable.find(key);
if (tableIt == remoteIt->second.rTable.end()) return {};
return tableIt->second;
}
application::RdmaEndpointConfig RdmaManager::GetRdmaEndpointConfig(int devId) {
const auto& [device, portId] = availDevices[devId];
const auto* deviceAttr = device->GetDeviceAttr();
application::RdmaEndpointConfig epConfig{};
epConfig.portId = portId;
epConfig.gidIdx = -1;
const char* envGidIdx = std::getenv("MORI_IB_GID_INDEX");
if (envGidIdx != nullptr) {
epConfig.gidIdx = std::atoi(envGidIdx);
}
epConfig.enableSrq = false;
epConfig.alignment = PAGESIZE;
epConfig.withCompChannel = (config.pollCqMode == PollCqMode::EVENT);
bool is_ionic = (deviceAttr->orig_attr.vendor_id ==
static_cast<uint32_t>(application::RdmaDeviceVendorId::Pensando));
uint32_t maxQpWr = static_cast<uint32_t>(deviceAttr->orig_attr.max_qp_wr);
uint32_t maxCqe = static_cast<uint32_t>(deviceAttr->orig_attr.max_cqe);
uint32_t maxSge = static_cast<uint32_t>(deviceAttr->orig_attr.max_sge);
if (is_ionic) maxSge = std::min(maxSge, 2u);
if (config.enableNotification && maxQpWr < config.notifPerQp) {
MORI_IO_ERROR(
"Device max_qp_wr={} is less than notifPerQp={}; notification requires at least "
"notifPerQp RQ slots. Either reduce notifPerQp or disable notification.",
maxQpWr, config.notifPerQp);
throw std::runtime_error("Device RQ capacity insufficient for configured notifPerQp");
}
uint32_t desiredSendWr = config.maxSendWr > 0 ? static_cast<uint32_t>(config.maxSendWr) : 8192u;
uint32_t desiredRecvWr = config.enableNotification ? config.notifPerQp : 0u;
uint32_t desiredCqe = config.maxCqeNum > 0 ? static_cast<uint32_t>(config.maxCqeNum) : 16384u;
std::optional<uint32_t> desiredMsgSge =
config.maxMsgSge > 0 ? std::optional<uint32_t>(static_cast<uint32_t>(config.maxMsgSge))
: std::nullopt;
env::Override("MORI_IO_QP_MAX_SEND_WR", desiredSendWr, mori::env::detail::ParsePositiveU32);
env::Override("MORI_IO_QP_MAX_RECV_WR", desiredRecvWr, mori::env::detail::ParsePositiveU32);
env::Override("MORI_IO_QP_MAX_CQE", desiredCqe, mori::env::detail::ParsePositiveU32);
env::Override("MORI_IO_QP_MAX_MSG_SGE", desiredMsgSge, mori::env::detail::ParsePositiveU32);
// Alias for convenience: keep both MORI_IO_QP_MAX_MSG_SGE and MORI_IO_QP_MAX_SGE.
env::Override("MORI_IO_QP_MAX_SGE", desiredMsgSge, mori::env::detail::ParsePositiveU32);
if (config.enableNotification && desiredRecvWr < config.notifPerQp) {
MORI_IO_WARN("MORI_IO_QP_MAX_RECV_WR={} is less than notifPerQp={}; clamping to notifPerQp",
desiredRecvWr, config.notifPerQp);
desiredRecvWr = config.notifPerQp;
}
epConfig.maxMsgsNum = std::min(desiredSendWr, maxQpWr);
// RQ must fit NotifManager's pre-posted recv WQEs (config.notifPerQp) when notification is
// enabled. MORI_IO_QP_MAX_RECV_WR can raise this baseline, but not lower it.
epConfig.maxRecvWr = desiredRecvWr > 0 ? std::min(desiredRecvWr, maxQpWr) : 0;
epConfig.maxCqeNum = std::min(desiredCqe, maxCqe);
uint32_t minRequiredCqe = epConfig.maxMsgsNum + epConfig.maxRecvWr;
if (epConfig.maxCqeNum < minRequiredCqe) {
uint32_t newCqeNum = std::min(minRequiredCqe, maxCqe);
MORI_IO_WARN(
"maxCqeNum ({}) is smaller than SQ+RQ depth ({}+{}={}); increasing maxCqeNum to {}",
epConfig.maxCqeNum, epConfig.maxMsgsNum, epConfig.maxRecvWr, minRequiredCqe, newCqeNum);
epConfig.maxCqeNum = newCqeNum;
}
if (desiredMsgSge.has_value()) {
if (*desiredMsgSge > maxSge) {
MORI_IO_WARN("maxMsgSge={} is greater than max_sge={}; clamping to max_sge", *desiredMsgSge,
maxSge);
*desiredMsgSge = maxSge;
}
epConfig.maxMsgSge = *desiredMsgSge;
} else {
epConfig.maxMsgSge = std::min(maxSge, is_ionic ? 2u : 4u);
}
// Inline capacity for the small notification SEND (NotifMessage). Providers such as
// bnxt_re reject IBV_SEND_INLINE with ENOMEM unless the QP was created with enough
// max_inline_data, so request a small but sufficient amount here.
uint32_t desiredInline = config.enableNotification ? 64u : 0u;
env::Override("MORI_IO_QP_MAX_INLINE_DATA", desiredInline, mori::env::detail::ParsePositiveU32);
epConfig.maxInlineData = desiredInline;
return epConfig;
}
application::RdmaEndpoint RdmaManager::CreateEndpoint(int devId) {
std::unique_lock<std::shared_mutex> lock(mu);
application::RdmaDeviceContext* devCtx = GetOrCreateDeviceContext(devId);
application::RdmaEndpoint rdmaEp = devCtx->CreateRdmaEndpoint(GetRdmaEndpointConfig(devId));
if (config.pollCqMode == PollCqMode::EVENT)
SYSCALL_RETURN_ZERO(ibv_req_notify_cq(rdmaEp.ibvHandle.cq, 0));
return rdmaEp;
}
EndpointId RdmaManager::ConnectEndpoint(EngineKey remoteKey, int devId,
application::RdmaEndpoint local, int rdevId,
application::RdmaEndpointHandle remote, TopoKeyPair topoKey,
int weight) {
std::unique_lock<std::shared_mutex> lock(mu);
deviceCtxs[devId]->ConnectEndpoint(local.handle, remote);
RemoteEngineMeta& meta = remotes[remoteKey];
auto epConfig = GetRdmaEndpointConfig(devId);
EpPair ep{weight,
devId,
rdevId,
remoteKey,
local,
remote,
std::make_shared<std::atomic<int>>(0),
static_cast<int>(epConfig.maxMsgsNum),
std::make_shared<std::atomic<bool>>(false),
std::make_shared<SubmissionLedger>(config.notifPerQp)};
meta.rTable[topoKey].push_back(ep);
EndpointId id = nextEndpointId_.fetch_add(1);
auto rt = std::make_shared<EndpointRuntime>(id, ep);
endpointsById_[id] = rt;
return id;
}
std::shared_ptr<EndpointRuntime> RdmaManager::GetEndpointRuntime(EndpointId id) {
std::shared_lock<std::shared_mutex> lock(mu);
auto it = endpointsById_.find(id);
if (it == endpointsById_.end()) return nullptr;
return it->second;
}
application::RdmaDeviceContext* RdmaManager::GetRdmaDeviceContext(int devId) {
std::shared_lock<std::shared_mutex> lock(mu);
return deviceCtxs[devId];
}
std::vector<std::shared_ptr<EndpointRuntime>> RdmaManager::SnapshotEndpointRuntimes() {
std::shared_lock<std::shared_mutex> lock(mu);
std::vector<std::shared_ptr<EndpointRuntime>> result;
result.reserve(endpointsById_.size());
for (auto& [_, rt] : endpointsById_) {
result.push_back(rt);
}
return result;
}
application::RdmaDeviceContext* RdmaManager::GetOrCreateDeviceContext(int devId) {
assert(devId < deviceCtxs.size());
application::RdmaDeviceContext* devCtx = deviceCtxs[devId];
if (devCtx == nullptr) {
devCtx = availDevices[devId].first->CreateRdmaDeviceContext();
deviceCtxs[devId] = devCtx;
}
return devCtx;
}
/* ---------------------------------------------------------------------------------------------- */
/* Notification Manager */
/* ---------------------------------------------------------------------------------------------- */
NotifManager::NotifManager(RdmaManager* rdmaMgr, const RdmaBackendConfig& cfg)
: rdma(rdmaMgr), config(cfg) {}
NotifManager::~NotifManager() { Shutdown(); }
void NotifManager::RegisterEndpoint(const std::shared_ptr<EndpointRuntime>& rt) {
if (config.pollCqMode == PollCqMode::EVENT) {
epoll_event ev;
ev.events = EPOLLIN;
ev.data.u64 = rt->id;
assert(rt->ep.local.ibvHandle.compCh);
SYSCALL_RETURN_ZERO(epoll_ctl(epfd, EPOLL_CTL_ADD, rt->ep.local.ibvHandle.compCh->fd, &ev));
}
// Skip notification setup if disabled
if (!config.enableNotification) {
std::lock_guard<std::mutex> lock(mu);
registeredRuntimes_[rt->id] = rt;
return;
}
std::lock_guard<std::mutex> lock(mu);
if (notifCtxById_.find(rt->id) != notifCtxById_.end()) return;
registeredRuntimes_[rt->id] = rt;
application::RdmaDeviceContext* devCtx = rdma->GetRdmaDeviceContext(rt->ep.ldevId);
assert(devCtx);
void* buf;
SYSCALL_RETURN_ZERO(
posix_memalign(reinterpret_cast<void**>(&buf), PAGESIZE,
static_cast<size_t>(config.notifPerQp) * sizeof(NotifMessage)));
application::RdmaMemoryRegion mr =
devCtx->RegisterRdmaMemoryRegion(buf, config.notifPerQp * sizeof(NotifMessage));
notifCtxById_.insert({rt->id, {mr, buf}});
struct ibv_qp* qp = rt->ep.local.ibvHandle.qp;
assert(qp);
for (uint64_t i = 0; i < config.notifPerQp; i++) {
struct ibv_sge sge{};
sge.addr = mr.addr + i * sizeof(NotifMessage);
sge.length = sizeof(NotifMessage);
sge.lkey = mr.lkey;
struct ibv_recv_wr wr{};
wr.wr_id = i;
wr.sg_list = &sge;
wr.num_sge = 1;
struct ibv_recv_wr* bad = nullptr;
SYSCALL_RETURN_ZERO(ibv_post_recv(qp, &wr, &bad));
}
}
NotifManager::FlushDrainStats NotifManager::ProcessOneCqe(
const std::shared_ptr<EndpointRuntime>& rt) {
const EpPair& ep = rt->ep;
ibv_cq* cq = ep.local.ibvHandle.cq;
FlushDrainStats flushDrain;
// Resolve notif context once before the CQ drain loop.
QpNotifContext* notifCtxPtr = nullptr;
if (config.enableNotification) {
std::lock_guard<std::mutex> lock(mu);
auto nit = notifCtxById_.find(rt->id);
if (nit != notifCtxById_.end()) notifCtxPtr = &nit->second;
}
const int batchSize = 32;
struct ibv_wc wc[batchSize];
int n = 0;
while ((n = ibv_poll_cq(cq, batchSize, wc)) > 0) {
for (int i = 0; i < n; ++i) {
if (wc[i].status != IBV_WC_SUCCESS) {
const bool isFlush = (wc[i].status == IBV_WC_WR_FLUSH_ERR);
const CqeFailureOrigin failureOrigin =
ClassifyCqeFailureOrigin(wc[i].wr_id, config.notifPerQp);
const CqeFailureAdvice failureAdvice =
isFlush ? CqeFailureAdvice{ibv_wc_status_str(wc[i].status), {}}
: DescribeCqeFailure(wc[i].status, failureOrigin, config);
if (isFlush) {
flushDrain.Record(wc[i].qp_num);
MORI_IO_DEBUG("ProcessOneCqe: flush error #{}: wr_id={} qp_num={}", flushDrain.count,
wc[i].wr_id, wc[i].qp_num);
} else {
// Non-flush error: this is the root cause — always log at ERROR.
if (failureAdvice.HasHint()) {
MORI_IO_ERROR(
"ProcessOneCqe: [ROOT CAUSE] CQE error: wr_id={} status={}({}) qp_num={} "
"vendor_err={} hint={}",
wc[i].wr_id, static_cast<uint32_t>(wc[i].status), failureAdvice.statusText,
wc[i].qp_num, wc[i].vendor_err, failureAdvice.hint);
} else {
MORI_IO_ERROR(
"ProcessOneCqe: [ROOT CAUSE] CQE error: wr_id={} status={}({}) qp_num={} "
"vendor_err={}",
wc[i].wr_id, static_cast<uint32_t>(wc[i].status), failureAdvice.statusText,
wc[i].qp_num, wc[i].vendor_err);
}
}
int mergedBatchSize = 0;
auto meta = ep.ledger
? ep.ledger->ReleaseByCqe(wc[i].wr_id, ep.sqDepth.get(), &mergedBatchSize)
: nullptr;
if (meta) {
(void)meta->finishedBatchSize.fetch_add(mergedBatchSize);
if (isFlush) {
meta->diagnostics.MarkFlushCascade();
} else {
meta->diagnostics.MarkRootCause();
}
LogAsyncTransferFailureIfNeeded(&meta->diagnostics,
static_cast<uint32_t>(StatusCode::ERR_RDMA_OP),
failureAdvice.ComposeStatusMessage());
TransferStatus* statusPtr = meta->status;
if (statusPtr != nullptr) {
statusPtr->Update(StatusCode::ERR_RDMA_OP, failureAdvice.ComposeStatusMessage());
meta->status = nullptr;
}
if (ep.degraded && ep.degraded->load(std::memory_order_relaxed) && ep.ledger) {
const int orphanedReleased = ep.ledger->ReleaseOrphanedByRecovery(ep.sqDepth.get());
ep.degraded->store(false, std::memory_order_relaxed);
MORI_IO_WARN(
"ProcessOneCqe: recovered degraded EP eid={} qpn={} by releasing {} orphaned WRs",
rt->id, ep.local.handle.qpn, orphanedReleased);
}
} else if (IsNotifSendWrId(wc[i].wr_id)) {
if (ep.sqDepth) ep.sqDepth->fetch_sub(1, std::memory_order_relaxed);
if (!isFlush) {
MORI_IO_WARN(
"ProcessOneCqe: failed notification SEND CQE, transfer_id={}, released 1 sqDepth",
ExtractTransferIdFromWrId(wc[i].wr_id));
}
} else if (wc[i].wr_id < config.notifPerQp) {
if (!isFlush) {
MORI_IO_WARN("ProcessOneCqe: failed notification RECV CQE, wr_id={} (recv_idx)",
wc[i].wr_id);
}
} else {
if (!isFlush) {
MORI_IO_WARN(
"ProcessOneCqe: failed CQE wr_id={} in ledger range but no record found, "
"sqDepth may be stale",
wc[i].wr_id);
}
}
continue;
}
if (wc[i].opcode == IBV_WC_RECV) {
// Skip RECV processing if notification is disabled
if (!config.enableNotification) {
MORI_IO_WARN("Received unexpected RECV completion when notification is disabled");
continue;
}
std::lock_guard<std::mutex> lock(mu);
assert(notifCtxPtr != nullptr);
QpNotifContext& ctx = *notifCtxPtr;
// FIXME: this notif mechenism has bug when notif index is wrapped around
uint64_t idx = wc[i].wr_id;
NotifMessage msg = reinterpret_cast<NotifMessage*>(ctx.mr.addr)[idx];
assert(msg.totalNum > 0);
EngineKey ekey = ep.remoteEngineKey;
if (notifPool[ekey].find(msg.id) == notifPool[ekey].end()) {
notifPool[ekey][msg.id] = msg.totalNum;
}
notifPool[ekey][msg.id] -= 1;
MORI_IO_TRACE(
"NotifManager receive notif message from engine {} id {} qp {} total num {} cur num {}",
ekey.c_str(), msg.id, msg.qpIndex, msg.totalNum, notifPool[ekey][msg.id]);
// replenish recv wr
struct ibv_sge sge{};
sge.addr = ctx.mr.addr + idx * sizeof(NotifMessage);
sge.length = sizeof(NotifMessage);
sge.lkey = ctx.mr.lkey;
struct ibv_recv_wr wr{};
wr.wr_id = idx;
wr.sg_list = &sge;
wr.num_sge = 1;
struct ibv_recv_wr* bad = nullptr;
SYSCALL_RETURN_ZERO(ibv_post_recv(ep.local.ibvHandle.qp, &wr, &bad));
} else if (wc[i].opcode == IBV_WC_SEND) {
if (IsNotifSendWrId(wc[i].wr_id)) {
// Backward-compatible handling for any notification SENDs posted by
// older code that used tagged transfer IDs instead of ledger records.
if (ep.sqDepth) ep.sqDepth->fetch_sub(1, std::memory_order_relaxed);
} else {
int mergedBatchSize = 0;
auto meta = ep.ledger
? ep.ledger->ReleaseByCqe(wc[i].wr_id, ep.sqDepth.get(), &mergedBatchSize)
: nullptr;
if (meta) {
uint32_t finishedBefore = meta->finishedBatchSize.fetch_add(mergedBatchSize);
TransferStatus* statusPtr = meta->status;
if (statusPtr != nullptr &&
(finishedBefore + mergedBatchSize) == meta->totalBatchSize) {
statusPtr->Update(StatusCode::SUCCESS, ibv_wc_status_str(wc[i].status));
}
MORI_IO_TRACE(
"ProcessOneCqe: notification SEND CQE for task {} total={} finished={} cur={}",
meta->id, meta->totalBatchSize, finishedBefore, mergedBatchSize);
} else {
MORI_IO_WARN(
"ProcessOneCqe: notification SEND CQE has no ledger record for wr_id {}; "
"releasing 1 sqDepth under fallback path",
wc[i].wr_id);
if (ep.sqDepth) ep.sqDepth->fetch_sub(1, std::memory_order_relaxed);
}
}
} else {
// Batch path: wr_id carries a recordId from the SubmissionLedger.
uint64_t recordId = wc[i].wr_id;
int mergedBatchSize = 0;
auto meta = ep.ledger
? ep.ledger->ReleaseByCqe(recordId, ep.sqDepth.get(), &mergedBatchSize)
: nullptr;
if (meta) {
uint32_t finishedBefore = meta->finishedBatchSize.fetch_add(mergedBatchSize);
TransferStatus* statusPtr = meta->status;
if (statusPtr != nullptr && (finishedBefore + mergedBatchSize) == meta->totalBatchSize) {
statusPtr->Update(StatusCode::SUCCESS, ibv_wc_status_str(wc[i].status));
}
MORI_IO_TRACE("ProcessOneCqe: batch CQE for task {} total={} finished={} cur={}",
meta->id, meta->totalBatchSize, finishedBefore, mergedBatchSize);
} else {
MORI_IO_WARN(
"ProcessOneCqe: no ledger record for wr_id {} (recordId {}); sqDepth may be stale",
wc[i].wr_id, recordId);
}
}
}
}
if (!flushDrain.Empty()) {
MORI_IO_DEBUG("ProcessOneCqe: drain — {} flush errors on eid={} qp_num={}", flushDrain.count,
rt->id, flushDrain.firstQpNum);
}
return flushDrain;
}
void NotifManager::EmitFlushSummaryIfNeeded(const FlushRoundStats& roundStats) {
if (roundStats.Empty()) {
flushSummaryStreak_ = 0;
return;
}
flushSummaryStreak_++;
const bool shouldLog =
(flushSummaryStreak_ == 1) ||
(flushSummaryStreak_ < 64 && (flushSummaryStreak_ & (flushSummaryStreak_ - 1)) == 0) ||
(flushSummaryStreak_ % 1000 == 0);
if (shouldLog) {
if (flushSummaryStreak_ == 1) {
MORI_IO_ERROR(
"CQ poll round summary: {} flush errors across {} endpoint(s); "
"representative eid={} qp_num={}. "
"Flush errors are cascaded from QP(s) entering Error State. "
"Check: (1) peer process alive, (2) PFC / network congestion, "
"(3) ibv_devinfo / dmesg for HW errors",
roundStats.total, roundStats.endpointCount, roundStats.sampleEndpointId,
roundStats.sampleQpNum);
} else {
MORI_IO_WARN(
"CQ poll round summary: {} flush errors across {} endpoint(s); "
"representative eid={} qp_num={}; in "
"consecutive flush round #{} (rate-limited). "
"Flush errors are cascaded from QP(s) entering Error State. "
"Check: (1) peer process alive, (2) PFC / network congestion, "
"(3) ibv_devinfo / dmesg for HW errors",
roundStats.total, roundStats.endpointCount, roundStats.sampleEndpointId,
roundStats.sampleQpNum, flushSummaryStreak_);
}
}
}
void NotifManager::MainLoop() {
if (config.pollCqMode == PollCqMode::EVENT) {
constexpr int maxEvents = 128;
epoll_event events[maxEvents];
while (running.load()) {
FlushRoundStats roundStats;
bool handledCqEvent = false;
int nfds = epoll_wait(epfd, events, maxEvents, 0 /*ms*/);
for (int i = 0; i < nfds; ++i) {
EndpointId eid = events[i].data.u64;
std::shared_ptr<EndpointRuntime> rt;
{
std::lock_guard<std::mutex> lock(mu);
auto it = registeredRuntimes_.find(eid);
if (it == registeredRuntimes_.end()) continue;
rt = it->second;
}
struct ibv_comp_channel* ch = rt->ep.local.ibvHandle.compCh;
struct ibv_cq* cq = nullptr;
void* evCtx = nullptr;
if (ibv_get_cq_event(ch, &cq, &evCtx)) continue;
ibv_ack_cq_events(cq, 1);
ibv_req_notify_cq(cq, 0);
handledCqEvent = true;
roundStats.Merge(rt->id, ProcessOneCqe(rt));
}
if (handledCqEvent) {
EmitFlushSummaryIfNeeded(roundStats);
}
}
} else {
while (running.load()) {
auto snapshot = rdma->SnapshotEndpointRuntimes();
if (snapshot.empty()) {
EmitFlushSummaryIfNeeded(FlushRoundStats{});
std::this_thread::yield();
continue;
}
FlushRoundStats roundStats;
for (auto& rt : snapshot) {
roundStats.Merge(rt->id, ProcessOneCqe(rt));
}
EmitFlushSummaryIfNeeded(roundStats);
}
}
}
bool NotifManager::PopInboundTransferStatus(const EngineKey& remote, TransferUniqueId id,
TransferStatus* status) {
std::lock_guard<std::mutex> lock(mu);
if (notifPool[remote].find(id) != notifPool[remote].end()) {
if (notifPool[remote][id] == 0) {
status->SetCode(StatusCode::SUCCESS);
return true;
}
}
return false;
}
void NotifManager::Start() {
if (running.load()) return;
if (config.pollCqMode == PollCqMode::EVENT) {
epfd = epoll_create1(EPOLL_CLOEXEC);
assert(epfd >= 0);
}
running.store(true);
thd = std::thread([this] { MainLoop(); });
}
void NotifManager::Shutdown() {
running.store(false);
if (config.pollCqMode == PollCqMode::EVENT) {
epfd = close(epfd);
}
if (thd.joinable()) thd.join();
}
/* ----------------------------------------------------------------------------------------------
*/
/* Control Plane Server */
/* ----------------------------------------------------------------------------------------------
*/
ControlPlaneServer::ControlPlaneServer(const std::string& k, const std::string& host, int port,
const RdmaBackendConfig& cfg, RdmaManager* rdmaMgr,
NotifManager* notifMgr)
: myEngKey(k), config(cfg) {
ctx.reset(new application::TCPContext(host, port));
rdma = rdmaMgr;
notif = notifMgr;
}
ControlPlaneServer::~ControlPlaneServer() { Shutdown(); }
void ControlPlaneServer::RegisterRemoteEngine(const EngineDesc& rdesc) {
std::lock_guard<std::mutex> lock(mu);
engines[rdesc.key] = rdesc;
}
void ControlPlaneServer::DeregisterRemoteEngine(const EngineDesc& rdesc) {
std::lock_guard<std::mutex> lock(mu);
engines.erase(rdesc.key);
}
std::optional<int> ControlPlaneServer::TryGetRemoteEnginePort(const EngineKey& ekey) const {
std::lock_guard<std::mutex> lock(mu);
auto it = engines.find(ekey);
if (it == engines.end()) return std::nullopt;
return it->second.port;
}
void ControlPlaneServer::BuildRdmaConn(EngineKey ekey, TopoKeyPair topo, int nicRank) {
application::TCPEndpointHandle tcph;
{
std::lock_guard<std::mutex> lock(mu);
assert((engines.find(ekey) != engines.end()) && "register engine first");
EngineDesc& rdesc = engines[ekey];
tcph = ctx->Connect(rdesc.host, rdesc.port);
}
int requestedNics = ResolveRequestedNics(config, topo.local, topo.remote);
auto candidates = rdma->Search(topo.local, requestedNics);
assert(!candidates.empty());
int rank = std::min<int>(nicRank, static_cast<int>(candidates.size()) - 1);
auto [devId, weight] = candidates[rank];
application::RdmaEndpoint lep = rdma->CreateEndpoint(devId);
Protocol p(tcph);
p.WriteMessageRegEndpoint({myEngKey, topo, devId, lep.handle, rank, devId});
MessageHeader hdr = p.ReadMessageHeader();
assert(hdr.type == MessageType::RegEndpoint);
MessageRegEndpoint msg = p.ReadMessageRegEndpoint(hdr.len);
EndpointId eid = rdma->ConnectEndpoint(ekey, devId, lep, msg.devId, msg.eph, topo, weight);
auto ert = rdma->GetEndpointRuntime(eid);
notif->RegisterEndpoint(ert);
MORI_IO_INFO("Built RdmaConn for engine {} with topo local({},{}) remote({},{})", ekey,
topo.local.deviceId, topo.local.loc, topo.remote.deviceId, topo.remote.loc);
ctx->CloseEndpoint(tcph);
}
void ControlPlaneServer::RegisterMemory(MemoryDesc& desc) {
std::lock_guard<std::mutex> lock(mu);
mems[desc.id] = desc;
}
void ControlPlaneServer::DeregisterMemory(const MemoryDesc& desc) {
std::lock_guard<std::mutex> lock(mu);
mems.erase(desc.id);
}
application::RdmaMemoryRegion ControlPlaneServer::AskRemoteMemoryRegion(EngineKey ekey, int rdevId,
MemoryUniqueId id) {
application::TCPEndpointHandle tcph;
{
std::lock_guard<std::mutex> lock(mu);
assert((engines.find(ekey) != engines.end()) && "register engine first");
EngineDesc& rdesc = engines[ekey];
tcph = ctx->Connect(rdesc.host, rdesc.port);
}
Protocol p(tcph);