MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
Endpoint.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 "Endpoint.hpp"
6#include <cstddef>
7#include <cstdint>
8#include <memory>
9#include <mutex>
10#include <optional>
11#include <random>
12#include <utility>
13#include <uuid.h>
14#include <sys/uio.h>
16#include <rdma/fabric.h>
17#include <rdma/fi_cm.h>
18#include <rdma/fi_endpoint.h>
19#include <rdma/fi_errno.h>
20#include <rdma/fi_rma.h>
21#include "Address.hpp"
22#include "CompletionQueue.hpp"
23#include "Domain.hpp"
24#include "EventQueue.hpp"
25#include "Exception.hpp"
26#include "FabricInfo.hpp"
27#include "LocalRegion.hpp"
28#include "RemoteRegion.hpp"
29
31{
33 {
34 // Use a global static random engine to prevent endpoint id collisions.
35 static auto mu = std::mutex{};
36 static auto engine = std::mt19937_64{std::random_device{}()};
37 auto const lock = std::scoped_lock{mu};
38 return std::uniform_int_distribution<Endpoint::Id>{}(engine);
39 }
40
41 Endpoint::Id Endpoint::idFromFID(::fid_t fid) noexcept
42 {
43 return contextValueToId(fid->context);
44 }
45
46 Endpoint::Id Endpoint::idFromFID(::fid_ep* fid) noexcept
47 {
48 return idFromFID(&fid->fid);
49 }
50
51 Endpoint Endpoint::create(std::shared_ptr<Domain> domain)
52 {
53 return Endpoint::create(std::move(domain), randomId());
54 }
55
57 {
58 return Endpoint::create(std::move(domain), randomId(), info);
59 }
60
61 Endpoint Endpoint::create(std::shared_ptr<Domain> domain, Id epid, FabricInfoView info)
62 {
63 ::fid_ep* raw;
64
65 fiCall(::fi_endpoint, "Failed to create endpoint", domain->raw(), info.raw(), &raw, idToContextValue(epid));
66
67 // expose the private constructor to std::make_shared inside this function
68 struct MakeSharedEnabler : public Endpoint
69 {
70 MakeSharedEnabler(::fid_ep* raw, FabricInfoView info, std::shared_ptr<Domain> domain)
72 {}
73 };
74
75 return {raw, info, std::move(domain)};
76 }
77
78 Endpoint Endpoint::create(std::shared_ptr<Domain> domain, Id epid)
79 {
80 return Endpoint::create(domain, epid, domain->fabric()->info());
81 }
82
83 Endpoint::Id Endpoint::id() const noexcept
84 {
85 return contextValueToId(_raw->fid.context);
86 }
87
89 {
90 catchAndLogFabricError([this]() { close(); }, "Failed to close endpoint");
91 }
92
93 Endpoint::Endpoint(::fid_ep* raw, FabricInfoView info, std::shared_ptr<Domain> domain, std::optional<std::shared_ptr<CompletionQueue>> cq,
94 std::optional<std::shared_ptr<EventQueue>> eq, std::optional<std::shared_ptr<AddressVector>> av)
95 : _raw(raw)
96 , _info(info.owned())
97 , _domain(std::move(domain))
98 , _cq(std::move(cq))
99 , _eq(std::move(eq))
100 , _av(std::move(av))
101 {
102 MXL_DEBUG("Endpoint {} created", Endpoint::idFromFID(raw));
103 }
104
106 {
107 if (_raw)
108 {
109#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG
110 auto id = this->id();
111#endif
112
113 fiCall(::fi_close, "Failed to close endpoint", &_raw->fid);
114
115 MXL_DEBUG("Endoint {} closed", id);
116
117 _raw = nullptr;
118 }
119 }
120
121 Endpoint::Endpoint(Endpoint&& other) noexcept
122 : _raw(other._raw)
123 , _info(std::move(other._info))
124 , _domain(std::move(other._domain))
125 , _cq(std::move(other._cq))
126 , _eq(std::move(other._eq))
127 , _av(std::move(other._av))
128 {
129 other._raw = nullptr;
130 }
131
133 {
134 close();
135
136 _raw = other._raw;
137 other._raw = nullptr;
138
139 _info = std::move(other._info);
140 _domain = std::move(other._domain);
141 _eq = std::move(other._eq);
142 _cq = std::move(other._cq);
143 _av = std::move(other._av);
144
145 return *this;
146 }
147
148 void Endpoint::bind(std::shared_ptr<EventQueue> eq)
149 {
150 fiCall(::fi_ep_bind, "Failed to bind event queue to endpoint", _raw, &eq->raw()->fid, 0);
151
152 _eq = eq;
153 }
154
155 void Endpoint::bind(std::shared_ptr<CompletionQueue> cq, std::uint64_t flags)
156 {
157 fiCall(::fi_ep_bind, "Failed to bind completion queue to endpoint", _raw, &cq->raw()->fid, flags);
158
159 _cq = cq;
160 }
161
162 void Endpoint::bind(std::shared_ptr<AddressVector> av)
163 {
164 fiCall(::fi_ep_bind, "Failed to bind address vector to endpoint", _raw, &av->raw()->fid, 0);
165
166 _av = av;
167 }
168
170 {
171 fiCall(::fi_enable, "Failed to enable endpoint", _raw);
172 }
173
175 {
176 auto dummy = std::uint8_t{};
177 fiCall(::fi_accept, "Failed to accept connection", _raw, &dummy, sizeof(dummy));
178 }
179
181 {
182 fiCall(::fi_connect, "Failed to connect endpoint", _raw, addr.raw(), nullptr, 0);
183 }
184
186 {
187 fiCall(::fi_shutdown, "Failed to shutdown endpoint", _raw, 0);
188 }
189
191 {
192 return RawFabricAddress::fromFid(&_raw->fid, _info.view());
193 }
194
195 std::shared_ptr<CompletionQueue> Endpoint::completionQueue() const
196 {
197 if (!_cq)
198 {
199 throw Exception::internal("no Completion queue is bound to the endpoint"); // Is this the right throw??
200 }
201
202 return *_cq;
203 }
204
205 std::shared_ptr<EventQueue> Endpoint::eventQueue() const
206 {
207 if (!_eq)
208 {
209 throw Exception::internal("No event queue bound to the endpoint"); // Is this the right throw??
210 }
211
212 return *_eq;
213 }
214
215 std::shared_ptr<AddressVector> Endpoint::addressVector() const
216 {
217 if (!_av)
218 {
219 throw Exception::internal("No address vector bound to the endpoint!");
220 }
221 return *_av;
222 }
223
224 std::pair<std::optional<Completion>, std::optional<Event>> Endpoint::readQueues()
225 {
226 std::optional<Completion> completion{std::nullopt};
227 std::optional<Event> event{std::nullopt};
228
229 if (_cq)
230 {
231 completion = (*_cq)->read();
232 }
233
234 if (_eq)
235 {
236 event = (*_eq)->read();
237 }
238
239 return {completion, event};
240 }
241
242 std::pair<std::optional<Completion>, std::optional<Event>> Endpoint::readQueuesBlocking(std::chrono::steady_clock::duration timeout)
243 {
244 std::optional<Completion> completion{std::nullopt};
245 std::optional<Event> event{std::nullopt};
246
247 // No queues, no blocking;
248 if (!_eq && !_cq)
249 {
250 throw Exception::invalidState("No queues bound to endpoint");
251 }
252
253 // There is no event queue, so we just block on the completion queue.
254 if (!_eq)
255 {
256 return {(*_cq)->readBlocking(timeout), event};
257 }
258
259 auto timeoutMs = std::chrono::duration_cast<std::remove_const_t<decltype(EQReadInterval)>>(timeout);
260
261 // This is the simple case: The user-supplied timeout is less than the minimum EventQueue read interval. So we just read the EventQueue once
262 // and then block on the CompletionQueue until the specified timeout.
263 if (timeoutMs < EQReadInterval)
264 {
265 auto event = (*_eq)->read();
266 auto completion = (*_cq)->readBlocking(timeout);
267
268 return {completion, event};
269 }
270
271 // The time point at which we must return control to the user.
272 auto deadline = std::chrono::steady_clock::now() + timeout;
273
274 for (;;)
275 {
276 // The maximum duration we can block for until we must return control to the caller.
277 auto timeUntilDeadline = std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now());
278
279 // If the time is up, we return control.
280 if (timeUntilDeadline <= std::chrono::milliseconds(0))
281 {
282 return {completion, event};
283 }
284
285 // Do a non-blocking read of the event queue first.
286 event = (*_eq)->read();
287 if (event)
288 {
289 return {completion, event};
290 }
291
292 // And then block on the completion queue until either the minimum duration between event queue reads has elapsed, or the latest point in
293 // time at which we need to return control to the caller has been reached.
294 completion = (*_cq)->readBlocking(std::min(EQReadInterval, timeUntilDeadline));
295 if (completion)
296 {
297 return {completion, event};
298 }
299 }
300 }
301
302 std::shared_ptr<Domain> Endpoint::domain() const
303 {
304 return _domain;
305 }
306
308 {
309 return _info.view();
310 }
311
312 ::fid_ep* Endpoint::raw() noexcept
313 {
314 return _raw;
315 }
316
317 ::fid_ep const* Endpoint::raw() const noexcept
318 {
319 return _raw;
320 }
321
322 void Endpoint::writeImpl(Completion::Token token, ::iovec const* msgIov, std::size_t iovCount, void** desc, ::fi_rma_iov const* rmaIov,
323 ::fi_addr_t destAddr, std::optional<std::uint32_t> immData) const
324 {
325 std::uint64_t data = immData.value_or(0);
326 std::uint64_t flags = FI_DELIVERY_COMPLETE;
327 flags |= immData.has_value() ? FI_REMOTE_CQ_DATA : 0;
328
329 ::fi_msg_rma msg = {
330 .msg_iov = msgIov,
331 .desc = desc,
332 .iov_count = iovCount,
333 .addr = destAddr,
334 .rma_iov = rmaIov,
335 .rma_iov_count = 1,
336 .context = Completion::tokenToContextValue(token),
337 .data = data,
338 };
339
340 fiCall(::fi_writemsg, "Failed to push rma write to work queue.", _raw, &msg, flags);
341 }
342
343 std::size_t Endpoint::write(Completion::Token token, LocalRegion const& local, RemoteRegion const& remote, ::fi_addr_t destAddr,
344 std::optional<std::uint32_t> immData) const
345 {
346 std::vector<void*> descs{local.desc};
347
348 auto msgIov = local.toIovec();
349 auto rmaIov = remote.toRmaIov();
350
351 writeImpl(token, &msgIov, 1, descs.data(), &rmaIov, destAddr, immData);
352
353 return 1;
354 }
355
356 std::size_t Endpoint::write(Completion::Token token, LocalRegionGroup const& localGroup, RemoteRegion const& remote, ::fi_addr_t destAddr,
357 std::optional<std::uint32_t> immData) const
358 {
359 auto remoteRmaIov = remote.toRmaIov();
360 auto remoteOffset = std::size_t{0};
361
362 auto const iovLimit = info().txIovLimit();
363 auto const nbWrites = (localGroup.size() + iovLimit - 1) / iovLimit; // ceil(group.size() / iovLimit)
364
365 for (auto i = std::size_t{0}; i < nbWrites; i++)
366 {
367 auto const begin = i * iovLimit;
368 auto const end = begin + std::min(iovLimit, localGroup.size() - begin);
369
370 auto const localGroupSpan = localGroup.span(begin, end);
371
372 // Validate that we don't bust the remote region
373 if ((remoteOffset + localGroupSpan.byteSize()) > remote.len)
374 {
375 throw Exception::invalidArgument("Local region group is too large for the remote region.");
376 }
377
378 remoteRmaIov.addr = remote.addr + remoteOffset;
379 remoteRmaIov.len = localGroupSpan.byteSize();
380
381 auto const isLastWrite = (i == nbWrites - 1);
382 auto const immDataForWrite = isLastWrite ? immData : std::nullopt;
383
384 writeImpl(token,
385 localGroupSpan.asIovec(),
386 localGroupSpan.size(),
387 const_cast<void**>(localGroupSpan.desc()),
388 &remoteRmaIov,
389 destAddr,
390 immDataForWrite);
391
392 remoteOffset += localGroupSpan.byteSize();
393 }
394
395 return nbWrites;
396 }
397
398 void Endpoint::recv(LocalRegion region) const
399 {
400 auto iovec = region.toIovec();
401 fiCall(::fi_recv, "Failed to push recv to work queue", _raw, iovec.iov_base, iovec.iov_len, nullptr, FI_ADDR_UNSPEC, nullptr);
402 }
403}
#define MXL_DEBUG(...)
Definition Logging.hpp:34
std::uintptr_t Token
A token used to associate a completion entry with an endpoint.
static constexpr void * tokenToContextValue(Token token) noexcept
Convert between completion tokens and context values that can be written to and read from raw libfabr...
std::shared_ptr< AddressVector > addressVector() const
Get the associated addres vector.
Definition Endpoint.cpp:215
::fid_ep * raw() noexcept
Get the raw libfabric handle to this endpoint.
Definition Endpoint.cpp:312
static Id idFromFID(::fid_t) noexcept
Read the endpoint id from a libfabric object reference.
Definition Endpoint.cpp:41
std::shared_ptr< Domain > domain() const
Get the domain that the endpoint has beed created on.
Definition Endpoint.cpp:302
void accept()
Accept an incoming connection.
Definition Endpoint.cpp:174
static Id randomId() noexcept
Generate a new random endpoint id.
Definition Endpoint.cpp:32
void enable()
This call transitions the endpoint into an enabled state.
Definition Endpoint.cpp:169
void close()
Close the endpoint and release all resources. Called from the destructor and the move assignment oper...
Definition Endpoint.cpp:105
std::uintptr_t Id
An id type that can be used to reference this endpoint from completions and events.
Definition Endpoint.hpp:38
RawFabricAddress localAddress() const
Definition Endpoint.cpp:190
~Endpoint()
Destructor releases all resources.
Definition Endpoint.cpp:88
std::optional< std::shared_ptr< AddressVector > > _av
Definition Endpoint.hpp:327
static Endpoint create(std::shared_ptr< Domain > domain, FabricInfoView info)
Allocates (active) new endpoint.
Definition Endpoint.cpp:56
FabricInfoView info() const noexcept
Get the fabric information passed to Endpoint::create() initially.
Definition Endpoint.cpp:307
void operator=(Endpoint const &)=delete
Endpoint(Endpoint const &)=delete
static constexpr Id contextValueToId(void *contextValue) noexcept
Convert between Ids and context values that can be written to and read from raw libfabric queue entri...
Definition Endpoint.hpp:57
void connect(RawFabricAddress const &addr)
Initiate a connection to a remote (passive) endpoint.
Definition Endpoint.cpp:180
std::pair< std::optional< Completion >, std::optional< Event > > readQueues()
Do a non-blocking read of both the event and completion queue associated with this endpoint.
Definition Endpoint.cpp:224
std::pair< std::optional< Completion >, std::optional< Event > > readQueuesBlocking(std::chrono::steady_clock::duration timeout)
Do a combined blocking read of both the event and completion queue associated with this endpoint.
Definition Endpoint.cpp:242
std::shared_ptr< CompletionQueue > completionQueue() const
Get the associated completion queue.
Definition Endpoint.cpp:195
std::shared_ptr< EventQueue > eventQueue() const
Get the assiociated event queue.
Definition Endpoint.cpp:205
void bind(std::shared_ptr< EventQueue > eq)
Bind the endpoint to an event queue.
Definition Endpoint.cpp:148
void recv(LocalRegion region) const
Push a recv work request to the endpoint work queue.
Definition Endpoint.cpp:398
std::shared_ptr< Domain > _domain
Definition Endpoint.hpp:323
static constexpr void * idToContextValue(Id id) noexcept
Convert between Ids and context values that can be written to and read from raw libfabric queue entri...
Definition Endpoint.hpp:49
std::size_t write(Completion::Token token, LocalRegion const &local, RemoteRegion const &remote, ::fi_addr_t destAddr=FI_ADDR_UNSPEC, std::optional< std::uint32_t > immData=std::nullopt) const
Push a remote write work request of a single contiguous buffer to the endpoint work queue.
Definition Endpoint.cpp:343
Id id() const noexcept
Get the id of this endpoint.
Definition Endpoint.cpp:83
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
std::optional< std::shared_ptr< EventQueue > > _eq
Definition Endpoint.hpp:326
std::optional< std::shared_ptr< CompletionQueue > > _cq
Definition Endpoint.hpp:325
void shutdown()
Initiate a graceful shutdown on a connection-oriented endpoint.
Definition Endpoint.cpp:185
void writeImpl(Completion::Token token, ::iovec const *msgIov, std::size_t iovCount, void **desc, ::fi_rma_iov const *rmaIov, ::fi_addr_t destAddr, std::optional< std::uint32_t > immData) const
Internal implementation of the remote write request.
Definition Endpoint.cpp:322
static Exception invalidArgument(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_ARG exception.
Definition Exception.hpp:43
static Exception internal(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INTERNAL exception.
Definition Exception.hpp:51
static Exception invalidState(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_STATE exception.
Definition Exception.hpp:59
Non-owning view of a FabricInfo. Returned when iterating over a FabricInfoList.
std::size_t txIovLimit() const noexcept
Return the IOV limit for this fabric info, which is the maximum number of iovecs that can be posted i...
Represent a scatter-gather list of source memory regions used for data transfer.
LocalRegionGroupSpan span(std::size_t beginIndex, std::size_t endIndex) const
Return a span representing a contiguous subset of the LocalRegionGroup.
std::size_t size() const noexcept
Wrapper around a libfabric endpoint address.
Definition Address.hpp:20
void * raw() noexcept
Pointer to the raw address data.
Definition Address.cpp:37
static RawFabricAddress fromFid(::fid_t fid, FabricInfoView info)
Retrieve the fabric address of an endpoint by passing its fid.
Definition Address.cpp:27
void catchAndLogFabricError(F &&fun, std::string_view msg)
int fiCall(F &&fun, std::string_view msg, T &&... args)
Call a libfabric function and check its return code.
std::filesystem::path _domain
The monitored domain.
Represent a source memory region used for for data transfer.
::iovec toIovec() const noexcept
Convert this LocalRegion to a struct iovec used by libfabric transfer functions.
Represent a remote memory region used for data transfer.
::fi_rma_iov toRmaIov() const noexcept
Convert this RemoteRegion to a struct fi_rma_iov used by libfabric RMA transfer functions.
gInfo flags
Mark the grain as invalid.