MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
RDMInitiator.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Contributors to the Media eXchange Layer project.
2//
3// SPDX-License-Identifier: Apache-2.0
4
5#include "RDMInitiator.hpp"
6#include <cassert>
7#include <chrono>
8#include <cstdint>
9#include <algorithm>
10#include <exception>
11#include <memory>
12#include <thread>
13#include <utility>
14#include <variant>
16#include <rdma/fabric.h>
17#include <rdma/fi_eq.h>
18#include "mxl-internal/Flow.hpp"
19#include "mxl/fabrics.h"
20#include "mxl/mxl.h"
21#include "AddressVector.hpp"
22#include "CompletionQueue.hpp"
23#include "Endpoint.hpp"
24#include "EventQueue.hpp"
25#include "Exception.hpp"
26#include "Fabric.hpp"
27#include "FabricInfoHelpers.hpp"
28#include "QueueHelpers.hpp"
29#include "Region.hpp"
30#include "TargetInfo.hpp"
31#include "VariantUtils.hpp"
32
34{
35 RDMInitiatorTarget::RDMInitiatorTarget(std::unique_ptr<EgressProtocol> proto, TargetInfo remoteInfo)
36 : _state(Idle{})
37 , _proto(std::move(proto))
38 , _remoteInfo(std::move(remoteInfo))
39 {}
40
41 bool RDMInitiatorTarget::isIdle() const noexcept
42 {
43 return std::holds_alternative<Idle>(_state);
44 }
45
47 {
48 _state = std::visit(
50 [&](Idle) -> State
51 {
52 auto fiAddr = ep.addressVector()->insert(_remoteInfo.fabricAddress);
53 return Activated{.fiAddr = fiAddr};
54 },
55 [](Activated state) -> State { return state; },
56 [](Removing state) -> State { return state; },
57 [](Done) -> State { throw Exception::invalidState("Endpoint has been shutdown and can no longer be used."); },
58 },
59 std::move(_state));
60 }
61
63 {
64 _state = std::visit(
66 [](Idle) -> State
67 {
68 MXL_WARN("Shutdown requested while waiting to activate, aborting.");
69 return Done{};
70 },
71 [&](Activated state) -> State
72 {
73 if (_proto->hasPendingWork())
74 {
75 MXL_INFO("Target removed that had outstanding writes, transitioning to removing state.");
76 return Removing{.fiAddr = state.fiAddr, .deadline = std::chrono::steady_clock::now() + RemoveTimeout};
77 }
78
79 ep.addressVector()->remove(state.fiAddr);
80 return Done{};
81 },
82 [](Removing state) -> State { return state; },
83 [](Done state) -> State { return state; },
84 },
85 std::move(_state));
86 }
87
89 {
90 auto const state = std::get_if<Removing>(&_state);
91 if (state == nullptr)
92 {
93 return;
94 }
95
96 if (std::chrono::steady_clock::now() >= state->deadline)
97 {
98 MXL_WARN("Writes to the removed target did not complete within {} ms, removing it anyway.",
99 std::chrono::duration_cast<std::chrono::milliseconds>(RemoveTimeout).count());
100 }
101 else
102 {
103 return;
104 }
105
106 ep.addressVector()->remove(state->fiAddr);
107 _state = Done{};
108 }
109
110 bool RDMInitiatorTarget::canEvict() const noexcept
111 {
112 return std::holds_alternative<Done>(_state);
113 }
114
115 void RDMInitiatorTarget::transferGrain(Endpoint const& ep, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint64_t remotePayloadOffset,
116 SliceRange const& sliceRange)
117 {
118 if (auto const state = std::get_if<Activated>(&_state); state != nullptr)
119 {
120 _proto->transferGrain(ep, localIndex, remoteIndex, remotePayloadOffset, sliceRange, state->fiAddr);
121 }
122 }
123
124 void RDMInitiatorTarget::transferSamples(Endpoint const& ep, std::uint64_t headIndex, std::size_t count)
125 {
126 if (auto const state = std::get_if<Activated>(&_state); state != nullptr)
127 {
128 _proto->transferSamples(ep, headIndex, count, state->fiAddr);
129 }
130 }
131
133 {
134 return std::visit(
136 [](Idle const&) { return true; },
137 [&](Activated const&) { return _proto->hasPendingWork(); },
138 [](Removing const&) { return true; },
139 [](Done const&) { return false; },
140 },
141 _state);
142 }
143
145 {
146 if (auto error = completion.tryErr(); error)
147 {
148 MXL_ERROR("Received a completion error: {}", error->toString());
149 }
150
151 std::visit(
153 [](Idle const&) {},
154 [&](Activated const&) { _proto->processCompletion(completion); },
155 [&](Removing const&) { _proto->processCompletion(completion); },
156 [](Done const&) {},
157 },
158 _state);
159 }
160
161 std::unique_ptr<RDMInitiator> RDMInitiator::setup(mxlFabricsInitiatorConfig const& config, FabricInfoView info,
162 InitiatorSetupOptions const& options)
163 {
164 requireCapability(info, FI_WRITE, "Interface is missing required remote write capability");
165
166 // Size the CQ to hold as many completions as the endpoint supports, to avoid
167 // CQ overflow. This assumes one CQ per endpoint; if CQs are ever shared,
168 // this sizing must be revisited.
170 cqAttr.size = std::max(cqAttr.size, info.txSize());
171 if (options.cqDepth)
172 {
173 cqAttr.size = *options.cqDepth;
174 }
176 {
178 {
180 {
181 throw Exception::make(MXL_ERR_NO_FABRIC, "Blocking API support requested, but not available for this fabric/version");
182 }
183
184 cqAttr.waitObject = FI_WAIT_NONE;
185 }
186 }
187
188 auto fabric = Fabric::open(info);
189 auto domain = Domain::open(fabric);
190 auto endpoint = Endpoint::create(domain);
191 auto cq = CompletionQueue::open(endpoint.domain(), cqAttr);
192 endpoint.bind(cq, FI_TRANSMIT | FI_RECV);
193
194 auto av = AddressVector::open(endpoint.domain());
195 endpoint.bind(av);
196
197 endpoint.bind(EventQueue::open(fabric));
198
199 endpoint.enable();
200
201 auto regions = MxlRegions::forReader(config.reader);
202 auto proto = selectEgressProtocol(regions.dataLayout(), regions.regions());
203
204 proto->registerMemory(domain);
205
206 struct MakeUniqueEnabler : RDMInitiator
207 {
208 MakeUniqueEnabler(Endpoint ep, std::unique_ptr<EgressProtocolTemplate> proto)
209 : RDMInitiator(std::move(ep), std::move(proto))
210 {}
211 };
212
213 return std::make_unique<MakeUniqueEnabler>(std::move(endpoint), std::move(proto));
214 }
215
216 RDMInitiator::RDMInitiator(Endpoint ep, std::unique_ptr<EgressProtocolTemplate> proto)
217 : _proto(std::move(proto))
218 , _endpoint(std::move(ep))
219 {}
220
221 void RDMInitiator::addTarget(TargetInfo const& targetInfo)
222 {
223 if (_remoteEndpoints.contains(targetInfo.id))
224 {
225 throw Exception::exists("A target with endpoint id {} has already been added to this initiator.", targetInfo.id);
226 }
227
228 auto const token = Completion::randomToken();
229 auto proto = _proto->createInstance(token, targetInfo);
230 proto->registerMemory(_endpoint.domain());
231
232 _remoteEndpoints.emplace(targetInfo.id, token);
233 _targets.emplace(token, RDMInitiatorTarget(std::move(proto), targetInfo));
234 }
235
237 {
238 auto& remote = findRemoteByEndpoint(targetInfo.id);
239 remote.shutdown(_endpoint);
240
241 // The target can no longer be found by its id, so no new transfers are posted to it. It stays in _targets until its outstanding
242 // writes have completed, so that their completions can be counted and the protocol memory stays valid.
243 auto const token = _remoteEndpoints.extract(targetInfo.id).mapped();
244 if (remote.canEvict())
245 {
246 _targets.erase(token);
247 }
248 }
249
251 {
252 for (auto& [_, target] : _targets)
253 {
254 target.shutdown(_endpoint);
255 }
256 _remoteEndpoints.clear();
257
258 auto const deadline = std::chrono::steady_clock::now() + ShutdownTimeout;
259 for (;;)
260 {
262
263 if (_targets.empty())
264 {
265 return;
266 }
267
268 if (std::chrono::steady_clock::now() >= deadline)
269 {
270 MXL_WARN("{} targets were not removed in time.", _targets.size());
271 return;
272 }
273
274 std::this_thread::sleep_for(ShutdownPollInterval);
275 drainCQ();
276 }
277 }
278
279 void RDMInitiator::transferGrain(std::uint64_t grainIndex, std::uint16_t startSlice, std::uint16_t endSlice)
280 {
281 // Post a transfer work item to all targets. If the target is not in "Added" state
282 // this is a no-op.
284 { target.transferGrain(_endpoint, grainIndex, grainIndex, MXL_GRAIN_PAYLOAD_OFFSET, SliceRange::make(startSlice, endSlice)); });
285 }
286
287 void RDMInitiator::transferGrainToTarget(Endpoint::Id targetId, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint64_t payloadOffset,
288 std::uint16_t startSlice, std::uint16_t endSlice)
289 {
290 // A completion will be posted to the completion queue per transfer, after which the counter will be decremented again
291 findRemoteByEndpoint(targetId).transferGrain(_endpoint, localIndex, remoteIndex, payloadOffset, SliceRange::make(startSlice, endSlice));
292 }
293
294 void RDMInitiator::transferSamples(std::uint64_t headIndex, std::size_t count)
295 {
296 forEachTarget([&](RDMInitiatorTarget& target) { target.transferSamples(_endpoint, headIndex, count); });
297 }
298
299 // makeProgress
308
309 // makeProgressBlocking
310 Initiator::MakeProgressResult RDMInitiator::makeProgressBlocking(std::chrono::steady_clock::duration timeout)
311 {
312 try
313 {
314 if (timeout < Endpoint::EQReadInterval)
315 {
316 makeProgress();
317 blockOnCQ(timeout);
319 return afterProgressResult();
320 }
321
322 auto const deadline = std::chrono::steady_clock::now() + timeout;
323 for (;;)
324 {
325 if (std::holds_alternative<Initiator::Ready>(makeProgress()))
326 {
327 return Initiator::Ready{};
328 }
329
330 auto const timeUntilDeadline = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
331 if (timeUntilDeadline <= std::chrono::milliseconds::zero())
332 {
333 return afterProgressResult();
334 }
335
336 // Bounded so that makeProgress() reads the event queue at least once per interval.
337 blockOnCQ(std::min(Endpoint::EQReadInterval, timeUntilDeadline));
338 }
339 }
340 catch (FabricException const& ex)
341 {
342 if (ex.isInterrupted())
343 {
344 return Initiator::Interrupted{};
345 }
346 throw;
347 }
348 }
349
351 {
352 auto it = _remoteEndpoints.find(id);
353 if (it == _remoteEndpoints.end())
354 {
355 throw Exception::notFound("No target found for endpoint id {}", id);
356 }
357
358 return findRemoteByToken(it->second);
359 }
360
362 {
363 auto it = _targets.find(token);
364 if (it == _targets.end())
365 {
366 throw Exception::notFound("No target found for completion token value");
367 }
368
369 return it->second;
370 }
371
373 {
374 for (auto const& [_, remote] : _targets)
375 {
376 if (remote.hasPendingWork())
377 {
378 return Initiator::NotReady{};
379 }
380 }
381
382 return Initiator::Ready{};
383 }
384
385 void RDMInitiator::blockOnCQ(std::chrono::steady_clock::duration timeout)
386 {
387 // A zero timeout would cause the queue to block indefinetly, which
388 // is not our documented behaviour.
389 if (timeout == std::chrono::milliseconds::zero())
390 {
391 // So just behave exactly like the non-blocking variant.
392 drainCQ();
393 return;
394 }
395
396 if (auto completion = _endpoint.completionQueue()->readBlocking(timeout); completion)
397 {
398 processCompletion(*completion);
399 drainCQ();
400 }
401 }
402
404 {
405 while (auto completion = _endpoint.completionQueue()->read())
406 {
407 processCompletion(*completion);
408 }
409 }
410
411 template<typename F>
413 {
414 // One failing target, e.g. an EFA peer in backoff answering EAGAIN, must not stop the others.
415 auto failure = std::exception_ptr{};
416 for (auto& [_, target] : _targets)
417 {
418 try
419 {
420 transfer(target);
421 }
422 catch (Exception const&)
423 {
424 if (!failure)
425 {
426 failure = std::current_exception();
427 }
428 }
429 }
430 if (failure)
431 {
432 std::rethrow_exception(failure);
433 }
434 }
435
437 {
438 for (auto& [_, target] : _targets)
439 {
440 target.activate(_endpoint);
441 }
442 }
443
445 {
446 for (auto& [_, target] : _targets)
447 {
448 target.finishRemoval(_endpoint);
449 }
450
451 std::erase_if(_targets, [](auto const& item) { return item.second.canEvict(); });
452 }
453
455 {
456 auto it = _targets.find(completion.token());
457 if (it == _targets.end())
458 {
459 MXL_ERROR("Dropping completion for unknown target.");
460 return;
461 }
462
463 it->second.handleCompletion(_endpoint, completion);
464 }
465
466} // namespace mxl::lib::fabrics::ofi
Internal shared-memory headers for discrete grains and event slots.
#define MXL_ERROR(...)
Definition Logging.hpp:67
#define MXL_WARN(...)
Definition Logging.hpp:56
#define MXL_INFO(...)
Definition Logging.hpp:45
static std::shared_ptr< AddressVector > open(std::shared_ptr< Domain > domain, Attributes attr=Attributes::defaults())
Create an AddressVector.
static std::shared_ptr< CompletionQueue > open(std::shared_ptr< Domain > domain, Attributes const &attr=Attributes::defaults())
Create a new completion queue in the specified domain.
static bool isWaitObjectSupportedForEFA() noexcept
Check if wait any wait object type supported by the EFA provider for this libfabric version.
Type to represent a completion entry from a CompletionQueue.
Token token() const noexcept
Get the token that was associated with the operation that has completed.
std::uintptr_t Token
A token used to associate a completion entry with an endpoint.
std::optional< Error > tryErr() const noexcept
Attempt to access the error variant. Returns std::nullopt if this is a data entry.
static std::shared_ptr< Domain > open(std::shared_ptr< Fabric > fabric)
Open a new domain associated with the specified fabric.
Definition Domain.cpp:30
RAII Wrapper around a libfabric endpoint (fi_ep).
Definition Endpoint.hpp:29
std::shared_ptr< AddressVector > addressVector() const
Get the associated addres vector.
Definition Endpoint.cpp:215
std::uintptr_t Id
An id type that can be used to reference this endpoint from completions and events.
Definition Endpoint.hpp:38
static Endpoint create(std::shared_ptr< Domain > domain, FabricInfoView info)
Allocates (active) new endpoint.
Definition Endpoint.cpp:56
static constexpr auto const EQReadInterval
The minimum interval at which the event queue will be polled when doing a blocking read of both (even...
Definition Endpoint.hpp:34
static std::shared_ptr< EventQueue > open(std::shared_ptr< Fabric >, Attributes const &attr=Attributes::defaults())
Create a new event queue associated with the specified fabric.
Custom exception type used in the fabrics library.
Definition Exception.hpp:28
static Exception make(mxlStatus status, fmt::format_string< T... > fmt, T &&... args)
Make any type of exception.
Definition Exception.hpp:35
static Exception notFound(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_NOT_FOUND exception.
Definition Exception.hpp:75
static Exception exists(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_EXISTS exception.
Definition Exception.hpp:67
static Exception invalidState(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_STATE exception.
Definition Exception.hpp:59
An internal exception type that extends.
Non-owning view of a FabricInfo. Returned when iterating over a FabricInfoList.
std::size_t txSize() const noexcept
Return the transmit queue size of the endpoint.
static std::shared_ptr< Fabric > open(FabricInfoView info)
Open a fabric object based on the provided FabricInfoView.
Definition Fabric.cpp:15
std::variant< Ready, NotReady, Interrupted > MakeProgressResult
Definition Initiator.hpp:42
static MxlRegions forReader(mxlFlowReader)
Definition Region.cpp:105
A single endpoint within an RDMInitiator.
void handleCompletion(Endpoint &ep, Completion completion)
Handle a completion event for this endpoint.
bool canEvict() const noexcept
Returns true if the target was shut down and can be evicted from the initiator.
void transferGrain(Endpoint const &ep, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint64_t remotePayloadOffset, SliceRange const &sliceRange)
Post a grain data transfer request to this endpoint.
bool isIdle() const noexcept
Returns true if the endpoint is idle and could be actived.
RDMInitiatorTarget(std::unique_ptr< EgressProtocol > proto, TargetInfo remoteInfo)
Construct a new RDMInitiatorEndpoint object.
bool hasPendingWork() const noexcept
Returns true if there's pending work for this target.
std::variant< Idle, Activated, Removing, Done > State
The various states that the endpoint can be in are stored inside a variant that we move from and then...
void finishRemoval(Endpoint &ep)
Complete the removal once all outstanding writes have completed or RemoveTimeout has elapsed.
void transferSamples(Endpoint const &ep, std::uint64_t headIndex, std::size_t count)
Post a sample data transfer request to this endpoint.
void shutdown(Endpoint &ep)
Stop transfers to this target.
void activate(Endpoint &ep)
Try to activate the endpoint.
std::unique_ptr< EgressProtocol > _proto
static constexpr auto RemoveTimeout
Upper bound for the removing state. A target that disappears may never complete the outstanding write...
std::map< Completion::Token, RDMInitiatorTarget > _targets
virtual void removeTarget(TargetInfo const &remoteTargetInfo) final
Remove a target from the initiator.
std::unique_ptr< EgressProtocolTemplate > _proto
std::map< Endpoint::Id, Completion::Token > _remoteEndpoints
RDMInitiator(Endpoint ep, std::unique_ptr< EgressProtocolTemplate > proto)
Construct a new RDMInitiator object.
Initiator::MakeProgressResult afterProgressResult() const noexcept
Returns true if any of the endpoints contained in this initiator have pending work.
virtual void addTarget(TargetInfo const &remoteTargetInfo) final
Add a target to the initiator.
void processCompletion(Completion completion)
Consume a completion entry.
static constexpr auto ShutdownPollInterval
Sleep time between two queue reads in shutdown().
void blockOnCQ(std::chrono::steady_clock::duration timeout)
Block on the completion queue until a completion arrives or the timeout elapses, then process all ava...
void evictRemovedTargets()
Complete the removal of targets whose outstanding writes have completed, and evict them.
virtual void transferGrainToTarget(Endpoint::Id targetId, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint64_t payloadOffset, std::uint16_t startSlice, std::uint16_t endSlice) final
Transfer a grain to a specific target.
virtual Initiator::MakeProgressResult makeProgressBlocking(std::chrono::steady_clock::duration timeout) final
Attempts to progress execution, including connection management and data operations.
static std::unique_ptr< RDMInitiator > setup(mxlFabricsInitiatorConfig const &config, FabricInfoView info, InitiatorSetupOptions const &options={})
Set up a new RDMInitiator.
virtual void transferSamples(std::uint64_t headIndex, std::size_t count) final
Transfer samples to all targets.
static constexpr auto ShutdownTimeout
Upper bound for shutdown(). It is longer than RDMInitiatorTarget::RemoveTimeout, so that each removal...
void activateIdleEndpoints()
Try to activate any idle endpoints.
RDMInitiatorTarget & findRemoteByEndpoint(Endpoint::Id id)
Find a remote target by its endpoint id.
void drainCQ()
Process completions until the completion queue is empty.
virtual void transferGrain(std::uint64_t grainIndex, std::uint16_t startSlice, std::uint16_t endSlice) final
Transfer a grain to all targets.
virtual Initiator::MakeProgressResult makeProgress() final
Attempts to progress execution, including connection management and data operations.
virtual void shutdown() final
Shut down the initiator gracefully.
void forEachTarget(F &&transfer)
Offer a transfer to every target.
RDMInitiatorTarget & findRemoteByToken(Completion::Token token)
Find a remote target by its completion token.
A SliceRange represents a range of slices within a grain.
static SliceRange make(std::uint16_t start, std::uint16_t end)
Create a SliceRange representing the range [start, end).
@ MXL_FABRICS_IFACE_CAP_BLOCKING_OPERATIONS
Definition fabrics.h:78
@ MXL_FABRICS_PROVIDER_EFA
Definition fabrics.h:51
struct mxlFabricsInitiatorConfig_t mxlFabricsInitiatorConfig
@ MXL_ERR_NO_FABRIC
Definition mxl.h:46
void drainEventQueue(EventQueue &eq)
Read all entries from a connectionless endpoint's event queue and log the errors among them.
std::unique_ptr< EgressProtocolTemplate > selectEgressProtocol(DataLayout const &layout, std::vector< Region > regions)
Select an appropriate egress protocol based on the data layout.
Definition Protocol.cpp:33
void requireCapability(FabricInfoView info, std::uint64_t cap, std::string_view message)
constexpr auto const MXL_GRAIN_PAYLOAD_OFFSET
Definition Flow.hpp:38
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
mxlFabricsInterfaceConfig interface
Definition fabrics.h:139
mxlFabricsProvider provider
Definition fabrics.h:100
mxlFabricsInterfaceCaps caps
Definition fabrics.h:101
static Attributes defaults()
Returns the a CompletionQueueAttr with all of its attributes set to reasonable defaults.
Provider-independent tuning options for initiator setup.
Definition Initiator.hpp:19
std::optional< std::size_t > cqDepth
Desired completion-queue depth.
Definition Initiator.hpp:25
The endpoint is done and can be evicted from the initiator.
TargetInfo contains all the information required by an initiator to operate transfers to the given ta...