MXL : Media eXchange Layer
MXL
Loading...
Searching...
No Matches
ProtocolEgressRMA.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
7#include "DataLayout.hpp"
8#include "Exception.hpp"
9#include "ImmData.hpp"
10#include "LocalRegion.hpp"
11
13{
14
16 std::vector<LocalRegion> localRegions)
17 : _token{token}
18 , _remoteInfo{std::move(info)}
19 , _layout{layout}
20 , _localRegions{std::move(localRegions)}
21 {}
22
23 void RMAGrainEgressProtocol::registerMemory(std::shared_ptr<Domain>)
24 {
25 // For this protocol, memory registration is completely handled at the protocol template level, so this function doesn't need to do anything.
26 }
27
28 void RMAGrainEgressProtocol::transferGrain(Endpoint const& ep, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint32_t payloadOffset,
29 SliceRange const& sliceRange, ::fi_addr_t destAddr)
30 {
31 auto const localGrain = _localRegions[localIndex % _localRegions.size()];
32 auto const remoteGrain = _remoteInfo.remoteRegions[remoteIndex % _remoteInfo.remoteRegions.size()];
33 auto const remoteSlot = remoteIndex % _remoteInfo.remoteRegions.size();
34
35 // Fast path: a full grain is transferred, can do one write no matter how many planes
36 if ((sliceRange.start() == 0) && (sliceRange.end() == _layout.totalSlices))
37 {
38 _pending += ep.write(_token, localGrain, remoteGrain, destAddr, std::make_optional(ImmDataGrain{remoteSlot, _layout.totalSlices}.data()));
39 return;
40 }
41
42 auto const planeCount = _layout.activePlaneCount();
43 for (std::size_t plane = 0; plane < planeCount; ++plane)
44 {
45 auto const sliceSize = _layout.sliceSizes[plane];
46 auto offset = std::uint32_t{0};
47 auto size = std::uint32_t{0};
48
49 if (plane == 0)
50 {
51 // need to include header with slice 0-x
52 if (sliceRange.start() == 0)
53 {
54 offset = sliceRange.transferOffset(0, sliceSize);
55 size = sliceRange.transferSize(sliceSize) + payloadOffset;
56 }
57 else
58 {
59 offset = sliceRange.transferOffset(payloadOffset, sliceSize);
60 size = sliceRange.transferSize(sliceSize);
61 }
62 }
63 else
64 {
65 auto const planeBase = _layout.planePayloadOffset(plane, payloadOffset);
66 offset = sliceRange.transferOffset(planeBase, sliceSize);
67 size = sliceRange.transferSize(sliceSize);
68 }
69
70 auto const localRegion = localGrain.sub(offset, size);
71 auto const remoteRegion = remoteGrain.sub(offset, size);
72
73 auto const isLastPlane = (plane == planeCount - 1);
74 auto const immData = isLastPlane ? std::make_optional(ImmDataGrain{remoteSlot, sliceRange.end()}.data()) : std::nullopt;
75
76 _pending += ep.write(_token, localRegion, remoteRegion, destAddr, immData);
77 }
78 }
79
80 void RMAGrainEgressProtocol::transferSamples(Endpoint const&, std::uint64_t, std::size_t, ::fi_addr_t)
81 {
82 throw Exception::invalidState("transferSamples is not supported in RMAGrainEgressProtocol.");
83 }
84
86 {
87 if (_pending > 0)
88 {
89 --_pending;
90 }
91 }
92
94 {
95 return _pending > 0;
96 }
97
99 {
100 return std::exchange(_pending, 0);
101 }
102
104 : _layout{layout}
105 , _regions{std::move(regions)}
106 {}
107
108 void RMAGrainEgressProtocolTemplate::registerMemory(std::shared_ptr<Domain> domain)
109 {
110 if (_localRegions)
111 {
112 throw Exception::invalidState("Memory already registered.");
113 }
114
115 domain->registerRegions(_regions, FI_WRITE);
116 _localRegions = domain->localRegions();
117 }
118
119 std::unique_ptr<EgressProtocol> RMAGrainEgressProtocolTemplate::createInstance(Completion::Token token, TargetInfo remoteInfo)
120 {
121 if (!_localRegions)
122 {
123 throw Exception::invalidState("Cannot create protocol before memory is registered.");
124 }
125
126 struct MakeUniqueEnabler : RMAGrainEgressProtocol
127 {
128 MakeUniqueEnabler(Completion::Token token, TargetInfo info, DataLayout::Discrete layout, std::vector<LocalRegion> localRegion)
129 : RMAGrainEgressProtocol{token, std::move(info), layout, std::move(localRegion)}
130 {}
131 };
132
133 return std::make_unique<MakeUniqueEnabler>(token, std::move(remoteInfo), _layout, *_localRegions);
134 }
135
137 std::size_t bounceBufferEntryCount)
138 : _token{token}
139 , _remoteInfo{std::move(info)}
140 , _layout{layout}
141 , _localRegion{localRegion}
142 , _entryHeaders{bounceBufferEntryCount}
143 , _bounceBufferEntryCount{bounceBufferEntryCount}
144 {}
145
146 void RMASampleEgressProtocol::registerMemory(std::shared_ptr<Domain> domain)
147 {
148 if (_entryHeaders.empty())
149 {
150 throw Exception::invalidState("Entry headers buffer are not initialized.");
151 }
152
153 auto entryHeaderRegions = std::vector<Region>{};
154 entryHeaderRegions.reserve(_entryHeaders.size());
155 for (auto& header : _entryHeaders)
156 {
157 entryHeaderRegions.emplace_back(reinterpret_cast<std::uintptr_t>(&header),
158 sizeof(AudioEntryHeader),
159 nullptr,
160 nullptr,
161 Region::Location::host()); // Host, because the bounce buffer will always be stored on host memory.
162 }
163
164 // The domain is shared with all endpoints, if there's more than 1 target, we can't assume that the first audio header entry for this target
165 // will be at index 1 (right after the audio samples buffer). Read the number of regions already registered to the domain, then
166 // register the entry header regions, and finally get the local regions again to retrieve the actual regions corresponding to the entry
167 // headers we just registered. Use the offset to correctly get the entry header regions in the list of local regions.
168 auto const offset = domain->localRegions().size();
169 domain->registerRegions(entryHeaderRegions, FI_WRITE);
170 auto const localRegions = domain->localRegions();
171
172 _entryHeaderRegions = std::vector(localRegions.cbegin() + static_cast<std::ptrdiff_t>(offset), localRegions.cend());
173 }
174
175 void RMASampleEgressProtocol::transferGrain(Endpoint const&, std::uint64_t, std::uint64_t, std::uint32_t, SliceRange const&, ::fi_addr_t)
176 {
177 throw Exception::invalidState("transferGrain is not supported in RMASampleEgressProtocol.");
178 }
179
180 void RMASampleEgressProtocol::transferSamples(Endpoint const& ep, std::uint64_t headIndex, std::size_t count, ::fi_addr_t destAddr)
181 {
182 if (count == 0)
183 {
184 throw Exception::invalidArgument("Count must be greater than 0.");
185 }
186
187 auto const entrySizeRequired = (_layout.sampleSize * _layout.channelCount * count) + sizeof(AudioEntryHeader);
188 if (entrySizeRequired > _remoteInfo.bounceBufferInfo->entrySize)
189 {
190 throw Exception::invalidArgument("Count is too large for the bounce buffer entry size. Count {}, entry size {}, required entry size {}.",
191 count,
192 _remoteInfo.bounceBufferInfo->entrySize,
193 entrySizeRequired);
194 }
195
196 // 1- Create the scatter-gather list for the transfer and prepend the audio header.
197 auto sgl = makeScatterGatherList(_layout, headIndex, count, _localRegion);
198 // set the header and prepend it to the scatter-gather list.
199 _entryHeaders[_bounceBufferEntryIndex].headIndex = headIndex;
201 sgl.insert(sgl.begin(), _entryHeaderRegions[_bounceBufferEntryIndex]);
202
203 // 2- Get the remote region
204 auto const remoteRegion = _remoteInfo.remoteRegions[_bounceBufferEntryIndex % _remoteInfo.remoteRegions.size()];
205
206 // 3- Send the remote write
207 _pending += ep.write(_token, sgl, remoteRegion, destAddr, _bounceBufferEntryIndex);
208
209 // 4- update bounce buffer entry index for the next transfer
211 }
212
214 {
215 if (_pending > 0)
216 {
217 --_pending;
218 }
219 }
220
222 {
223 return _pending > 0;
224 }
225
227 {
228 return std::exchange(_pending, 0);
229 }
230
231 std::vector<LocalRegion> RMASampleEgressProtocol::makeScatterGatherList(DataLayout::Continuous const& layout, std::uint64_t headIndex,
232 std::size_t count, LocalRegion const& region)
233 {
236 count,
237 layout.bufferLength,
238 layout.sampleSize,
239 layout.channelCount,
240 reinterpret_cast<std::uint8_t*>(region.addr), // NOLINT
241 slice);
242
243 // Double the scatter-gather list length if the second fragment is present.
244 auto const sgListLen = (slice.base.fragments[1].size > 0) ? 2 * slice.count : slice.count;
245
246 // Create the scatter-gather list using the slices. We create at least one scatter-gather entry per channel. We potentially create an
247 // additional one per channel if 2 fragments are present (wrap-around). When a fragment is not present its size will be 0.
248 auto sgList = std::vector<LocalRegion>{};
249 sgList.reserve(sgListLen);
250 // Write all fragments for one channel before moving to the next channel.
251 // Doing otherwise (fragment first) only works when source and target wrapped slices split at the same fragment sizes.
252 // If source and target have different ring positions, the target consumes the bytes with different fragment sizes and "stitches" the channel
253 // data back together incorrectly.
254 for (auto chan = std::size_t{0}; chan < slice.count; chan++)
255 {
256 for (auto const& fragment : slice.base.fragments)
257 {
258 // check if the fragment present
259 if (fragment.size > 0)
260 {
261 auto const srcAddr = reinterpret_cast<std::uintptr_t>(fragment.pointer) + (slice.stride * chan);
262
263 sgList.emplace_back(LocalRegion{.addr = srcAddr, .len = fragment.size, .desc = region.desc});
264 }
265 }
266 }
267
268 return sgList;
269 }
270
275
276 void RMASampleEgressProtocolTemplate::registerMemory(std::shared_ptr<Domain> domain)
277 {
278 // This function should be called once during setup and be the first memory to register, otherwise it's a bug.
279 if (_localRegion)
280 {
281 throw Exception::invalidState("Memory already registered.");
282 }
283 if (!domain->localRegions().empty())
284 {
285 throw Exception::invalidState("No memory should be previously registered.");
286 }
287
288 // Register the audio region provided by the user. When the actual protocol instance is created, the protocol will register additional
289 // regions for the bounce buffer entry headers, but we can only do that once we have the actual protocol instance since the bounce buffer
290 // entry count is a parameter of the protocol instance.
291 domain->registerRegion(_region, FI_WRITE);
292
293 _localRegion = domain->localRegions().front();
294 }
295
296 std::unique_ptr<EgressProtocol> RMASampleEgressProtocolTemplate::createInstance(Completion::Token token, TargetInfo remoteInfo)
297 {
298 if (!_localRegion)
299 {
300 throw Exception::invalidState("Cannot create protocol before memory is registered.");
301 }
302
303 if (!remoteInfo.bounceBufferInfo)
304 {
305 throw Exception::invalidArgument("Remote target does not have bounce buffer info required for sample egress protocol.");
306 }
307
308 struct MakeUniqueEnabler : RMASampleEgressProtocol
309 {
310 MakeUniqueEnabler(Completion::Token token, TargetInfo info, DataLayout::Continuous layout, LocalRegion localRegion,
311 std::uint32_t bounceBufferEntryCount)
312 : RMASampleEgressProtocol{token, std::move(info), layout, localRegion, bounceBufferEntryCount}
313 {}
314 };
315
316 return std::make_unique<MakeUniqueEnabler>(token, std::move(remoteInfo), _layout, *_localRegion, remoteInfo.bounceBufferInfo->entryCount);
317 };
318}
static void getMutableMultiBufferSlices(std::uint64_t index, std::size_t count, std::size_t bufferLength, std::size_t sampleWordSize, std::size_t channelCount, std::uint8_t *baseBufferPtr, mxlMutableWrappedMultiBufferSlice &slice) noexcept
Type to represent a completion entry from a CompletionQueue.
std::uintptr_t Token
A token used to associate a completion entry with an endpoint.
RAII Wrapper around a libfabric endpoint (fi_ep).
Definition Endpoint.hpp:29
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
static Exception invalidArgument(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_ARG exception.
Definition Exception.hpp:43
static Exception invalidState(fmt::format_string< T... > fmt, T &&... args)
Make an MXL_ERR_INVALID_STATE exception.
Definition Exception.hpp:59
Immediate data representation for discrete flow transfers.
Definition ImmData.hpp:15
std::uint32_t data() const noexcept
Get the packed immediate data.
Definition ImmData.cpp:27
virtual void registerMemory(std::shared_ptr< Domain > domain) override
Register memory required by the protocol.
std::optional< std::vector< LocalRegion > > _localRegions
RMAGrainEgressProtocolTemplate(DataLayout::Discrete layout, std::vector< Region > regions)
virtual std::unique_ptr< EgressProtocol > createInstance(Completion::Token, TargetInfo remoteInfo) override
Create a new instance of the protocol for a remote target.
virtual std::size_t reset() final
Destroy the protocol object.
virtual void processCompletion(Completion const &) final
Process a completion event. Any post-processing after a transfer should be done here.
virtual void transferSamples(Endpoint const &, std::uint64_t, std::size_t, ::fi_addr_t) final
Transfer samples to a remote target.
virtual bool hasPendingWork() const final
Check if there is uncompleted requests.
virtual void registerMemory(std::shared_ptr< Domain > domain) final
Register local memory regions used in this protocol.
virtual void transferGrain(Endpoint const &ep, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint32_t payloadOffset, SliceRange const &sliceRange, ::fi_addr_t destAddr=FI_ADDR_UNSPEC) final
Transfer a grain to a remote target.
RMAGrainEgressProtocol(Completion::Token token, TargetInfo info, DataLayout::Discrete dataLayout, std::vector< LocalRegion > _localRegions)
virtual void registerMemory(std::shared_ptr< Domain > domain) override
Register memory required by the protocol.
virtual std::unique_ptr< EgressProtocol > createInstance(Completion::Token, TargetInfo remoteInfo) override
Create a new instance of the protocol for a remote target.
RMASampleEgressProtocolTemplate(DataLayout::Continuous layout, Region region)
virtual void processCompletion(Completion const &) final
Process a completion event. Any post-processing after a transfer should be done here.
virtual void registerMemory(std::shared_ptr< Domain > domain) final
Register local memory regions used in this protocol.
virtual void transferSamples(Endpoint const &ep, std::uint64_t headIndex, std::size_t count, ::fi_addr_t destAddr=FI_ADDR_UNSPEC) final
Transfer samples to a remote target.
virtual std::size_t reset() final
Destroy the protocol object.
RMASampleEgressProtocol(Completion::Token token, TargetInfo info, DataLayout::Continuous dataLayout, LocalRegion _localRegion, std::size_t bounceBufferEntryCount)
virtual void transferGrain(Endpoint const &ep, std::uint64_t localIndex, std::uint64_t remoteIndex, std::uint32_t payloadOffset, SliceRange const &sliceRange, ::fi_addr_t destAddr=FI_ADDR_UNSPEC) final
Transfer a grain to a remote target.
virtual bool hasPendingWork() const final
Check if there is uncompleted requests.
static std::vector< LocalRegion > makeScatterGatherList(DataLayout::Continuous const &layout, std::uint64_t headIndex, std::size_t count, LocalRegion const &region)
Create the scatter-gather list for a given audio region and data layout. This will be used for the re...
static Location host() noexcept
specify a host memory location.
Definition Region.cpp:23
Represent a memory region (unregistered).
Definition Region.hpp:24
A SliceRange represents a range of slices within a grain.
std::uint32_t transferSize(std::uint32_t sliceSize) const noexcept
Get the size of the range (end - start).
std::uint32_t transferOffset(std::uint32_t payloadOffset, std::uint32_t sliceSize) const noexcept
Get the offset within the payload for the start of the range.
std::uint16_t end() const noexcept
Get the exclusive end of the range.
std::uint16_t start() const noexcept
Get the inclusive start of the range.
struct mxlMutableWrappedMultiBufferSlice_t mxlMutableWrappedMultiBufferSlice
std::size_t size() const noexcept
Returns the total number of writers that are registered in the DomainWatcher.
std::size_t count(uuids::uuid id) const noexcept
Returns the number of writers registered for flow id 'id'.
Header for an audio bounce buffer entry.
Continuous layout variant of DataLayout.
Discrete layout variant of DataLayout.
Represent a source memory region used for for data transfer.
TargetInfo contains all the information required by an initiator to operate transfers to the given ta...
std::optional< TargetInfoBounceBufferInfo > bounceBufferInfo