CIRCT 24.0.0git
Loading...
Searching...
No Matches
Ports.cpp
Go to the documentation of this file.
1//===- Ports.cpp - ESI communication channels -------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// DO NOT EDIT!
10// This file is distributed as part of an ESI package. The source for this file
11// should always be modified within CIRCT (lib/dialect/ESI/runtime/cpp/).
12//
13//===----------------------------------------------------------------------===//
14
15#include "esi/Ports.h"
16#include "esi/Types.h"
17
18#include <algorithm>
19#include <atomic>
20#include <chrono>
21#include <cstring>
22#include <map>
23#include <stdexcept>
24
25using namespace esi;
26
28 if (auto chanType = dynamic_cast<const ChannelType *>(type))
29 type = chanType->getInner();
30 auto translationType = dynamic_cast<const WindowType *>(type);
31 if (translationType) {
32 this->type = translationType->getIntoType();
33 this->translationInfo = std::make_unique<TranslationInfo>(translationType);
34 } else {
35 this->type = type;
36 this->translationInfo = nullptr;
37 }
38}
39
42
43WriteChannelPort &BundlePort::getRawWrite(const std::string &name) const {
44 auto f = channels.find(name);
45 if (f == channels.end())
46 throw std::runtime_error("Channel '" + name + "' not found");
47 auto *write = dynamic_cast<WriteChannelPort *>(&f->second);
48 if (!write)
49 throw std::runtime_error("Channel '" + name + "' is not a write channel");
50 return *write;
51}
52
53ReadChannelPort &BundlePort::getRawRead(const std::string &name) const {
54 auto f = channels.find(name);
55 if (f == channels.end())
56 throw std::runtime_error("Channel '" + name + "' not found");
57 auto *read = dynamic_cast<ReadChannelPort *>(&f->second);
58 if (!read)
59 throw std::runtime_error("Channel '" + name + "' is not a read channel");
60 return *read;
61}
62
70
72 {
73 std::unique_lock<std::mutex> lock(callbackMutex);
74 // Revoke the callback under the same mutex used by invokeCallback(). New
75 // deliveries need to observe the disconnected state and the callback
76 // nullification at the same time.
77 callback = nullptr;
79 // Wait for any callback which already snapped the old function to finish
80 // before clearing per-connection state below.
81 callbackCv.wait(lock, [this]() { return activeCallbacks == 0; });
82 }
83
84 pollingState.reset();
86}
87
89 std::unique_ptr<SegmentedMessageData> &msg) {
90 ReadCallback activeCallback;
91 {
92 std::lock_guard<std::mutex> lock(callbackMutex);
93 // Check the disconnected state and snapshot the callback while holding the
94 // same mutex as disconnect(). That prevents disconnect() from clearing the
95 // callback after we decide to invoke it but before we've retained our own
96 // safe local copy.
98 return false;
99 assert(callback && "Callback should be set in non-disconnected mode");
100 activeCallback = callback;
101 // Count only callbacks which successfully captured a callable target.
102 // disconnect() waits on this count so it can safely tear down state which
103 // the callback path may still reference.
105 }
106
107 // Release the in-flight slot on every exit path, including exceptions from
108 // the callback itself.
109 auto finish = [this]() {
110 std::lock_guard<std::mutex> lock(callbackMutex);
111 assert(activeCallbacks > 0 && "Callback count underflow");
113 if (activeCallbacks == 0)
114 callbackCv.notify_all();
115 };
116
117 try {
118 // For zero-width port types (e.g. `VoidType`), transports which require
119 // every message to be at least one byte send a single placeholder byte;
120 // strip it. Empty messages are also accepted, both from transports which
121 // support them and from backends re-delivering a message the callback
122 // previously rejected (and which was already stripped). Anything else is
123 // malformed transport data. The matching pad happens in
124 // `WriteChannelPort::maybePadEmptyMessage`.
125 if (msg && type && type->getBitWidth() == 0) {
126 size_t size = msg->totalSize();
127 if (size == 1)
128 msg = std::make_unique<MessageData>();
129 else if (size != 0)
130 throw std::runtime_error("zero-width message must be empty or use a "
131 "single-byte placeholder payload");
132 }
133
134 bool consumed = activeCallback(msg);
135 finish();
136 return consumed;
137 } catch (...) {
138 finish();
139 throw;
140 }
141}
142
144 const ConnectOptions &options) {
146 throw std::runtime_error("Channel already connected");
147
149
150 if (translationInfo)
151 translationInfo->precomputeFrameInfo();
152
153 if (options.translateMessage && translationInfo) {
154 translationInfo->requireTranslationSupported();
155 this->callback = [this, cb = std::move(callback)](
156 std::unique_ptr<SegmentedMessageData> &data) {
157 if (!translatedMessage) {
158 MessageData flat = data->toMessageData();
159 if (!translateIncoming(flat))
160 return true;
162 std::make_unique<MessageData>(std::move(translationBuffer));
163 }
164
165 if (!cb(translatedMessage))
166 return false;
167
168 translatedMessage.reset();
169 return true;
170 };
171 } else {
172 this->callback = callback;
173 }
174 connectImpl(options);
176}
177
179 const ConnectOptions &options) {
180 connect(
181 [cb = std::move(callback)](std::unique_ptr<SegmentedMessageData> &data)
182 -> bool { return cb(data->toMessageData()); },
183 options);
184}
185
188 throw std::runtime_error("Channel already connected");
189
190 if (options.bufferSize.has_value())
191 maxDataQueueMsgs = options.bufferSize.value();
193
195
196 if (translationInfo)
197 translationInfo->precomputeFrameInfo();
198
199 bool translate = options.translateMessage && translationInfo;
200 if (translate)
201 translationInfo->requireTranslationSupported();
202 this->callback = [this,
203 translate](std::unique_ptr<SegmentedMessageData> &msg) {
204 MessageData data;
205 if (translate) {
206 if (!translatedMessage) {
207 MessageData flat = msg->toMessageData();
208 if (!translateIncoming(flat))
209 return true;
211 std::make_unique<MessageData>(std::move(translationBuffer));
212 }
213 data = translatedMessage->toMessageData();
214 } else {
215 data = msg->toMessageData();
216 }
217
218 if (!pollingState->enqueue(data))
219 return false;
220
221 translatedMessage.reset();
222 return true;
223 };
224 connectImpl(options);
226}
227
228std::future<MessageData> ReadChannelPort::readAsync() {
229 if (mode == Mode::Callback)
230 throw std::runtime_error(
231 "Cannot read from a callback channel. Call `connect()` without a "
232 "callback specified to use polling mode.");
234 throw std::runtime_error(
235 "Cannot read from a disconnected channel. `connect()` the channel "
236 "without a callback before calling `readAsync()`.");
237
238 assert(mode == Mode::Polling && "Channel must be in polling mode to read");
239 assert(pollingState && "Polling state should be initialized in polling mode");
240
241 return pollingState->readAsync();
242}
243
244//===----------------------------------------------------------------------===//
245// Window translation support
246//===----------------------------------------------------------------------===//
247
249 // Reject serial-encoded windows: any field with bulkCountWidth > 0 indicates
250 // serial (bulk) encoding, which the translator does not yet support. Surface
251 // this clearly at connect()-time rather than silently buffering forever in
252 // translateIncoming().
253 for (const auto &frame : windowType->getFrames()) {
254 for (const auto &field : frame.fields) {
255 if (field.bulkCountWidth > 0)
256 throw std::runtime_error(
257 "Window translation for serial (bulk) list encoding is not "
258 "implemented (window '" +
259 windowType->getName() + "', frame '" + frame.name + "', field '" +
260 field.name +
261 "'). Connect the port with ConnectOptions{translateMessage=false} "
262 "and decode the frames manually.");
263 }
264 }
265}
266
268 const Type *intoType = windowType->getIntoType();
269
270 const StructType *intoStruct = dynamic_cast<const StructType *>(intoType);
271 if (!intoStruct)
272 throw std::runtime_error(
273 "Window intoType must be a struct for translation");
274
275 const auto &intoFields = intoStruct->getFields();
276
277 // Build a map from field name to (offset, type, isListField).
278 // For list fields, the offset is where the list_length field will be stored,
279 // and we also track the element type.
280 struct FieldInfo {
281 size_t offset;
282 const Type *type;
283 bool isList;
284 const Type *listElementType; // Only valid if isList is true
285 size_t listElementSize; // Only valid if isList is true
286 };
287 std::map<std::string, FieldInfo> fieldMap;
288 size_t currentOffset = 0;
289 hasListField = false;
290
291 auto processField = [&](const std::string &name, const Type *fieldType) {
292 auto *listType = dynamic_cast<const ListType *>(fieldType);
293 if (listType) {
294 hasListField = true;
295 // For list fields in the intoType:
296 // - We store a list_length (size_t / 8 bytes) followed by the list data
297 // - The offset here is where the list_length goes
298 const Type *elemType = listType->getElementType();
299 std::ptrdiff_t elemBits = elemType->getBitWidth();
300 if (elemBits < 0)
301 throw std::runtime_error(
302 "Cannot translate list with dynamically-sized element type: " +
303 name);
304 if (elemBits == 0)
305 throw std::runtime_error(
306 "Cannot translate list with zero-width element type: " + name);
307 if (elemBits % 8 != 0)
308 throw std::runtime_error(
309 "Cannot translate list element with non-byte-aligned size: " +
310 name);
311 size_t elemBytes = (static_cast<size_t>(elemBits) + 7) / 8;
312 fieldMap[name] = {currentOffset, fieldType, true, elemType, elemBytes};
313 // Reserve space for list_length. We use size_t (8 bytes on 64-bit
314 // platforms) for consistency with standard C/C++ container sizes.
315 // Note: This means the translated message format is platform-dependent.
316 currentOffset += sizeof(size_t);
317 // List data will be appended dynamically after the fixed header
318 } else {
319 std::ptrdiff_t fieldBits = fieldType->getBitWidth();
320 if (fieldBits < 0)
321 throw std::runtime_error("Cannot translate field with dynamic size: " +
322 name);
323 if (fieldBits % 8 != 0)
324 throw std::runtime_error(
325 "Cannot translate field with non-byte-aligned size: " + name);
326 size_t fieldBytes = (static_cast<size_t>(fieldBits) + 7) / 8;
327 fieldMap[name] = {currentOffset, fieldType, false, nullptr, 0};
328 currentOffset += fieldBytes;
329 }
330 };
331
332 if (intoStruct->isReverse()) {
333 for (auto it = intoFields.rbegin(); it != intoFields.rend(); ++it)
334 processField(it->first, it->second);
335 } else {
336 for (const auto &[name, fieldType] : intoFields)
337 processField(name, fieldType);
338 }
339
340 // intoTypeBytes is now the size of the fixed header portion
341 // (for types with lists, this excludes the variable-length list data)
342 intoTypeBytes = currentOffset;
343
344 const auto &windowFrames = windowType->getFrames();
345 frames.clear();
346 frames.reserve(windowFrames.size());
347
348 for (const auto &frame : windowFrames) {
349 FrameInfo frameInfo;
350 size_t frameOffset = 0;
351
352 // Calculate frame layout in SV memory order.
353 // SV structs are laid out with the last declared field at the lowest
354 // address. So when we iterate fields in reverse order (rbegin to rend),
355 // we get the memory layout order.
356 //
357 // For list fields, the lowered struct in CIRCT adds fields in this order:
358 // 1. list_data[numItems] - array of list elements
359 // 2. list_size - (if numItems > 1) count of valid items
360 // 3. last - indicates end of list
361 //
362 // In SV memory layout (reversed), this becomes:
363 // offset 0: last (1 byte)
364 // offset 1: list_size (if present)
365 // offset after size: list_data[numItems]
366 // offset after list: header fields...
367 struct FrameFieldLayout {
368 std::string name;
369 size_t frameOffset;
370 size_t size;
371 bool isList;
372 size_t numItems; // From window spec
373 size_t listElementSize; // Size of each list element
374 size_t bufferOffset; // Offset in translation buffer
375 const Type *listElementType; // Element type for list fields
376 };
377 std::vector<FrameFieldLayout> fieldLayouts;
378
379 for (auto fieldIt = frame.fields.rbegin(); fieldIt != frame.fields.rend();
380 ++fieldIt) {
381 const WindowType::Field &field = *fieldIt;
382 auto it = fieldMap.find(field.name);
383 if (it == fieldMap.end())
384 throw std::runtime_error("Frame field '" + field.name +
385 "' not found in intoType");
386
387 const FieldInfo &fieldInfo = it->second;
388 FrameFieldLayout layout;
389 layout.name = field.name;
390 layout.bufferOffset = fieldInfo.offset;
391 layout.isList = fieldInfo.isList;
392 layout.numItems = field.numItems;
393 layout.listElementType = fieldInfo.listElementType;
394 layout.listElementSize = fieldInfo.listElementSize;
395
396 if (fieldInfo.isList) {
397 // For list fields, the frame layout is (in memory order):
398 // 1. 'last' field (1 byte)
399 // 2. list_data (one element per frame)
400 // Note: numItems > 1 is not yet supported.
401 size_t numItems = field.numItems > 0 ? field.numItems : 1;
402 if (numItems != 1)
403 throw std::runtime_error(
404 "List translation with numItems > 1 is not yet supported. "
405 "Field '" +
406 field.name + "' has numItems=" + std::to_string(numItems));
407
408 // 'last' field comes first in memory
409 size_t lastOffset = frameOffset;
410 frameOffset += 1;
411
412 // List data comes after 'last'
413 layout.frameOffset = frameOffset;
414 layout.size = fieldInfo.listElementSize;
415 fieldLayouts.push_back(layout);
416 frameOffset += layout.size;
417
418 // Create ListFieldInfo for this list field
419 ListFieldInfo listInfo;
420 listInfo.fieldName = layout.name;
421 listInfo.dataOffset = layout.frameOffset;
422 listInfo.elementSize = fieldInfo.listElementSize;
423 listInfo.listLengthBufferOffset = layout.bufferOffset;
425 listInfo.lastFieldOffset = lastOffset;
426 frameInfo.listField = listInfo;
427 } else {
428 // Regular (non-list) field
429 std::ptrdiff_t fieldBits = fieldInfo.type->getBitWidth();
430 layout.frameOffset = frameOffset;
431 layout.size = (static_cast<size_t>(fieldBits) + 7) / 8;
432 fieldLayouts.push_back(layout);
433 frameOffset += layout.size;
434 }
435 }
436
437 frameInfo.expectedSize = frameOffset;
438
439 // Second pass: build copy ops for non-list fields
440 for (const auto &layout : fieldLayouts) {
441 if (!layout.isList) {
442 // Regular field - add copy op
443 frameInfo.copyOps.push_back(
444 {layout.frameOffset, layout.bufferOffset, layout.size});
445 }
446 // List fields were already handled in the first pass
447 }
448
449 // Sort copy ops by frameOffset to ensure processing order matches frame
450 // layout.
451 std::sort(frameInfo.copyOps.begin(), frameInfo.copyOps.end(),
452 [](const CopyOp &a, const CopyOp &b) {
453 return a.frameOffset < b.frameOffset;
454 });
455
456 // Merge adjacent copy ops
457 if (!frameInfo.copyOps.empty()) {
458 std::vector<CopyOp> mergedOps;
459 mergedOps.push_back(frameInfo.copyOps[0]);
460
461 for (size_t i = 1; i < frameInfo.copyOps.size(); ++i) {
462 CopyOp &last = mergedOps.back();
463 CopyOp current = frameInfo.copyOps[i];
464
465 if (last.frameOffset + last.size == current.frameOffset &&
466 last.bufferOffset + last.size == current.bufferOffset) {
467 last.size += current.size;
468 } else {
469 mergedOps.push_back(current);
470 }
471 }
472
473 frameInfo.copyOps = std::move(mergedOps);
474 }
475
476 frames.push_back(std::move(frameInfo));
477 }
478
479 // Set frameBytes from the lowered type's bit width. Fall back to the
480 // maximum computed frame expectedSize if the type system can't report width
481 // (e.g. opaque union types).
482 std::ptrdiff_t loweredBits = windowType->getLoweredType()->getBitWidth();
483 if (loweredBits > 0) {
484 frameBytes = (loweredBits + 7) / 8;
485 } else {
486 frameBytes = 0;
487 for (const auto &f : frames)
488 frameBytes = std::max(frameBytes, f.expectedSize);
489 }
490}
491
494 "Translation type must be set for window translation.");
495
496 // Get the frame data directly.
497 const uint8_t *frameData = data.getBytes();
498 size_t frameDataSize = data.size();
499
500 // Get the frame metadata for the current expected frame.
501 const auto &frameInfo = translationInfo->frames[nextFrameIndex];
502
503 // Check size
504 if (frameDataSize < frameInfo.expectedSize)
505 throw std::runtime_error("Frame data too small: expected at least " +
506 std::to_string(frameInfo.expectedSize) +
507 " bytes, got " + std::to_string(frameDataSize) +
508 " bytes");
509
510 // Check if this is the first frame of a new message.
511 // For list frames, we use accumulatingListData to track whether we're
512 // continuing to accumulate list items.
513 bool isFirstFrame = (nextFrameIndex == 0) && !accumulatingListData;
514
515 if (isFirstFrame) {
516 // Initialize the translation buffer to hold the fixed header portion.
517 translationBuffer.resize(translationInfo->intoTypeBytes, 0);
518 // Clear list data buffer for types with lists
519 if (translationInfo->hasListField)
520 listDataBuffer.clear();
521 }
522
523 // Execute copy ops for non-list fields
524 for (const auto &op : frameInfo.copyOps)
525 std::memcpy(translationBuffer.data() + op.bufferOffset,
526 frameData + op.frameOffset, op.size);
527
528 // Handle list field if present in this frame
529 if (frameInfo.listField.has_value()) {
530 const auto &listInfo = frameInfo.listField.value();
531
532 // With numItems == 1, each frame contains exactly one list element
533 size_t bytesToCopy = listInfo.elementSize;
534 // Additional check: dataOffset must not be beyond frameDataSize
535 if (listInfo.dataOffset > frameDataSize)
536 throw std::runtime_error("List data offset is beyond frame bounds");
537 // Bounds check to prevent buffer overflow from corrupted _size field
538 if (listInfo.dataOffset + bytesToCopy > frameDataSize)
539 throw std::runtime_error("List data extends beyond frame bounds");
540 size_t oldSize = listDataBuffer.size();
541 listDataBuffer.resize(oldSize + bytesToCopy);
542 std::memcpy(listDataBuffer.data() + oldSize,
543 frameData + listInfo.dataOffset, bytesToCopy);
544
545 // Check if this is the last frame of the list
546 uint8_t lastFlag = frameData[listInfo.lastFieldOffset];
547 if (lastFlag) {
548 // List is complete. Build the final message:
549 // [fixed header with list_length (size_t)][list data...]
550 // Write the actual length to the listLengthBufferOffset position.
551 size_t listLength = listDataBuffer.size() / listInfo.elementSize;
552 size_t *listLengthPtr = reinterpret_cast<size_t *>(
553 translationBuffer.data() + listInfo.listLengthBufferOffset);
554 *listLengthPtr = listLength;
555
556 // Append list data to translation buffer
557 size_t headerSize = translationBuffer.size();
558 translationBuffer.resize(headerSize + listDataBuffer.size());
559 std::memcpy(translationBuffer.data() + headerSize, listDataBuffer.data(),
560 listDataBuffer.size());
561
562 // Reset for next message
563 nextFrameIndex = 0;
564 listDataBuffer.clear();
565 accumulatingListData = false;
566 return true;
567 }
568
569 // Not the last frame - stay on this frame index for list accumulation
570 // (list frames repeat until last=true)
572 return false;
573 }
574
575 // No list field in this frame - advance to next frame
577 size_t numFrames = translationInfo->frames.size();
578
579 // Check if all frames have been received.
580 if (nextFrameIndex >= numFrames) {
581 // Reset for the next message.
582 nextFrameIndex = 0;
583 return true;
584 }
585
586 return false;
587}
588
591 "Translation type must be set for window translation.");
592
593 const uint8_t *srcData = data.getBytes();
594 size_t srcDataSize = data.size();
595
596 if (srcDataSize < translationInfo->intoTypeBytes)
597 throw std::runtime_error("Source data too small: expected at least " +
598 std::to_string(translationInfo->intoTypeBytes) +
599 " bytes, got " + std::to_string(srcDataSize) +
600 " bytes");
601
602 // Check if we have list fields
603 if (!translationInfo->hasListField) {
604 // No list fields - simple fixed-size translation
605 for (const auto &frameInfo : translationInfo->frames) {
606 std::vector<uint8_t> frameBuffer(frameInfo.expectedSize, 0);
607 for (const auto &op : frameInfo.copyOps)
608 std::memcpy(frameBuffer.data() + op.frameOffset,
609 srcData + op.bufferOffset, op.size);
610 translationBuffer.emplace_back(std::move(frameBuffer));
611 }
612 return;
613 }
614
615 // Handle list fields - need to split list data into multiple frames
616 for (const auto &frameInfo : translationInfo->frames) {
617 if (!frameInfo.listField.has_value()) {
618 // Non-list frame - copy as normal
619 std::vector<uint8_t> frameBuffer(frameInfo.expectedSize, 0);
620 for (const auto &op : frameInfo.copyOps)
621 std::memcpy(frameBuffer.data() + op.frameOffset,
622 srcData + op.bufferOffset, op.size);
623 translationBuffer.emplace_back(std::move(frameBuffer));
624 } else {
625 // List frame - need to generate multiple frames
626 const auto &listInfo = frameInfo.listField.value();
627
628 // Read the list length from the source data
629 size_t listLength = 0;
630 std::memcpy(&listLength, srcData + listInfo.listLengthBufferOffset,
631 sizeof(size_t));
632
633 // Check that the buffer is large enough for the list data
634 if (translationInfo->intoTypeBytes + (listLength * listInfo.elementSize) >
635 srcDataSize) {
636 throw std::runtime_error(
637 "Source buffer too small for list data: possible corrupted or "
638 "inconsistent list length field");
639 }
640 // Get pointer to list data (after the fixed header)
641 const uint8_t *listData = srcData + translationInfo->intoTypeBytes;
642
643 // Generate frames for the list
644 size_t itemsRemaining = listLength;
645 size_t listDataOffset = 0;
646
647 // Handle empty list case - still need to send one frame with last=true
648 if (listLength == 0)
649 throw std::runtime_error(
650 "Cannot send empty lists - parallel ESI list encoding requires at "
651 "least one frame to be sent, and each frame must contain at least "
652 "one element.");
653
654 while (itemsRemaining > 0) {
655 std::vector<uint8_t> frameBuffer(frameInfo.expectedSize, 0);
656
657 // Copy non-list fields (header data) to each frame
658 for (const auto &op : frameInfo.copyOps)
659 std::memcpy(frameBuffer.data() + op.frameOffset,
660 srcData + op.bufferOffset, op.size);
661
662 // With numItems == 1, each frame contains exactly one list element
663 size_t bytesInThisFrame = listInfo.elementSize;
664
665 // Copy list data
666 std::memcpy(frameBuffer.data() + listInfo.dataOffset,
667 listData + listDataOffset, bytesInThisFrame);
668
669 // Update remaining count
670 itemsRemaining -= 1;
671 listDataOffset += bytesInThisFrame;
672
673 // Set last field
674 frameBuffer[listInfo.lastFieldOffset] = (itemsRemaining == 0) ? 1 : 0;
675
676 translationBuffer.emplace_back(std::move(frameBuffer));
677 }
678 }
679 }
680}
681
682std::vector<MessageData>
684 size_t frameBytes = getFrameSizeBytes();
685 assert(frameBytes > 0 && "Frame size must be greater than 0");
686 if (data.getSize() % frameBytes != 0)
687 throw std::runtime_error(
688 "write message size (" + std::to_string(data.getSize()) +
689 ") is not a multiple of frame size (" + std::to_string(frameBytes) +
690 ") on type " + type->toString());
691 std::vector<MessageData> frames;
692 size_t numFrames = data.getSize() / frameBytes;
693 const uint8_t *ptr = data.getBytes();
694 for (size_t i = 0; i < numFrames; ++i) {
695 frames.emplace_back(ptr, frameBytes);
696 ptr += frameBytes;
697 }
698 return frames;
699}
700
701//===----------------------------------------------------------------------===//
702// WriteChannelPort
703//===----------------------------------------------------------------------===//
704
709
710 /// Stop this connection: after this returns, it doesn't touch the port
711 /// again. Waits for another thread writing on it to stop.
712 void stop() {
713 // Set before waiting, so a writer on another thread drops what it fetches
714 // meanwhile.
715 stopped = true;
716 std::lock_guard<std::recursive_mutex> lock(mutex);
717 pendingMsg.reset();
718 }
719
720 /// Mark that the DataFetchCallback may have data, then poll().
721 void notify() {
722 dataAvailable = true;
723 poll();
724 }
725
726 /// Write fetched data (fetching more as needed) until the DataFetchCallback
727 /// has none, the backend backpressures, or the connection is stopped. Does
728 /// nothing if another thread is doing so, or if called from a callback.
729 void poll();
730
731private:
732 enum class DrainResult {
733 /// The DataFetchCallback has no data.
734 Idle,
735 /// The backend backpressured.
736 Blocked,
737 /// Wrote the maximum number of messages for one call.
738 Yielded,
739 /// The connection was stopped.
740 Stopped,
741 };
742 /// The body of poll(). Requires `mutex`.
743 DrainResult drain();
744
748
749 /// Held while writing, including while calling the callbacks. Recursive so
750 /// that the callbacks can disconnect the port or call
751 /// notifyAsyncDataAvailable().
752 std::recursive_mutex mutex;
753 /// Set by the thread holding `mutex` while in drain(), so callbacks don't
754 /// start another one. We need this instead of relying on a normal mutex
755 /// because a normal mutex when 'try_to_lock' is called by the same thread the
756 /// behavior is undefined.
757 bool draining = false;
758 /// Set when the port is disconnected (or reconnected) or destroyed. After
759 /// that, this connection doesn't touch the port.
760 std::atomic<bool> stopped = false;
761 /// False once `fetch` returns nullptr (or throws), until notify() is called.
762 /// Atomic since notify() sets it without `mutex`.
763 std::atomic<bool> dataAvailable = true;
764 /// A fetched message which the port hasn't accepted yet. Guarded by
765 /// `mutex`.
766 std::unique_ptr<SegmentedMessageData> pendingMsg;
767};
768
770 DrainResult result = DrainResult::Idle;
771 do {
772 std::unique_lock<std::recursive_mutex> lock(mutex, std::try_to_lock);
773 if (!lock.owns_lock() || draining)
774 break;
775 draining = true;
776 try {
777 result = drain();
778 } catch (...) {
779 // Thrown by the error callback.
780 draining = false;
781 throw;
782 }
783 draining = false;
784 // Repeat for a notify() which arrived after drain() last checked
785 // `dataAvailable` but before the lock was released, since it couldn't
786 // poll() itself. Otherwise, the next poll() continues.
787 } while (result == DrainResult::Idle && dataAvailable);
788}
789
792 size_t written = 0;
793 while (!stopped) {
794 if (!pendingMsg) {
795 // Leave the rest for the next call.
796 if (written == kMaxAsyncWritesPerCall)
797 return DrainResult::Yielded;
798 // Cleared before fetching, so a notification which arrives while
799 // fetching (and which would be missed if this returns nullptr) isn't
800 // lost.
801 if (!dataAvailable.exchange(false)) {
802 // tryWrite() only sends the rest of a windowed message's frames
803 // before the next message, so with none, send them here.
804 try {
805 return port.flushInternal() ? DrainResult::Idle
806 : DrainResult::Blocked;
807 } catch (...) {
808 port.discardPendingFrames();
809 onError(std::current_exception());
810 continue;
811 }
812 }
813 std::exception_ptr fetchError;
814 try {
815 pendingMsg = fetch();
816 } catch (...) {
817 fetchError = std::current_exception();
818 }
819 // If the callback disconnected the port, drop the message (or error).
820 if (stopped) {
821 pendingMsg.reset();
822 break;
823 }
824 if (fetchError) {
825 onError(fetchError);
826 continue;
827 }
828 if (!pendingMsg)
829 continue;
830 // The callback had data, so it may have more.
831 dataAvailable = true;
832 }
833
834 try {
835 if (!port.tryWriteSegmentedImpl(pendingMsg))
836 return DrainResult::Blocked;
837 ++written;
838 } catch (...) {
839 pendingMsg.reset();
840 port.discardPendingFrames();
841 onError(std::current_exception());
842 }
843 }
844 return DrainResult::Stopped;
845}
846
848
849void WriteChannelPort::requireNotCallbackMode(const char *method) const {
850 if (mode == Mode::Callback)
851 throw std::runtime_error(
852 std::string("Cannot call `") + method +
853 "()` on a write channel connected in callback mode. Use "
854 "`connect()` without callbacks.");
855}
856
859 if (translationInfo) {
860 translationInfo->precomputeFrameInfo();
862 translationInfo->requireTranslationSupported();
863 }
864 connectImpl(options);
865}
866
868 if (mode == Mode::Callback)
869 throw std::runtime_error("Channel already connected in callback mode");
870 connectCommon(options);
872}
873
876 throw std::runtime_error("Channel already connected");
877 if (hasPendingFrames())
878 throw std::runtime_error(
879 "Cannot connect in callback mode while a windowed message written in "
880 "sync mode has unsent frames. Reconnect in sync mode and flush() "
881 "first.");
882 connectCommon(options);
884}
885
887 WriteErrorCallback onError,
888 const ConnectOptions &options) {
889 if (!fetch)
890 throw std::invalid_argument(
891 "WriteChannelPort::connect: null data fetch callback");
892 if (!onError)
893 throw std::invalid_argument(
894 "WriteChannelPort::connect: null error callback");
895 auto writer = std::make_shared<DefaultAsyncWriter>(*this, std::move(fetch),
896 std::move(onError));
897 connectCallbackMode(options);
898 std::lock_guard<std::mutex> lock(asyncWriterMutex);
899 asyncWriter = std::move(writer);
900}
901
903 // Translated frames left over from a callback mode write are dropped. Those
904 // from a sync mode write are kept, to be flushed after reconnecting.
905 bool wasCallbackMode = mode == Mode::Callback;
907 if (wasCallbackMode)
910}
911
912std::shared_ptr<WriteChannelPort::DefaultAsyncWriter>
914 std::lock_guard<std::mutex> lock(asyncWriterMutex);
915 return asyncWriter;
916}
917
919 std::shared_ptr<DefaultAsyncWriter> writer;
920 {
921 std::lock_guard<std::mutex> lock(asyncWriterMutex);
922 writer = std::move(asyncWriter);
923 }
924 if (writer)
925 writer->stop();
926}
927
929 if (mode == Mode::Callback)
930 if (std::shared_ptr<DefaultAsyncWriter> writer = getAsyncWriter())
931 writer->poll();
932 // A callback may have disconnected the port.
933 if (!isConnected())
934 return false;
935 return pollWriteImpl();
936}
937
939 std::shared_ptr<DefaultAsyncWriter> writer =
940 mode == Mode::Callback ? getAsyncWriter() : nullptr;
941 if (!writer)
942 throw std::runtime_error(
943 "Cannot call `notifyAsyncDataAvailable()` on a write channel which "
944 "is not connected in callback mode.");
945 writer->notify();
946}
947
949 if (translateMessages) {
950 assert(translationBuffer.empty() &&
951 "Cannot call write() with pending translated messages");
952 translateOutgoing(data);
953 for (auto &msg : translationBuffer)
955 translationBuffer.clear();
956 } else {
958 }
959}
960
962 if (translateMessages) {
963 // Do not accept a new message if there are pending messages to flush.
964 if (!flushInternal())
965 return false;
966 assert(translationBuffer.empty() &&
967 "Translation buffer should be empty after successful flush");
968 translateOutgoing(data);
969 // If the first frame isn't accepted, don't keep the message: nothing
970 // would flush it unless the caller writes again.
971 if (!translationBuffer.empty() &&
973 translationBuffer.clear();
974 return false;
975 }
978 return true;
979 }
981}
982
993
assert(baseType &&"element must be base type")
PortMap channels
Definition Ports.h:797
ReadChannelPort & getRawRead(const std::string &name) const
Definition Ports.cpp:53
WriteChannelPort & getRawWrite(const std::string &name) const
Get access to the raw byte streams of a channel.
Definition Ports.cpp:43
const BundleType * type
Definition Ports.h:796
BundlePort(AppID id, const BundleType *type, PortMap channels)
Construct a port.
Definition Ports.cpp:40
Bundles represent a collection of channels.
Definition Types.h:104
const Type * type
Definition Ports.h:234
size_t getFrameSizeBytes() const
Get the size of each frame in bytes.
Definition Ports.h:219
virtual void connectImpl(const ConnectOptions &options)
Called by all connect methods to let backends initiate the underlying connections.
Definition Ports.h:309
ChannelPort(const Type *type)
Definition Ports.cpp:27
std::unique_ptr< TranslationInfo > translationInfo
Definition Ports.h:301
bool poll()
Poll for incoming data.
Definition Ports.h:208
virtual bool isConnected() const =0
Channels are the basic communication primitives.
Definition Types.h:125
Lists represent variable-length sequences of elements of a single type.
Definition Types.h:405
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
MessageData toMessageData() const override
Flatten all segments into a standard MessageData.
Definition Common.h:263
A ChannelPort which reads data from the accelerator.
Definition Ports.h:595
volatile Mode mode
Definition Ports.h:692
std::mutex callbackMutex
Synchronizes callback revocation during disconnect.
Definition Ports.h:720
virtual void connect(ReadCallback callback, const ConnectOptions &options={})
Definition Ports.cpp:143
virtual std::future< MessageData > readAsync()
Asynchronous polling read.
Definition Ports.cpp:228
size_t nextFrameIndex
Index of the next expected frame (for multi-frame windows).
Definition Ports.h:701
std::vector< uint8_t > translationBuffer
Window translation support.
Definition Ports.h:699
bool accumulatingListData
Flag to track whether we're in the middle of accumulating list data.
Definition Ports.h:705
void resetTranslationState()
Reset translation state buffers and indices.
Definition Ports.cpp:63
std::function< bool(std::unique_ptr< SegmentedMessageData > &)> ReadCallback
Primary callback API for raw reads.
Definition Ports.h:603
std::optional< detail::PollingBuffer< MessageData > > pollingState
Definition Ports.h:717
bool translateIncoming(MessageData &data)
Translate incoming data if the port type is a window type.
Definition Ports.cpp:492
virtual void disconnect() override
Disconnect the channel.
Definition Ports.cpp:71
size_t activeCallbacks
Definition Ports.h:722
std::unique_ptr< SegmentedMessageData > translatedMessage
If a translated message has been assembled but not yet consumed, retain ownership here so retries pre...
Definition Ports.h:696
uint64_t maxDataQueueMsgs
Definition Ports.h:716
std::function< bool(MessageData)> FlatReadCallback
Compatibility callback API for callers which want flattened message bytes instead of the owning segme...
Definition Ports.h:608
ReadCallback callback
Backends should not call this directly.
Definition Ports.h:687
std::vector< uint8_t > listDataBuffer
For list fields: accumulated list data across frames.
Definition Ports.h:703
bool invokeCallback(std::unique_ptr< SegmentedMessageData > &msg)
Invoke the currently registered callback.
Definition Ports.cpp:88
std::condition_variable callbackCv
Definition Ports.h:721
Structs are an ordered collection of fields, each with a name and a type.
Definition Types.h:264
bool isReverse() const
Definition Types.h:293
const FieldVector & getFields() const
Definition Types.h:272
Root class of the ESI type system.
Definition Types.h:36
virtual std::ptrdiff_t getBitWidth() const
Definition Types.h:43
Windows represent a fixed-size sliding window over a stream of data.
Definition Types.h:334
A ChannelPort which sends data to the accelerator.
Definition Ports.h:315
void stopAsyncWriter()
Detach and stop the default implementation's current connection, if any.
Definition Ports.cpp:918
std::mutex asyncWriterMutex
Protects asyncWriter.
Definition Ports.h:561
std::shared_ptr< DefaultAsyncWriter > asyncWriter
The default implementation's current connection, if in use.
Definition Ports.h:563
void connectCallbackMode(const ConnectOptions &options)
For backends which override connect(DataFetchCallback, ...): check that the port is disconnected,...
Definition Ports.cpp:874
void writeInternal(const MessageData &data)
write(), tryWrite() and flush() without the mode check.
Definition Ports.cpp:948
size_t translationBufferIdx
Index of the next message to write in translationBuffer.
Definition Ports.h:527
virtual void disconnect() override
Disconnect the port.
Definition Ports.cpp:902
virtual bool tryWriteImpl(const MessageData &data)=0
Implementation for tryWrite(). Subclasses must implement this.
void connectCommon(const ConnectOptions &options)
Set up translation and call connectImpl(). Shared by both modes.
Definition Ports.cpp:857
bool translateMessages
Whether to translate outgoing data if the port type is a window type.
Definition Ports.h:522
void requireNotCallbackMode(const char *method) const
Throw if the port is connected in callback mode.
Definition Ports.cpp:849
virtual void notifyAsyncDataAvailable()
Notify the port that the DataFetchCallback has data again.
Definition Ports.cpp:938
bool tryWriteInternal(const MessageData &data)
Definition Ports.cpp:961
virtual void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
Definition Ports.cpp:867
virtual bool pollWriteImpl()
Backend-specific polling.
Definition Ports.h:463
const MessageData & maybePadEmptyMessage(const MessageData &data)
Pad an empty payload with a single zero byte if the port type has a zero-width logical width (e....
Definition Ports.h:477
bool pollImpl() final
If the default callback mode implementation is in use, write fetched data (see connect()).
Definition Ports.cpp:928
bool hasPendingFrames() const
Whether a windowed message's frames are partially written.
Definition Ports.h:542
void discardPendingFrames()
Drop the frames of a partially written (windowed) message.
Definition Ports.cpp:994
std::function< void(std::exception_ptr)> WriteErrorCallback
Callback mode error handler.
Definition Ports.h:333
std::shared_ptr< DefaultAsyncWriter > getAsyncWriter()
Return the default implementation's current connection, if any.
Definition Ports.cpp:913
void translateOutgoing(const MessageData &data)
Translate outgoing data if the port type is a window type.
Definition Ports.cpp:589
std::vector< MessageData > getMessageFrames(const MessageData &data)
Break a message into its frames.
Definition Ports.cpp:683
static constexpr size_t kMaxAsyncWritesPerCall
The most messages the default callback mode implementation writes per call to notifyAsyncDataAvailabl...
Definition Ports.h:445
std::atomic< Mode > mode
Definition Ports.h:467
std::vector< MessageData > translationBuffer
If tryWrite cannot write all the messages of a windowed type at once, it stores them here and writes ...
Definition Ports.h:525
std::function< std::unique_ptr< SegmentedMessageData >()> DataFetchCallback
Callback mode data source.
Definition Ports.h:327
~WriteChannelPort() override
Stops the default callback mode implementation, if in use, dropping a fetched message which hasn't be...
Definition Ports.cpp:847
virtual void writeImpl(const MessageData &)=0
Implementation for write(). Subclasses must implement this.
Definition esi.py:1
std::map< std::string, ChannelPort & > PortMap
Definition Ports.h:37
std::atomic< bool > stopped
Set when the port is disconnected (or reconnected) or destroyed.
Definition Ports.cpp:760
bool draining
Set by the thread holding mutex while in drain(), so callbacks don't start another one.
Definition Ports.cpp:757
void notify()
Mark that the DataFetchCallback may have data, then poll().
Definition Ports.cpp:721
void poll()
Write fetched data (fetching more as needed) until the DataFetchCallback has none,...
Definition Ports.cpp:769
void stop()
Stop this connection: after this returns, it doesn't touch the port again.
Definition Ports.cpp:712
DrainResult drain()
The body of poll(). Requires mutex.
Definition Ports.cpp:791
DefaultAsyncWriter(WriteChannelPort &port, DataFetchCallback fetch, WriteErrorCallback onError)
Definition Ports.cpp:706
std::recursive_mutex mutex
Held while writing, including while calling the callbacks.
Definition Ports.cpp:752
std::atomic< bool > dataAvailable
False once fetch returns nullptr (or throws), until notify() is called.
Definition Ports.cpp:763
std::unique_ptr< SegmentedMessageData > pendingMsg
A fetched message which the port hasn't accepted yet.
Definition Ports.cpp:766
const WriteErrorCallback onError
Definition Ports.cpp:747
std::optional< unsigned > bufferSize
The buffer size is optional and should be considered merely a hint.
Definition Ports.h:128
bool translateMessage
If the type of this port is a window, translate the incoming/outgoing data into its underlying ('into...
Definition Ports.h:187
A copy operation for translating between frame data and the translation.
Definition Ports.h:253
size_t bufferOffset
Offset in the translation buffer.
Definition Ports.h:257
size_t frameOffset
Offset in the incoming/outgoing frame data.
Definition Ports.h:255
size_t size
Number of bytes to copy.
Definition Ports.h:259
Information about each frame in the windowed type.
Definition Ports.h:281
std::vector< CopyOp > copyOps
Precomputed copy operations for translating this frame (non-list fields).
Definition Ports.h:286
std::optional< ListFieldInfo > listField
Information about list fields in this frame (parallel encoding).
Definition Ports.h:289
size_t expectedSize
The total size of a frame in bytes.
Definition Ports.h:283
Information about a list field within a frame (for parallel encoding).
Definition Ports.h:265
size_t listLengthBufferOffset
Offset in the translation buffer where list length is stored.
Definition Ports.h:275
size_t dataOffset
Offset of the list data array in the frame.
Definition Ports.h:269
std::string fieldName
Name of the list field.
Definition Ports.h:267
size_t lastFieldOffset
Offset of the 'last' field in the frame.
Definition Ports.h:273
size_t elementSize
Size of each list element in bytes.
Definition Ports.h:271
size_t listDataBufferOffset
Offset in the translation buffer where list data starts.
Definition Ports.h:277
void precomputeFrameInfo()
Precompute and optimize the copy operations for translating frames.
Definition Ports.cpp:267
void requireTranslationSupported() const
Throw if this window cannot be translated by the runtime translator (e.g.
Definition Ports.cpp:248
bool hasListField
True if the window contains a list field (variable-size message).
Definition Ports.h:299
const WindowType * windowType
The window type being translated.
Definition Ports.h:249
size_t intoTypeBytes
Size of the 'into' type in bytes (for fixed-size types).
Definition Ports.h:295
size_t frameBytes
Number of bytes per wire frame (from the lowered type's bit width).
Definition Ports.h:297
std::vector< FrameInfo > frames
Precomputed information about each frame.
Definition Ports.h:292
Field information describing a field within a frame.
Definition Types.h:337
std::string name
Definition Types.h:338