CIRCT 24.0.0git
Loading...
Searching...
No Matches
Ports.h
Go to the documentation of this file.
1//===- Ports.h - ESI communication channels ---------------------*- C++ -*-===//
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.
12//
13//===----------------------------------------------------------------------===//
14
15// NOLINTNEXTLINE(llvm-header-guard)
16#ifndef ESI_PORTS_H
17#define ESI_PORTS_H
18
19#include "esi/Common.h"
20#include "esi/Types.h"
21#include "esi/Utils.h"
22
23#include <algorithm>
24#include <atomic>
25#include <cassert>
26#include <condition_variable>
27#include <deque>
28#include <exception>
29#include <functional>
30#include <future>
31#include <mutex>
32#include <queue>
33
34namespace esi {
35
36class ChannelPort;
37using PortMap = std::map<std::string, ChannelPort &>;
38
39namespace detail {
40
41/// Shared queue/promise helper for polling-style read APIs.
42///
43/// Producers either fulfill the oldest waiting reader immediately or enqueue
44/// the value for a later `readAsync()`. Consumers either receive buffered data
45/// immediately or install a promise which is fulfilled by the next enqueue.
46template <typename BufferedT>
48public:
49 explicit PollingBuffer(uint64_t maxQueued) : maxQueued(maxQueued) {}
50
51 /// Return the current bounded queue size. `0` means unbounded.
52 uint64_t getMaxQueued() {
53 std::scoped_lock<std::mutex> lock(mutex);
54 return maxQueued;
55 }
56
57 /// Update the bounded queue size. `0` means unbounded.
58 void setMaxQueued(uint64_t maxMsgs) {
59 std::scoped_lock<std::mutex> lock(mutex);
60 maxQueued = maxMsgs;
61 }
62
63 /// Try to deliver or enqueue a produced value.
64 ///
65 /// Returns `false` only when the bounded queue is full.
66 bool enqueue(BufferedT &value) {
67 std::scoped_lock<std::mutex> lock(mutex);
68 assert(!(!promiseQueue.empty() && !dataQueue.empty()) &&
69 "Both queues are in use.");
70
71 if (!promiseQueue.empty()) {
72 std::promise<BufferedT> promise = std::move(promiseQueue.front());
73 promiseQueue.pop();
74 promise.set_value(std::move(value));
75 } else {
76 if (dataQueue.size() >= maxQueued && maxQueued != 0)
77 return false;
78 dataQueue.push(std::move(value));
79 }
80 return true;
81 }
82
83 /// Read the next value asynchronously.
84 ///
85 /// If a value is already buffered, the returned future is ready
86 /// immediately. Otherwise the future is backed by an internal promise which
87 /// is fulfilled by a later `enqueue()`.
88 std::future<BufferedT> readAsync() {
89 std::scoped_lock<std::mutex> lock(mutex);
90 assert(!(!promiseQueue.empty() && !dataQueue.empty()) &&
91 "Both queues are in use.");
92
93 if (!dataQueue.empty()) {
94 std::promise<BufferedT> promise;
95 std::future<BufferedT> future = promise.get_future();
96 promise.set_value(std::move(dataQueue.front()));
97 dataQueue.pop();
98 return future;
99 }
100
101 promiseQueue.emplace();
102 return promiseQueue.back().get_future();
103 }
104
105private:
106 std::mutex mutex;
107 std::queue<BufferedT> dataQueue;
108 uint64_t maxQueued;
109 std::queue<std::promise<BufferedT>> promiseQueue;
110};
111
112} // namespace detail
113
114/// Unidirectional channels are the basic communication primitive between the
115/// host and accelerator. A 'ChannelPort' is the host side of a channel. It can
116/// be either read or write but not both. At this level, channels are untyped --
117/// just streams of bytes. They are not intended to be used directly by users
118/// but used by higher level APIs which add types.
120public:
121 ChannelPort(const Type *type);
122 virtual ~ChannelPort() {}
123
125 /// The buffer size is optional and should be considered merely a hint.
126 /// Individual implementations use it however they like. The unit is number
127 /// of messages of the port type.
128 std::optional<unsigned> bufferSize = std::nullopt;
129
130 /// If the type of this port is a window, translate the incoming/outgoing
131 /// data into its underlying ('into') type. For 'into' types without lists,
132 /// just re-arranges the data fields from the lowered type to the 'into'
133 /// type.
134 ///
135 /// If this option is false, no translation is done and the data is
136 /// passed through as-is. Same is true for non-windowed types.
137 ///
138 /// For messages with lists, only two types are supported:
139 /// 1) Parallel encoding includes any 'header' data with each frame. Said
140 /// header data is the same across all frames, so this encoding is
141 /// inefficient but is commonly used for on-chip streaming interfaces.
142 /// Each frame contains a 'last' field to indicate the end of the list.
143 /// In cases where 'numItems' is greater than 1, a field named
144 /// '<listField>_size' indicates the number of valid items in that
145 /// frame.
146 /// 2) Serial (bulk transfer) encoding, where a 'header' frame precedes
147 /// the list data frame. Said header frame contains a 'count' field
148 /// indicating the number of items in the list. Importantly, the
149 /// header frame is always re-transmitted after the specified number of
150 /// list items have been sent. If the 'count' field is zero, the end of
151 /// the list has been reached. If it is non-zero, the message has not
152 /// been completely transmitted and reading should continue until a
153 /// 'count' of zero is received.
154 ///
155 /// In both cases, the host-side MessageData contains the complete header
156 /// followed by the list data. In other words, header data is not duplicated
157 /// in the returned message. So for a windowed type with header fields and
158 /// a list of (x,y) coordinates, the host memory layout would be:
159 /// ```
160 /// struct ExampleList {
161 /// uint32_t headerField2; // SystemVerilog ordering
162 /// uint32_t headerField1;
163 /// size_t list_length; // Number list items
164 /// struct { uint16_t y, x; } list_data[];
165 /// }
166 /// ```
167 ///
168 /// In a parallel encoding, each frame's wire format (from hardware) is:
169 /// ```
170 /// struct ExampleListFrame {
171 /// uint8_t list_last; // Non-zero indicates last item in list
172 /// struct { uint16_t y, x; } list_data[numItems]; // SV field ordering
173 /// uint32_t headerField2; // SV struct ordering (reversed)
174 /// uint32_t headerField1;
175 /// }
176 /// ```
177 ///
178 /// Important note: for consistency, preserves SystemVerilog struct field
179 /// ordering! So it's the opposite of C struct ordering.
180 ///
181 /// Implementation status:
182 /// - Only parallel list encoding is supported.
183 /// - Fields must be byte-aligned.
184 ///
185 /// See the CIRCT documentation (or td files) for more details on windowed
186 /// messages.
187 bool translateMessage = true;
188
189 ConnectOptions(std::optional<unsigned> bufferSize = std::nullopt,
190 bool translateMessage = true)
192 };
193
194 /// Set up a connection to the accelerator.
195 virtual void connect(const ConnectOptions &options = ConnectOptions()) = 0;
196 virtual void disconnect() = 0;
197 virtual bool isConnected() const = 0;
198
199 /// Poll for incoming data. Returns true if data was read or written into a
200 /// buffer as a result of the poll, though it may return false regardless
201 /// (e.g. a write port in callback mode doesn't report its writes). Calling
202 /// the call back could (will) also happen in that case. Some backends need
203 /// this to be called periodically. In the usual case, this will be called by
204 /// a background thread, but the ESI runtime does not want to assume that the
205 /// host processes use standard threads. If the user wants to provide their
206 /// own threads, they need to call this on each port occasionally. This is
207 /// also called from the 'master' poll method in the Accelerator class.
208 bool poll() {
209 if (isConnected())
210 return pollImpl();
211 return false;
212 }
213
214 /// Get the size of each frame in bytes. For windowed types, this is the
215 /// lowered type's width; otherwise, the port type's width. Transports
216 /// (DMA engines, cosim, etc.) require every message to be at least one
217 /// byte, so void / zero-width port types are reported as 1 byte here; the
218 /// transport pads or strips that placeholder byte transparently.
219 size_t getFrameSizeBytes() const {
220 size_t bytes = translationInfo ? translationInfo->frameBytes
221 : utils::bitsToBytes(type->getBitWidth());
222 return std::max<size_t>(1, bytes);
223 }
224 const Type *getType() const { return type; }
225
226 /// If this port carries a windowed type, return the original WindowType
227 /// (whose `intoType` is what `getType()` returns). Returns nullptr for
228 /// non-windowed ports.
229 const WindowType *getWindowType() const {
230 return translationInfo ? translationInfo->windowType : nullptr;
231 }
232
233protected:
234 const Type *type;
235
236 /// Instructions for translating windowed types. Precomputes and optimizes a
237 /// list of copy operations.
240
241 /// Precompute and optimize the copy operations for translating frames.
242 void precomputeFrameInfo();
243
244 /// Throw if this window cannot be translated by the runtime translator
245 /// (e.g. uses serial/bulk list encoding which is not yet supported).
246 void requireTranslationSupported() const;
247
248 /// The window type being translated.
250
251 /// A copy operation for translating between frame data and the translation.
252 /// Run this during the translation.
253 struct CopyOp {
254 /// Offset in the incoming/outgoing frame data.
256 /// Offset in the translation buffer.
258 /// Number of bytes to copy.
259 size_t size;
260 };
261
262 /// Information about a list field within a frame (for parallel encoding).
263 /// Note: Currently only numItems == 1 is supported (one list element per
264 /// frame).
266 /// Name of the list field.
267 std::string fieldName;
268 /// Offset of the list data array in the frame.
270 /// Size of each list element in bytes.
272 /// Offset of the 'last' field in the frame.
274 /// Offset in the translation buffer where list length is stored.
276 /// Offset in the translation buffer where list data starts.
278 };
279
280 /// Information about each frame in the windowed type.
281 struct FrameInfo {
282 /// The total size of a frame in bytes.
284 /// Precomputed copy operations for translating this frame (non-list
285 /// fields).
286 std::vector<CopyOp> copyOps;
287 /// Information about list fields in this frame (parallel encoding).
288 /// Currently only one list field per frame is supported.
289 std::optional<ListFieldInfo> listField;
290 };
291 /// Precomputed information about each frame.
292 std::vector<FrameInfo> frames;
293 /// Size of the 'into' type in bytes (for fixed-size types).
294 /// For types with lists, this is the size of the fixed header portion.
295 size_t intoTypeBytes = 0;
296 /// Number of bytes per wire frame (from the lowered type's bit width).
297 size_t frameBytes = 0;
298 /// True if the window contains a list field (variable-size message).
299 bool hasListField = false;
300 };
301 std::unique_ptr<TranslationInfo> translationInfo;
302
303 /// Method called by poll() to actually poll the channel if the channel is
304 /// connected.
305 virtual bool pollImpl() { return false; }
306
307 /// Called by all connect methods to let backends initiate the underlying
308 /// connections.
309 virtual void connectImpl(const ConnectOptions &options) {}
310};
311
312/// A ChannelPort which sends data to the accelerator. It has two modes: Sync
313/// and Callback, which cannot be used at the same time. The mode is set at
314/// connect() time. To change the mode, disconnect() and then connect() again.
316public:
318 /// Stops the default callback mode implementation, if in use, dropping a
319 /// fetched message which hasn't been completely written.
320 ~WriteChannelPort() override;
321
322 /// Callback mode data source. Called whenever the port can accept a message:
323 /// returns the next message to write (ownership is transferred), or nullptr
324 /// if none is available yet. After returning nullptr (or throwing), it isn't
325 /// called again until notifyAsyncDataAvailable() is. Must return
326 /// immediately.
328 std::function<std::unique_ptr<SegmentedMessageData>()>;
329
330 /// Callback mode error handler. Called with the exception thrown while
331 /// writing a message returned by the DataFetchCallback (which is then
332 /// dropped), or by the DataFetchCallback itself.
333 using WriteErrorCallback = std::function<void(std::exception_ptr)>;
334
335 /// Disconnect the port. In callback mode, drops a fetched message which
336 /// hasn't been completely written. With the default callback mode
337 /// implementation, blocks until another thread writing fetched data
338 /// (including the callbacks it invokes) has stopped. Must not be called
339 /// concurrently with connect() or disconnect() on another thread. Subclasses
340 /// which override this must call it.
341 virtual void disconnect() override;
342 virtual bool isConnected() const override {
343 return mode != Mode::Disconnected;
344 }
345
346 //===--------------------------------------------------------------------===//
347 // Sync mode: connect without a callback to use write(), tryWrite(), and
348 // flush(). These throw in callback mode.
349 //===--------------------------------------------------------------------===//
350
351 /// Connect in sync mode. Throws if connected in callback mode.
352 virtual void connect(const ConnectOptions &options = {}) override;
353
354 /// A very basic blocking write API. Will likely change for performance
355 /// reasons.
356 void write(const MessageData &data) {
357 requireNotCallbackMode("write");
358 writeInternal(data);
359 }
360
361 /// Write a multi-segment message. Takes ownership so the backend can hold
362 /// the message across partial writes / async completions. See
363 /// writeSegmentedImpl().
364 void write(std::unique_ptr<SegmentedMessageData> msg) {
365 requireNotCallbackMode("write");
366 if (!msg)
367 throw std::runtime_error(
368 "WriteChannelPort::write: null SegmentedMessageData");
369 writeSegmentedImpl(std::move(msg));
370 }
371
372 /// A basic non-blocking write API. Returns true if any of the data was
373 /// sent; false means none of it was, and the write should be retried. If
374 /// the data type is a window a 'true' return does not indicate that the
375 /// message has been completely written. The 'flush' method can be used to
376 /// check that the entire buffer has been written. It is invalid for
377 /// backends to always return false (i.e. backends must eventually ensure
378 /// that writes may succeed).
379 bool tryWrite(const MessageData &data) {
380 requireNotCallbackMode("tryWrite");
381 return tryWriteInternal(data);
382 }
383
384 /// Non-blocking write of a multi-segment message. On success, takes
385 /// ownership of `msg` (leaving it null) and returns true. On failure, returns
386 /// false and leaves `msg` untouched so the caller can retry with the same
387 /// message. Same completion semantics as `tryWrite(const MessageData &)`.
388 /// See tryWriteSegmentedImpl().
389 bool tryWrite(std::unique_ptr<SegmentedMessageData> &msg) {
390 requireNotCallbackMode("tryWrite");
391 if (!msg)
392 throw std::runtime_error(
393 "WriteChannelPort::tryWrite: null SegmentedMessageData");
394 return tryWriteSegmentedImpl(msg);
395 }
396
397 /// Flush any buffered data. Returns true if all data was flushed.
398 ///
399 /// If `translateMessages` is false, calling `flush()` will immediately return
400 /// true and perform no action, as there is no buffered data to flush.
401 bool flush() {
402 requireNotCallbackMode("flush");
403 return flushInternal();
404 }
405
406 //===--------------------------------------------------------------------===//
407 // Callback mode: connect with a data fetch callback, which the port calls to
408 // get messages to write whenever it can accept them. connect() and
409 // notifyAsyncDataAvailable() provide a default implementation, which
410 // backends may override (e.g. to fetch messages as DMA buffers free up).
411 //===--------------------------------------------------------------------===//
412
413 /// Connect in callback mode. Throws if already connected, if either callback
414 /// is null, or if frames of a windowed message written in sync mode haven't
415 /// all been sent yet (reconnect in sync mode and flush() them first). Must
416 /// not be called concurrently with connect() or disconnect() on another
417 /// thread. Callbacks may be invoked from any thread, but never
418 /// concurrently with each other, and must return quickly. Exceptions thrown
419 /// by `fetch` are reported to `onError`; those thrown by `onError`
420 /// propagate out of whichever call invoked it (e.g.
421 /// notifyAsyncDataAvailable() or poll(); the accelerator's service thread
422 /// logs them). They may call notifyAsyncDataAvailable() and disconnect() (and
423 /// then connect()), but must not wait on another thread which uses the port.
424 ///
425 /// Default implementation: the port calls `fetch` and writes what it returns
426 /// with tryWriteSegmentedImpl() (so backends which override that for
427 /// scatter-gather support receive messages as-is), until `fetch` returns
428 /// nullptr or the backend backpressures. It does so from
429 /// notifyAsyncDataAvailable() and from poll() (e.g. called by the
430 /// accelerator's service thread via `AcceleratorServiceThread::addPoll()`),
431 /// which also retries the one fetched message the backend didn't accept.
432 /// Each call writes at most `kMaxAsyncWritesPerCall` messages, so that it
433 /// returns even if `fetch` always has data; poll() writes the rest.
434 /// `fetch` is first called by the first of either after connecting. Its
435 /// state is only allocated while it is in use.
436 ///
437 /// Backends which override this must also override
438 /// notifyAsyncDataAvailable(), uphold the callback contracts, and call
439 /// connectCallbackMode().
440 virtual void connect(DataFetchCallback fetch, WriteErrorCallback onError,
441 const ConnectOptions &options = {});
442
443 /// The most messages the default callback mode implementation writes per
444 /// call to notifyAsyncDataAvailable() or poll().
445 static constexpr size_t kMaxAsyncWritesPerCall = 64;
446
447 /// Notify the port that the DataFetchCallback has data again. Throws if the
448 /// port isn't connected in callback mode.
449 ///
450 /// Default implementation: unless another thread is already writing fetched
451 /// data (which then picks the new data up), writes it immediately on the
452 /// calling thread.
453 virtual void notifyAsyncDataAvailable();
454
455protected:
456 /// If the default callback mode implementation is in use, write fetched data
457 /// (see connect()). Then, if the port is still connected (a callback may
458 /// disconnect it), call pollWriteImpl() and return its result.
459 bool pollImpl() final;
460
461 /// Backend-specific polling. Write port backends override this rather than
462 /// pollImpl(). Returns true if any progress was made.
463 virtual bool pollWriteImpl() { return false; }
464
465 /// Indicates the current mode of the channel.
467 std::atomic<Mode> mode = Mode::Disconnected;
468
469 /// For backends which override connect(DataFetchCallback, ...): check that
470 /// the port is disconnected, set up message translation, call connectImpl(),
471 /// and enter callback mode, in which the sync write APIs throw.
472 void connectCallbackMode(const ConnectOptions &options);
473
474 /// Pad an empty payload with a single zero byte if the port type has a
475 /// zero-width logical width (e.g. `VoidType`). Transports (DMA engines,
476 /// cosim, etc.) require every message to carry at least one byte.
478 if (!data.getSize() && type && type->getBitWidth() == 0)
479 return transportPad0Bytes;
480 return data;
481 }
482
483 /// Backing storage for `maybePadEmptyMessage` return so that the returned
484 /// reference outlives the call.
485 inline static const MessageData transportPad0Bytes = MessageData({0});
486
487 /// Implementation for write(). Subclasses must implement this.
488 virtual void writeImpl(const MessageData &) = 0;
489
490 /// Implementation for tryWrite(). Subclasses must implement this.
491 virtual bool tryWriteImpl(const MessageData &data) = 0;
492
493 /// Implementation for the segmented write(). `msg` is non-null. The default
494 /// flattens the message (without copying if it is already a MessageData)
495 /// and writes it like write(const MessageData &). Backends override for
496 /// scatter-gather / chunked-DMA support.
497 virtual void writeSegmentedImpl(std::unique_ptr<SegmentedMessageData> msg) {
498 MessageData scratch;
499 writeInternal(msg->asMessageData(scratch));
500 }
501
502 /// Implementation for the segmented tryWrite(), also used by the default
503 /// callback mode implementation. `msg` is non-null. On success, takes
504 /// ownership of it (leaving it null) and returns true; otherwise leaves it
505 /// untouched. The default flattens the message (without copying if it is
506 /// already a MessageData) and writes it like tryWrite(const MessageData &).
507 /// Backends override for scatter-gather / chunked-DMA support.
508 virtual bool
509 tryWriteSegmentedImpl(std::unique_ptr<SegmentedMessageData> &msg) {
510 MessageData scratch;
511 if (!tryWriteInternal(msg->asMessageData(scratch)))
512 return false;
513 msg.reset();
514 return true;
515 }
516
517 /// Break a message into its frames.
518 std::vector<MessageData> getMessageFrames(const MessageData &data);
519
520 /// Whether to translate outgoing data if the port type is a window type. Set
521 /// by the connect() method.
522 bool translateMessages = false;
523 /// If tryWrite cannot write all the messages of a windowed type at once, it
524 /// stores them here and writes them out one by one on subsequent calls.
525 std::vector<MessageData> translationBuffer;
526 /// Index of the next message to write in translationBuffer.
528 /// Translate outgoing data if the port type is a window type. Append the new
529 /// message 'chunks' to translationBuffer.
530 void translateOutgoing(const MessageData &data);
531
532private:
533 /// Throw if the port is connected in callback mode.
534 void requireNotCallbackMode(const char *method) const;
535 /// Set up translation and call connectImpl(). Shared by both modes.
536 void connectCommon(const ConnectOptions &options);
537 /// write(), tryWrite() and flush() without the mode check.
538 void writeInternal(const MessageData &data);
539 bool tryWriteInternal(const MessageData &data);
540 bool flushInternal();
541 /// Whether a windowed message's frames are partially written.
542 bool hasPendingFrames() const {
544 }
545 /// Drop the frames of a partially written (windowed) message.
547
548 //===--------------------------------------------------------------------===//
549 // Default callback mode implementation.
550 //===--------------------------------------------------------------------===//
551
552 /// One connection using the default implementation: its state and the logic
553 /// which writes fetched data. Defined in Ports.cpp.
554 struct DefaultAsyncWriter;
555 /// Return the default implementation's current connection, if any.
556 std::shared_ptr<DefaultAsyncWriter> getAsyncWriter();
557 /// Detach and stop the default implementation's current connection, if any.
558 void stopAsyncWriter();
559
560 /// Protects `asyncWriter`.
562 /// The default implementation's current connection, if in use.
563 std::shared_ptr<DefaultAsyncWriter> asyncWriter;
564};
565
566/// Instantiated when a backend does not know how to create a write channel.
568public:
571
572 void connect(const ConnectOptions &options = {}) override {
573 throw std::runtime_error(errmsg);
574 }
576 const ConnectOptions &options = {}) override {
577 throw std::runtime_error(errmsg);
578 }
579
580protected:
581 void writeImpl(const MessageData &) override {
582 throw std::runtime_error(errmsg);
583 }
584 bool tryWriteImpl(const MessageData &) override {
585 throw std::runtime_error(errmsg);
586 }
587
588 std::string errmsg;
589};
590
591/// A ChannelPort which reads data from the accelerator. It has two modes:
592/// Callback and Polling which cannot be used at the same time. The mode is set
593/// at connect() time. To change the mode, disconnect() and then connect()
594/// again. When the port is disconnected, it will backpressure hardware.
596
597public:
598 /// Primary callback API for raw reads.
599 ///
600 /// The message is passed by owning reference so the callee can consume it,
601 /// move storage out of it, or leave it intact when returning `false` to
602 /// request a retry with the same message object.
604 std::function<bool(std::unique_ptr<SegmentedMessageData> &)>;
605
606 /// Compatibility callback API for callers which want flattened message
607 /// bytes instead of the owning segmented message object.
608 using FlatReadCallback = std::function<bool(MessageData)>;
609
612
613 /// Disconnect the channel. Warning: this method may block until all callbacks
614 /// have returned. Do not call it anywhere which could be in a callback
615 /// control path otherwise deadlock will occur.
616 virtual void disconnect() override;
617 virtual bool isConnected() const override {
618 return mode != Mode::Disconnected;
619 }
620
621 //===--------------------------------------------------------------------===//
622 // Callback mode: To use a callback, connect with a callback function which
623 // will get called with incoming data. This function can be called from any
624 // thread. It shall return true to indicate that the data was consumed. False
625 // if it could not accept the data and should be tried again at some point in
626 // the future. Callback is not allowed to block and needs to execute quickly.
627 //
628 // TODO: Have the callback return something upon which the caller can check,
629 // wait, and be notified.
630 //===--------------------------------------------------------------------===//
631
632 virtual void connect(ReadCallback callback,
633 const ConnectOptions &options = {});
634
635 /// Connect a compatibility callback which receives flattened `MessageData`
636 /// objects. This adapts the primary segmented callback path.
637 virtual void connect(FlatReadCallback callback,
638 const ConnectOptions &options = {});
639
640 //===--------------------------------------------------------------------===//
641 // Polling mode methods: To use futures or blocking reads, connect without any
642 // arguments. You will then be able to use readAsync() or read().
643 //===--------------------------------------------------------------------===//
644
645 /// Default max data queue size set at connect time.
646 static constexpr uint64_t DefaultMaxDataQueueMsgs = 32;
647
648 /// Connect to the channel in polling mode.
649 virtual void connect(const ConnectOptions &options = {}) override;
650
651 /// Asynchronous polling read.
652 ///
653 /// Throws if the port is disconnected or currently connected in callback
654 /// mode.
655 virtual std::future<MessageData> readAsync();
656
657 /// Specify a buffer to read into. Blocking. Basic API, will likely change
658 /// for performance and functionality reasons.
659 virtual void read(MessageData &outData) {
660 std::future<MessageData> f = readAsync();
661 f.wait();
662 outData = std::move(f.get());
663 }
664
665 /// Set maximum number of messages to store in the dataQueue. 0 means no
666 /// limit. This is only used in polling mode and is set to default of 32 upon
667 /// connect. While it may seem redundant to have this and bufferSize, there
668 /// may be (and are) backends which have a very small amount of memory which
669 /// are accelerator accessible and want to move messages out as quickly as
670 /// possible.
671 void setMaxDataQueueMsgs(uint64_t maxMsgs) {
672 maxDataQueueMsgs = maxMsgs;
673 if (pollingState)
674 pollingState->setMaxQueued(maxMsgs);
675 }
676
677protected:
678 /// Invoke the currently registered callback.
679 ///
680 /// Handles synchronization race conditions with disconnects. Backends should
681 /// use this helper instead of calling `callback` directly.
682 bool invokeCallback(std::unique_ptr<SegmentedMessageData> &msg);
683
684private:
685 /// Backends should not call this directly. Use `invokeCallback()` instead,
686 /// which handles synchronization with disconnects.
688
689protected:
690 /// Indicates the current mode of the channel.
692 volatile Mode mode;
693
694 /// If a translated message has been assembled but not yet consumed, retain
695 /// ownership here so retries present the same message object.
696 std::unique_ptr<SegmentedMessageData> translatedMessage;
697
698 /// Window translation support.
699 std::vector<uint8_t> translationBuffer;
700 /// Index of the next expected frame (for multi-frame windows).
701 size_t nextFrameIndex = 0;
702 /// For list fields: accumulated list data across frames.
703 std::vector<uint8_t> listDataBuffer;
704 /// Flag to track whether we're in the middle of accumulating list data.
706 /// Reset translation state buffers and indices.
708 /// Translate incoming data if the port type is a window type. Returns true if
709 /// the message has been completely received.
710 bool translateIncoming(MessageData &data);
711
712 //===--------------------------------------------------------------------===//
713 // Polling mode members.
714 //===--------------------------------------------------------------------===//
715
717 std::optional<detail::PollingBuffer<MessageData>> pollingState;
718
719 /// Synchronizes callback revocation during disconnect.
720 std::mutex callbackMutex;
721 std::condition_variable callbackCv;
722 size_t activeCallbacks = 0;
723};
724
725/// Instantiated when a backend does not know how to create a read channel.
727public:
730
732 const ConnectOptions &options = ConnectOptions()) override {
733 throw std::runtime_error(errmsg);
734 }
736 const ConnectOptions &options = ConnectOptions()) override {
737 throw std::runtime_error(errmsg);
738 }
739 void connect(const ConnectOptions &options = ConnectOptions()) override {
740 throw std::runtime_error(errmsg);
741 }
742 std::future<MessageData> readAsync() override {
743 throw std::runtime_error(errmsg);
744 }
745
746protected:
747 std::string errmsg;
748};
749
750/// Services provide connections to 'bundles' -- collections of named,
751/// unidirectional communication channels. This class provides access to those
752/// ChannelPorts.
754public:
755 /// Compute the direction of a channel given the bundle direction and the
756 /// bundle port's direction.
757 static bool isWrite(BundleType::Direction bundleDir) {
758 return bundleDir == BundleType::Direction::To;
759 }
760
761 /// Construct a port.
763 virtual ~BundlePort() = default;
764
765 /// Get the ID of the port.
766 AppID getID() const { return id; }
767
768 /// Get access to the raw byte streams of a channel. Intended for internal
769 /// usage and binding to other languages (e.g. Python) which have their own
770 /// message serialization code. Exposed publicly as an escape hatch, but
771 /// ordinary users should not use. You have been warned.
772 WriteChannelPort &getRawWrite(const std::string &name) const;
773 ReadChannelPort &getRawRead(const std::string &name) const;
774 const PortMap &getChannels() const { return channels; }
775
776 /// Cast this Bundle port to a subclass which is actually useful. Returns
777 /// nullptr if the cast fails.
778 // TODO: this probably shouldn't be 'const', but bundle ports' user access are
779 // const. Change that.
780 template <typename T>
781 T *getAs() const {
782 return const_cast<T *>(dynamic_cast<const T *>(this));
783 }
784
785 /// Calls `poll` on all channels in the bundle and returns true if any of them
786 /// returned true.
787 bool poll() {
788 bool result = false;
789 for (auto &channel : channels)
790 result |= channel.second.poll();
791 return result;
792 }
793
794protected:
798};
799
800} // namespace esi
801
802#endif // ESI_PORTS_H
assert(baseType &&"element must be base type")
virtual ~BundlePort()=default
T * getAs() const
Cast this Bundle port to a subclass which is actually useful.
Definition Ports.h:781
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 PortMap & getChannels() const
Definition Ports.h:774
bool poll()
Calls poll on all channels in the bundle and returns true if any of them returned true.
Definition Ports.h:787
const BundleType * type
Definition Ports.h:796
BundlePort(AppID id, const BundleType *type, PortMap channels)
Construct a port.
Definition Ports.cpp:40
static bool isWrite(BundleType::Direction bundleDir)
Compute the direction of a channel given the bundle direction and the bundle port's direction.
Definition Ports.h:757
AppID getID() const
Get the ID of the port.
Definition Ports.h:766
Bundles represent a collection of channels.
Definition Types.h:104
Unidirectional channels are the basic communication primitive between the host and accelerator.
Definition Ports.h:119
const Type * getType() const
Definition Ports.h:224
virtual void connect(const ConnectOptions &options=ConnectOptions())=0
Set up a connection to the accelerator.
virtual void disconnect()=0
const WindowType * getWindowType() const
If this port carries a windowed type, return the original WindowType (whose intoType is what getType(...
Definition Ports.h:229
virtual bool pollImpl()
Method called by poll() to actually poll the channel if the channel is connected.
Definition Ports.h:305
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
virtual ~ChannelPort()
Definition Ports.h:122
std::unique_ptr< TranslationInfo > translationInfo
Definition Ports.h:301
bool poll()
Poll for incoming data.
Definition Ports.h:208
virtual bool isConnected() const =0
A concrete flat message backed by a single vector of bytes.
Definition Common.h:201
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
virtual bool isConnected() const override
Definition Ports.h:617
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
Mode
Indicates the current mode of the channel.
Definition Ports.h:691
std::optional< detail::PollingBuffer< MessageData > > pollingState
Definition Ports.h:717
static constexpr uint64_t DefaultMaxDataQueueMsgs
Default max data queue size set at connect time.
Definition Ports.h:646
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
void setMaxDataQueueMsgs(uint64_t maxMsgs)
Set maximum number of messages to store in the dataQueue.
Definition Ports.h:671
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
virtual void read(MessageData &outData)
Specify a buffer to read into.
Definition Ports.h:659
std::condition_variable callbackCv
Definition Ports.h:721
ReadChannelPort(const Type *type)
Definition Ports.h:610
Root class of the ESI type system.
Definition Types.h:36
void connect(ReadCallback callback, const ConnectOptions &options=ConnectOptions()) override
Definition Ports.h:731
void connect(const ConnectOptions &options=ConnectOptions()) override
Connect to the channel in polling mode.
Definition Ports.h:739
std::future< MessageData > readAsync() override
Asynchronous polling read.
Definition Ports.h:742
UnknownReadChannelPort(const Type *type, std::string errmsg)
Definition Ports.h:728
void connect(FlatReadCallback callback, const ConnectOptions &options=ConnectOptions()) override
Connect a compatibility callback which receives flattened MessageData objects.
Definition Ports.h:735
void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
Definition Ports.h:572
void writeImpl(const MessageData &) override
Implementation for write(). Subclasses must implement this.
Definition Ports.h:581
UnknownWriteChannelPort(const Type *type, std::string errmsg)
Definition Ports.h:569
void connect(DataFetchCallback fetch, WriteErrorCallback onError, const ConnectOptions &options={}) override
Connect in callback mode.
Definition Ports.h:575
bool tryWriteImpl(const MessageData &) override
Implementation for tryWrite(). Subclasses must implement this.
Definition Ports.h:584
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
virtual bool isConnected() const override
Definition Ports.h:342
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
virtual bool tryWriteSegmentedImpl(std::unique_ptr< SegmentedMessageData > &msg)
Implementation for the segmented tryWrite(), also used by the default callback mode implementation.
Definition Ports.h:509
virtual void writeSegmentedImpl(std::unique_ptr< SegmentedMessageData > msg)
Implementation for the segmented write().
Definition Ports.h:497
bool tryWriteInternal(const MessageData &data)
Definition Ports.cpp:961
void write(const MessageData &data)
A very basic blocking write API.
Definition Ports.h:356
static const MessageData transportPad0Bytes
Backing storage for maybePadEmptyMessage return so that the returned reference outlives the call.
Definition Ports.h:485
bool tryWrite(std::unique_ptr< SegmentedMessageData > &msg)
Non-blocking write of a multi-segment message.
Definition Ports.h:389
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
void write(std::unique_ptr< SegmentedMessageData > msg)
Write a multi-segment message.
Definition Ports.h:364
Mode
Indicates the current mode of the channel.
Definition Ports.h:466
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 flush()
Flush any buffered data.
Definition Ports.h:401
bool hasPendingFrames() const
Whether a windowed message's frames are partially written.
Definition Ports.h:542
bool tryWrite(const MessageData &data)
A basic non-blocking write API.
Definition Ports.h:379
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
ChannelPort(const Type *type)
Definition Ports.cpp:27
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.
PollingBuffer(uint64_t maxQueued)
Definition Ports.h:49
std::future< BufferedT > readAsync()
Read the next value asynchronously.
Definition Ports.h:88
uint64_t getMaxQueued()
Return the current bounded queue size. 0 means unbounded.
Definition Ports.h:52
bool enqueue(BufferedT &value)
Try to deliver or enqueue a produced value.
Definition Ports.h:66
void setMaxQueued(uint64_t maxMsgs)
Update the bounded queue size. 0 means unbounded.
Definition Ports.h:58
std::queue< std::unique_ptr< T > > dataQueue
Definition Ports.h:107
std::queue< std::promise< std::unique_ptr< T > > > promiseQueue
Definition Ports.h:109
uint64_t bitsToBytes(uint64_t bits)
Compute ceil(bits/8).
Definition Utils.h:232
Definition esi.py:1
std::map< std::string, ChannelPort & > PortMap
Definition Ports.h:37
ConnectOptions(std::optional< unsigned > bufferSize=std::nullopt, bool translateMessage=true)
Definition Ports.h:189
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
TranslationInfo(const WindowType *windowType)
Definition Ports.h:239
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