30#include <initializer_list>
66 WriteCosimChannelPort(
67 AcceleratorConnection &conn, RpcClient &client,
68 const RpcClient::ChannelDesc &desc,
const Type *type, std::string name,
70 : WriteChannelPort(type), conn(conn), client(client), desc(desc),
71 name(std::move(name)), defaultMaxInFlight(defaultMaxInFlight) {}
72 ~WriteCosimChannelPort() { disconnect(); }
75 void connect(DataFetchCallback fetch, WriteErrorCallback onError,
76 const ConnectOptions &options = {})
override {
78 throw std::invalid_argument(
79 "WriteChannelPort::connect: null data fetch callback");
81 throw std::invalid_argument(
82 "WriteChannelPort::connect: null error callback");
83 connectCallbackMode(options);
86 std::lock_guard<std::mutex> lock(callbackMutex);
88 sender = client.connectServerSender(
90 [
this, fetch = std::move(
91 fetch)]() -> std::optional<std::vector<MessageData>> {
92 std::unique_ptr<SegmentedMessageData> msg = fetch();
95 return toFrames(*msg);
106 void notifyAsyncDataAvailable()
override {
107 std::lock_guard<std::mutex> lock(callbackMutex);
109 throw std::runtime_error(
110 "Cannot call `notifyAsyncDataAvailable()` on a write channel which "
111 "is not connected in callback mode.");
115 void disconnect()
override {
116 std::unique_ptr<RpcClient::WriteChannelConnection> oldSender;
118 std::lock_guard<std::mutex> lock(callbackMutex);
119 oldSender = std::move(sender);
124 oldSender->disconnect();
128 void connectImpl(
const ChannelPort::ConnectOptions &options)
override {
129 if (desc.dir != RpcClient::ChannelDirection::ToServer)
130 throw std::runtime_error(
"Channel '" + name +
131 "' is not a to server channel");
132 client.setToServerMaxInFlight(
133 name, options.
bufferSize.value_or(defaultMaxInFlight));
137 void traceWrite(
const MessageData &data) {
138 conn.getLogger().trace(
140 &data](std::string &subsystem, std::string &msg,
141 std::unique_ptr<std::map<std::string, std::any>> &details) {
142 subsystem =
"cosim_write";
143 msg =
"Writing message to channel '" + name +
"'";
144 details = std::make_unique<std::map<std::string, std::any>>();
145 (*details)[
"channel"] = name;
146 (*details)[
"data_size"] =
data.getSize();
147 (*details)[
"message_data"] =
data.toHex();
151 void writeImpl(
const MessageData &data)
override {
152 auto frames = getMessageFrames(data);
153 for (
const auto &frame : frames) {
155 client.writeToServer(name, frame);
158 bool tryWriteImpl(
const MessageData &data)
override {
159 auto frames = getMessageFrames(data);
163 bool rest = translateMessages && translationBufferIdx > 0;
164 if (!client.tryWriteToServer(name, frames, rest))
166 for (
size_t i = 0; i < frames.size(); ++i)
173 std::vector<MessageData> toFrames(
const SegmentedMessageData &msg) {
176 std::vector<MessageData> frames;
177 if (translateMessages) {
179 translateOutgoing(data);
181 translationBuffer.clear();
184 std::vector<MessageData> translated;
185 translated.swap(translationBuffer);
186 for (
const MessageData &frame : translated)
187 for (MessageData &wireFrame :
188 getMessageFrames(maybePadEmptyMessage(frame)))
189 frames.push_back(std::move(wireFrame));
191 frames = getMessageFrames(maybePadEmptyMessage(data));
193 for (
size_t i = 0; i < frames.size(); ++i)
198 AcceleratorConnection &conn;
200 RpcClient::ChannelDesc desc;
202 unsigned defaultMaxInFlight;
205 std::mutex callbackMutex;
207 std::unique_ptr<RpcClient::WriteChannelConnection> sender;
219 ReadCosimChannelPort(AcceleratorConnection &conn, RpcClient &client,
220 const RpcClient::ChannelDesc &desc,
const Type *type,
222 : ReadChannelPort(type), conn(conn), client(client), desc(desc),
223 name(std::move(name)) {}
225 ~ReadCosimChannelPort() =
default;
227 void connectImpl(
const ChannelPort::ConnectOptions &options)
override {
228 if (desc.dir != RpcClient::ChannelDirection::ToClient)
229 throw std::runtime_error(
"Channel '" + name +
230 "' is not a to client channel");
233 connection = client.connectClientReceiver(
235 [
this](std::unique_ptr<SegmentedMessageData> &data) {
237 conn.getLogger().trace(
239 std::string &subsystem, std::string &msg,
240 std::unique_ptr<std::map<std::string, std::any>> &details) {
241 subsystem =
"cosim_read";
242 msg =
"Received message from channel '" + name +
"'";
243 details = std::make_unique<std::map<std::string, std::any>>();
244 MessageData flat =
data->toMessageData();
245 (*details)[
"channel"] = name;
246 (*details)[
"data_size"] = flat.getSize();
247 (*details)[
"message_data"] = flat.toHex();
250 bool consumed = invokeCallback(data);
254 conn.getLogger().trace(
256 std::string &subsystem, std::string &msg,
257 std::unique_ptr<std::map<std::string, std::any>> &details) {
258 subsystem =
"cosim_read";
259 msg =
"Message from channel '" + name +
"' consumed";
268 void disconnect()
override {
269 conn.getLogger().debug(
"cosim_read",
"Disconnecting channel " + name);
271 connection->disconnect();
278 AcceleratorConnection &conn;
280 RpcClient::ChannelDesc desc;
282 std::unique_ptr<RpcClient::ReadChannelConnection> connection;
295std::unique_ptr<AcceleratorConnection>
298 std::string host =
"localhost";
301 if ((colon = connectionString.find(
':')) != std::string::npos) {
302 portStr = connectionString.substr(colon + 1);
303 host = connectionString.substr(0, colon);
304 }
else if (connectionString.ends_with(
"cosim.cfg")) {
305 std::ifstream cfg(connectionString);
306 std::string line, key, value;
308 while (getline(cfg, line))
309 if ((colon = line.find(
":")) != std::string::npos) {
310 key = line.substr(0, colon);
311 value = line.substr(colon + 1);
314 else if (key ==
"host")
318 if (portStr.size() == 0)
319 throw std::runtime_error(
"port line not found in file");
320 }
else if (connectionString ==
"env") {
321 char *hostEnv = getenv(
"ESI_COSIM_HOST");
326 char *portEnv = getenv(
"ESI_COSIM_PORT");
330 throw std::runtime_error(
"ESI_COSIM_PORT environment variable not set");
332 throw std::runtime_error(
"Invalid connection std::string '" +
333 connectionString +
"'");
335 uint16_t port = stoul(portStr);
336 auto conn = make_unique<CosimAccelerator>(
ctxt, host, port);
361class CosimSysInfo :
public SysInfo {
371 :
SysInfo(conn), rpcClient(rpcClient) {
375 if (!rpcClient->
getChannelDesc(
"__cosim_cycle_count.arg", argDesc) ||
376 !rpcClient->
getChannelDesc(
"__cosim_cycle_count.result", resultDesc))
379 Context &ctxt = conn.getCtxt();
384 {{
"cycle", i64Type}, {
"freq", i64Type}}));
386 reqPort = std::make_unique<WriteCosimChannelPort>(
387 conn, *rpcClient, argDesc, i1Type,
"__cosim_cycle_count.arg");
388 respPort = std::make_unique<ReadCosimChannelPort>(
389 conn, *rpcClient, resultDesc, resultType,
"__cosim_cycle_count.result");
395 bundleType, *reqPort, *respPort));
399 uint32_t getEsiVersion()
const override {
return rpcClient->
getEsiVersion(); }
400 std::optional<uint64_t> getCycleCount()
const override {
403 return getCycleInfo().cycle;
405 std::optional<uint64_t> getCoreClockFrequency()
const override {
408 return getCycleInfo().freq;
411 std::vector<uint8_t> getCompressedManifest()
const override {
416 const esi::Type *getType(Context &ctxt, esi::Type *type) {
426 std::unique_ptr<WriteCosimChannelPort> reqPort;
427 std::unique_ptr<ReadCosimChannelPort> respPort;
428 std::unique_ptr<FuncService::Function> func;
430 CycleInfo getCycleInfo()
const {
431 MessageData arg({1});
432 std::future<MessageData> result = func->call(arg);
434 MessageData respMsg = result.get();
435 return *respMsg.
as<CycleInfo>();
441class CosimMMIO :
public MMIO {
443 CosimMMIO(CosimAccelerator &conn, Context &ctxt,
const AppIDPath &idPath,
448 RpcClient::ChannelDesc cmdArg, cmdResp;
449 if (!rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.arg", cmdArg) ||
450 !rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.result", cmdResp))
451 throw std::runtime_error(
"Could not find MMIO channels");
453 const esi::Type *i64Type = getType(ctxt,
new UIntType(cmdResp.
type, 64));
454 const esi::Type *cmdType = getType(
455 ctxt,
new StructType(cmdArg.
type, {{
"write", new BitsType(
"i1", 1)},
456 {
"offset", new UIntType(
"ui32", 32)},
457 {
"data", new BitsType(
"i64", 64)}}));
460 cmdArgPort = std::make_unique<WriteCosimChannelPort>(
461 conn, *rpcClient, cmdArg, cmdType,
"__cosim_mmio_read_write.arg");
462 cmdRespPort = std::make_unique<ReadCosimChannelPort>(
463 conn, *rpcClient, cmdResp, i64Type,
"__cosim_mmio_read_write.result");
464 auto *bundleType =
new BundleType(
465 "cosimMMIO", {{
"arg", BundleType::Direction::To, cmdType},
466 {
"result", BundleType::Direction::From, i64Type}});
468 *cmdArgPort, *cmdRespPort));
481 uint64_t
read(uint32_t addr)
const override {
482 MMIOCmd cmd{.data = 0, .offset =
addr, .write =
false};
484 std::lock_guard<std::mutex> g(mmioCmdLock);
485 std::future<MessageData> result = cmdMMIO->call(arg);
487 uint64_t ret = *result.get().as<uint64_t>();
488 conn.getLogger().trace(
489 [addr, ret](std::string &subsystem, std::string &msg,
490 std::unique_ptr<std::map<std::string, std::any>> &details) {
491 subsystem =
"cosim_mmio";
492 msg =
"MMIO[0x" +
toHex(addr) +
"] = 0x" +
toHex(ret);
497 void write(uint32_t addr, uint64_t data)
override {
498 conn.getLogger().trace(
500 data](std::string &subsystem, std::string &msg,
501 std::unique_ptr<std::map<std::string, std::any>> &details) {
502 subsystem =
"cosim_mmio";
503 msg =
"MMIO[0x" +
toHex(addr) +
"] <- 0x" +
toHex(data);
505 MMIOCmd cmd{.data =
data, .offset =
addr, .write =
true};
507 std::lock_guard<std::mutex> g(mmioCmdLock);
508 std::future<MessageData> result = cmdMMIO->call(arg);
513 const esi::Type *getType(Context &ctxt, esi::Type *type) {
521 std::unique_ptr<WriteCosimChannelPort> cmdArgPort;
522 std::unique_ptr<ReadCosimChannelPort> cmdRespPort;
523 std::unique_ptr<FuncService::Function> cmdMMIO;
527struct HostMemReadReq {
533using HostMemWriteResp = uint8_t;
544void putBits(uint8_t *buf,
size_t bitOff,
size_t width, uint64_t val) {
545 for (
size_t i = 0; i < width; ++i)
546 if ((val >> i) & 1ULL)
547 buf[(bitOff + i) >> 3] |=
static_cast<uint8_t
>(1u << ((bitOff + i) & 7));
549uint64_t getBits(
const uint8_t *buf,
size_t bitOff,
size_t width) {
551 for (
size_t i = 0; i < width; ++i)
552 if (buf[(bitOff + i) >> 3] & (1u << ((bitOff + i) & 7)))
557const StructType &getHostMemPayload(
const Type *type,
558 std::string_view direction) {
561 throw std::runtime_error(
562 std::format(
"Invalid HostMem {} channel layout", direction));
566size_t getHostMemDataBytes(
const StructType &payload,
567 std::string_view direction) {
568 const auto &fields = payload.
getFields();
569 auto data = std::find_if(fields.begin(), fields.end(), [](
const auto &field) {
570 return field.first ==
"data";
572 if (data == fields.end() ||
573 !
dynamic_cast<const BitVectorType *
>(
data->second))
574 throw std::runtime_error(
575 std::format(
"Invalid HostMem {} field: data", direction));
576 auto width =
data->second->getBitWidth();
577 if (width < 8 || !std::has_single_bit(
static_cast<uint64_t
>(width)))
578 throw std::runtime_error(std::format(
579 "HostMem {} width must be a power of two and at least 8", direction));
583void validateHostMemFields(
584 const StructType &payload,
585 std::initializer_list<std::pair<std::string_view, size_t>> expected,
586 std::string_view direction) {
587 if (payload.
getFields().size() != expected.size())
588 throw std::runtime_error(
589 std::format(
"Invalid HostMem {} channel layout", direction));
590 auto field = payload.
getFields().begin();
591 for (
auto [name, width] : expected) {
592 if (field->first != name ||
593 (!
dynamic_cast<const BitVectorType *
>(field->second) &&
594 !(width == 0 &&
dynamic_cast<const VoidType *
>(field->second))) ||
595 field->second->getBitWidth() !=
static_cast<std::ptrdiff_t
>(width))
596 throw std::runtime_error(
597 std::format(
"Invalid HostMem {} field: {}", direction, field->first));
604class HostMemReadRespFrame {
606 HostMemReadRespFrame(uint8_t tag,
const uint8_t *data,
size_t validBytes,
607 size_t wordBytes,
bool last)
608 : bytes(wordBytes + 2, 0) {
609 putBits(bytes.data(), 0, 1, last);
610 for (
size_t i = 0; i < validBytes; ++i)
611 putBits(bytes.data(), 1 + i * 8, 8, data[i]);
612 putBits(bytes.data(), 1 + wordBytes * 8, 8, tag);
615 MessageData toMessage()
const {
616 return MessageData(bytes.data(), bytes.size());
620 std::vector<uint8_t> bytes;
627class HostMemWriteReqFrame {
629 HostMemWriteReqFrame(
const uint8_t *raw,
size_t dataBytes,
size_t sizeWidth)
630 : bytes(raw), sizeWidth(sizeWidth), dataOff(1 + sizeWidth),
631 tagOff(dataOff + dataBytes * 8), addrOff(tagOff + 8) {}
633 uint64_t address()
const {
return getBits(bytes, addrOff, 64); }
634 uint8_t tag()
const {
return getBits(bytes, tagOff, 8); }
635 uint8_t dataByte(
size_t i)
const {
636 return getBits(bytes, dataOff + 8 * i, 8);
639 size_t validBytes()
const {
return getBits(bytes, 1, sizeWidth) + 1; }
640 bool last()
const {
return getBits(bytes, 0, 1) != 0; }
643 const uint8_t *bytes;
644 size_t sizeWidth, dataOff, tagOff, addrOff;
651static constexpr uint32_t kPcieMaxReadRequestBytes = 64 * 4;
653class CosimHostMem :
public HostMem {
655 CosimHostMem(AcceleratorConnection &acc, Context &ctxt, RpcClient *rpcClient)
656 : HostMem(
acc),
acc(
acc), ctxt(ctxt), rpcClient(rpcClient) {}
658 void start()
override {
665 RpcClient::ChannelDesc writeArg, writeResp;
666 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_write.arg", writeArg) ||
667 !rpcClient->
getChannelDesc(
"__cosim_hostmem_write.result", writeResp))
668 throw std::runtime_error(
"Could not find HostMem write channels");
670 RpcClient::ChannelDesc readArg, readResp;
671 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_read_req.data", readArg) ||
672 !rpcClient->
getChannelDesc(
"__cosim_hostmem_read_resp.data", readResp))
673 throw std::runtime_error(
"Could not find HostMem read channels");
677 Manifest manifest(ctxt,
acc.getService<SysInfo>()->getJsonManifest());
678 auto channelType = [
this](
const RpcClient::ChannelDesc &desc) {
679 auto type = ctxt.
getType(desc.type);
681 throw std::runtime_error(
"HostMem channel type not in manifest: " +
685 const esi::Type *writeReqType = channelType(writeArg);
686 const auto &writePayload = getHostMemPayload(writeReqType,
"write");
687 writeDataBytes = getHostMemDataBytes(writePayload,
"write");
688 writeSizeWidth = std::countr_zero(writeDataBytes);
689 validateHostMemFields(writePayload,
692 {
"data", writeDataBytes * 8},
693 {
"data_size", writeSizeWidth},
697 (64 + 8 + writeDataBytes * 8 + writeSizeWidth + 1 + 7) / 8;
700 const esi::Type *readRespType = channelType(readResp);
701 const auto &readPayload = getHostMemPayload(readRespType,
"read");
702 readDataBytes = getHostMemDataBytes(readPayload,
"read");
703 validateHostMemFields(
704 readPayload, {{
"tag", 8}, {
"data", readDataBytes * 8}, {
"last", 1}},
706 const esi::Type *readReqType = channelType(readArg);
712 readRespPort = std::make_unique<WriteCosimChannelPort>(
713 conn, *rpcClient, readResp, readRespType,
714 "__cosim_hostmem_read_resp.data", 0);
715 readRespPort->connect();
716 readReqPort = std::make_unique<ReadCosimChannelPort>(
717 conn, *rpcClient, readArg, readReqType,
718 "__cosim_hostmem_read_req.data");
719 readReqPort->connect(
720 [
this](
const MessageData &req) {
return serviceRead(req); });
723 const esi::Type *writeRespType = channelType(writeResp);
727 writeRespPort = std::make_unique<WriteCosimChannelPort>(
728 conn, *rpcClient, writeResp, writeRespType,
729 "__cosim_hostmem_write.result", 0);
730 writeReqPort = std::make_unique<ReadCosimChannelPort>(
731 conn, *rpcClient, writeArg, writeReqType,
"__cosim_hostmem_write.arg");
732 auto *bundleType =
new BundleType(
734 {{
"arg", BundleType::Direction::To, writeReqType},
735 {
"result", BundleType::Direction::From, writeRespType}});
737 bundleType, *writeRespPort,
739 write->connect([
this](
const MessageData &req) {
return serviceWrite(req); },
745 bool serviceRead(
const MessageData &reqBytes) {
746 const HostMemReadReq *req = reqBytes.
as<HostMemReadReq>();
747 acc.getLogger().trace(
748 [&](std::string &subsystem, std::string &msg,
749 std::unique_ptr<std::map<std::string, std::any>> &details) {
750 subsystem =
"hostmem";
751 msg =
"Read request: addr=0x" +
toHex(req->address) +
752 " len=" + std::to_string(req->length) +
753 " tag=" + std::to_string(req->tag);
758 const auto *dataPtr =
reinterpret_cast<const uint8_t *
>(req->address);
759 size_t numDataResps =
760 req->length == 0 ? 0 : 1 + (req->length - 1) / readDataBytes;
761 if (numDataResps == 0)
762 acc.getLogger().error(
764 std::format(
"Read request with length=0 from addr=0x{} tag={}. "
765 "Reads of length 0 are not valid and indicate a bug "
767 toHex(req->address), req->tag));
768 size_t maxReadBytes =
769 std::max<size_t>(kPcieMaxReadRequestBytes, readDataBytes);
770 if (req->length > maxReadBytes)
771 acc.getLogger().error(
773 std::format(
"Read request length={} from addr=0x{} tag={} exceeds "
774 "the cosim maximum read request size ({} bytes). The "
775 "requester must split reads larger than this into "
776 "multiple requests.",
777 req->length,
toHex(req->address), req->tag,
779 size_t numResps = std::max<size_t>(numDataResps, 1);
780 for (
size_t i = 0; i < numResps; ++i) {
781 size_t offset = i * readDataBytes;
782 size_t validBytes = std::min<size_t>(req->length - offset, readDataBytes);
783 bool last = i + 1 == numResps;
784 HostMemReadRespFrame frame(req->tag,
785 validBytes ? dataPtr + offset :
nullptr,
786 validBytes, readDataBytes, last);
787 acc.getLogger().trace(
788 [&](std::string &subsystem, std::string &msg,
789 std::unique_ptr<std::map<std::string, std::any>> &details) {
790 subsystem =
"HostMem";
791 msg = std::format(
"Read result: valid_bytes={} tag={} last={:d}",
792 validBytes, req->tag, last);
794 readRespPort->write(frame.toMessage());
801 MessageData serviceWrite(
const MessageData &reqBytes) {
802 if (reqBytes.
getSize() != writeFrameBytes)
803 throw std::runtime_error(
"HostMem write frame size mismatch. Size is " +
804 std::to_string(reqBytes.
getSize()) +
805 ", expected " + std::to_string(writeFrameBytes) +
807 HostMemWriteReqFrame req(reqBytes.
getBytes(), writeDataBytes,
809 acc.getLogger().trace(
810 [&](std::string &subsystem, std::string &msg,
811 std::unique_ptr<std::map<std::string, std::any>> &details) {
812 subsystem =
"hostmem";
813 msg =
"Write request: addr=0x" +
toHex(req.address()) +
814 " valid_bytes=" + std::to_string(req.validBytes()) +
815 " tag=" + std::to_string(req.tag()) +
816 " last=" + std::to_string(req.last());
818 uint8_t *dataPtr =
reinterpret_cast<uint8_t *
>(req.address());
819 size_t validBytes = req.validBytes();
820 for (
size_t i = 0; i < validBytes; ++i)
821 dataPtr[i] = req.dataByte(i);
822 HostMemWriteResp resp = req.tag();
826 struct CosimHostMemRegion :
public HostMemRegion {
827 CosimHostMemRegion(std::size_t size) : ptr(malloc(size)), size(size) {
829 memset(ptr, 0xFF, size);
831 virtual ~CosimHostMemRegion() { free(ptr); }
832 virtual void *getPtr()
const override {
return ptr; }
833 virtual std::size_t getSize()
const override {
return size; }
840 virtual std::unique_ptr<HostMemRegion>
841 allocate(std::size_t size, HostMem::Options opts)
const override {
844 std::unique_ptr<HostMemRegion> ret(
new (std::nothrow)
845 CosimHostMemRegion(size));
846 if (!ret || !ret->getPtr())
848 acc.getLogger().debug(
849 [&](std::string &subsystem, std::string &msg,
850 std::unique_ptr<std::map<std::string, std::any>> &details) {
851 subsystem =
"HostMem";
852 msg =
"Allocated host memory region at 0x" +
toHex(ret->getPtr()) +
853 " of size " + std::to_string(size);
857 virtual bool mapMemory(
void *ptr, std::size_t size,
858 HostMem::Options opts)
const override {
861 virtual void unmapMemory(
void *ptr)
const override {}
864 AcceleratorConnection &
acc;
866 RpcClient *rpcClient;
867 size_t readDataBytes = 0;
868 size_t writeDataBytes = 0;
869 size_t writeSizeWidth = 0;
870 size_t writeFrameBytes = 0;
871 std::unique_ptr<WriteCosimChannelPort> readRespPort;
872 std::unique_ptr<ReadCosimChannelPort> readReqPort;
873 std::unique_ptr<CallService::Callback>
read;
874 std::unique_ptr<WriteCosimChannelPort> writeRespPort;
875 std::unique_ptr<ReadCosimChannelPort> writeReqPort;
876 std::unique_ptr<CallService::Callback>
write;
880namespace esi::backends::cosim {
889 if (prefix.size() > 0)
892 for (
auto client : clients) {
893 AppIDPath fullClientPath = prefix + client.relPath;
894 std::map<std::string, std::string> channelAssignments;
895 for (
auto assignment : client.channelAssignments)
896 if (assignment.second.type ==
"cosim")
897 channelAssignments[assignment.first] = std::any_cast<std::string>(
898 assignment.second.implOptions.at(
"name"));
904 const std::string &channelName,
906 const Type *type)
override;
910 std::map<AppIDPath, std::map<std::string, std::string>>
915std::unique_ptr<ChannelPort>
922 throw std::runtime_error(
"Could not find port for '" + idPath.
toStr() +
923 "." + channelName +
"'");
924 const std::map<std::string, std::string> &channelAssignments = f->second;
925 auto cosimChannelNameIter = channelAssignments.find(channelName);
926 if (cosimChannelNameIter == channelAssignments.end())
927 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
928 channelName +
"' in cosimulation");
933 if (!
conn.rpcClient->getChannelDesc(cosimChannelNameIter->second, chDesc))
934 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
935 channelName +
"' in cosimulation");
937 std::unique_ptr<ChannelPort> port;
938 std::string fullChannelName = idPath.
toStr() +
"." + channelName;
940 port = std::make_unique<WriteCosimChannelPort>(
941 conn, *
conn.rpcClient, chDesc, type, fullChannelName);
943 port = std::make_unique<ReadCosimChannelPort>(
conn, *
conn.rpcClient, chDesc,
944 type, fullChannelName);
953 std::unique_ptr<Engine> engine =
nullptr;
954 if (engineTypeName ==
"cosim")
955 engine = std::make_unique<CosimEngine>(*
this, idPath, details, clients);
969 }
else if (svcType ==
typeid(
SysInfo)) {
972 return new CosimSysInfo(*
this,
rpcClient.get());
#define REGISTER_ACCELERATOR(Name, TAccelerator)
static constexpr unsigned DefaultToClientMaxInFlight
Default maximum number of frames in flight (queued in the simulator or sent but not yet consumed by t...
static constexpr unsigned DefaultToServerMaxInFlight
Default maximum number of frames sent to a server-bound channel which the simulation has not yet cons...
services::Service Service
ServiceClass * getService(AppIDPath id={}, std::string implName={}, ServiceImplDetails details={}, HWClientDetails clients={})
Get a typed reference to a particular service type.
Context & getCtxt() const
void clearOwnedObjects()
Drop accelerator-owned objects before a derived backend destroys resources that those objects may ref...
Context & ctxt
ESI accelerator context.
void registerEngine(AppIDPath idPath, std::unique_ptr< Engine > engine, const HWClientDetails &clients)
If createEngine is overridden, this method should be called to register the engine and all of the cha...
virtual void disconnect()
Disconnect from the accelerator cleanly.
Logger & getLogger() const
AcceleratorConnection(Context &ctxt)
std::string toStr() const
Bits are just an array of bits.
static bool isWrite(BundleType::Direction bundleDir)
Compute the direction of a channel given the bundle direction and the bundle port's direction.
Bundles represent a collection of channels.
AcceleratorConnections, Accelerators, and Manifests must all share a context.
std::optional< const Type * > getType(Type::ID id) const
Resolve a type id to the type.
void registerType(Type *type)
Register a type with the context. Takes ownership of the pointer type.
Engine(AcceleratorConnection &conn)
const uint8_t * getBytes() const
const T * as() const
Cast to a type.
size_t getSize() const
Get the size of the data in bytes.
static MessageData from(T &t)
Cast from a type to its raw bytes.
A ChannelPort which reads data from the accelerator.
virtual void disconnect() override
Disconnect the channel.
const MessageData & asMessageData(MessageData &scratch) const
Return this message as a MessageData without copying if it already is one.
Structs are an ordered collection of fields, each with a name and a type.
const FieldVector & getFields() const
Root class of the ESI type system.
A ChannelPort which sends data to the accelerator.
virtual void disconnect() override
Disconnect the port.
virtual void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
Connect to an ESI simulation.
void createEngine(const std::string &engineTypeName, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients) override
Create a new engine for channel communication with the accelerator.
std::unique_ptr< RpcClient > rpcClient
void setManifestMethod(ManifestMethod method)
static std::unique_ptr< AcceleratorConnection > connect(Context &, std::string connectionString)
Parse the connection std::string and instantiate the accelerator.
virtual Service * createService(Service::Type service, AppIDPath path, std::string implName, const ServiceImplDetails &details, const HWClientDetails &clients) override
Called by getServiceImpl exclusively.
ManifestMethod manifestMethod
CosimAccelerator(Context &, std::string hostname, uint16_t port)
Construct and connect to a cosim server.
std::set< std::unique_ptr< ChannelPort > > channels
CosimEngine(CosimAccelerator &conn, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients)
std::map< AppIDPath, std::map< std::string, std::string > > clientChannelAssignments
std::unique_ptr< ChannelPort > createPort(AppIDPath idPath, const std::string &channelName, BundleType::Direction dir, const Type *type) override
Each engine needs to know how to create a ports.
A client for the cosim RPC server.
std::vector< uint8_t > getCompressedManifest() const
Get the compressed manifest from the server.
uint32_t getEsiVersion() const
Get the ESI version from the manifest.
bool getChannelDesc(const std::string &channelName, ChannelDesc &desc) const
Get the channel description for a channel name.
static Callback * get(AcceleratorConnection &acc, AppID id, const BundleType *type, WriteChannelPort &result, ReadChannelPort &arg)
static Function * get(AppID id, BundleType *type, WriteChannelPort &arg, ReadChannelPort &result)
Implement the SysInfo API for a standard MMIO protocol.
const std::type_info & Type
Information about the Accelerator system.
connect(destination, source)
std::unique_ptr< Engine > createEngine(AcceleratorConnection &conn, const std::string &dmaEngineName, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients)
Create an engine by name.
std::string toHex(void *val)
std::vector< HWClientDetail > HWClientDetails
std::map< std::string, std::any > ServiceImplDetails
const T * getUnwrappedAs(const Type *type)
Unwrap aliases and channels, then cast the payload to T.
Description of a channel from the server.
std::optional< unsigned > bufferSize
The buffer size is optional and should be considered merely a hint.
Description of a channel from the server.