21#include "cosim.grpc.pb.h"
24#include <grpcpp/channel.h>
25#include <grpcpp/client_context.h>
26#include <grpcpp/create_channel.h>
27#include <grpcpp/security/credentials.h>
39using grpc::ClientContext;
40using grpc::ClientReader;
41using grpc::ClientReaderWriter;
42using grpc::ClientWriter;
47 throw std::runtime_error(msg +
". Code " + to_string(s.error_code()) +
48 ": " + s.error_message() +
" (" +
49 s.error_details() +
")");
56 std::unique_ptr<ChannelServer::Stub>
stub;
60 esi::cosim::ChannelDesc &desc);
68std::unique_ptr<AcceleratorConnection>
71 std::string host =
"localhost";
74 if ((colon = connectionString.find(
':')) != std::string::npos) {
75 portStr = connectionString.substr(colon + 1);
76 host = connectionString.substr(0, colon);
77 }
else if (connectionString.ends_with(
"cosim.cfg")) {
78 std::ifstream cfg(connectionString);
79 std::string line, key, value;
81 while (getline(cfg, line))
82 if ((colon = line.find(
":")) != std::string::npos) {
83 key = line.substr(0, colon);
84 value = line.substr(colon + 1);
87 else if (key ==
"host")
91 if (portStr.size() == 0)
92 throw std::runtime_error(
"port line not found in file");
93 }
else if (connectionString ==
"env") {
94 char *hostEnv = getenv(
"ESI_COSIM_HOST");
99 char *portEnv = getenv(
"ESI_COSIM_PORT");
103 throw std::runtime_error(
"ESI_COSIM_PORT environment variable not set");
105 throw std::runtime_error(
"Invalid connection std::string '" +
106 connectionString +
"'");
108 uint16_t port = stoul(portStr);
109 auto conn = make_unique<CosimAccelerator>(
ctxt, host, port);
125 auto channel = grpc::CreateChannel(hostname +
":" + std::to_string(port),
126 grpc::InsecureChannelCredentials());
137class CosimSysInfo :
public SysInfo {
140 :
SysInfo(conn), rpcClient(rpcClient) {}
142 uint32_t getEsiVersion()
const override {
143 ::esi::cosim::Manifest response = getManifest();
144 return response.esi_version();
147 std::vector<uint8_t> getCompressedManifest()
const override {
148 ::esi::cosim::Manifest response = getManifest();
149 std::string compressedManifestStr = response.compressed_manifest();
150 return std::vector<uint8_t>(compressedManifestStr.begin(),
151 compressedManifestStr.end());
155 ::esi::cosim::Manifest getManifest()
const {
156 ::esi::cosim::Manifest response;
160 ClientContext context;
162 Status s = rpcClient->GetManifest(&context, arg, &response);
164 std::this_thread::sleep_for(std::chrono::milliseconds(10));
165 }
while (response.esi_version() < 0);
169 esi::cosim::ChannelServer::Stub *rpcClient;
178 ChannelServer::Stub *rpcClient,
const ChannelDesc &desc,
179 const Type *type, std::string name)
182 ~WriteCosimChannelPort() =
default;
184 void connectImpl(std::optional<unsigned> bufferSize)
override {
185 if (desc.dir() != ChannelDesc::Direction::ChannelDesc_Direction_TO_SERVER)
186 throw std::runtime_error(
"Channel '" + name +
187 "' is not a to server channel");
188 assert(desc.name() == name);
194 conn.getLogger().trace(
196 &data](std::string &subsystem, std::string &msg,
197 std::unique_ptr<std::map<std::string, std::any>> &details) {
198 subsystem =
"cosim_write";
199 msg =
"Writing message to channel '" + name +
"'";
200 details = std::make_unique<std::map<std::string, std::any>>();
201 (*details)[
"channel"] = name;
202 (*details)[
"data_size"] =
data.getSize();
203 (*details)[
"message_data"] =
data.toHex();
206 ClientContext context;
207 AddressedMessage msg;
208 msg.set_channel_name(name);
209 msg.mutable_message()->set_data(
data.getBytes(),
data.getSize());
210 VoidMessage response;
211 grpc::Status sendStatus = rpcClient->SendToServer(&context, msg, &response);
212 if (!sendStatus.ok())
213 throw std::runtime_error(
"Failed to write to channel '" + name +
214 "': " + std::to_string(sendStatus.error_code()) +
215 " " + sendStatus.error_message() +
216 ". Details: " + sendStatus.error_details());
226 ChannelServer::Stub *rpcClient;
237class ReadCosimChannelPort
239 public grpc::ClientReadReactor<esi::cosim::Message> {
242 ChannelServer::Stub *rpcClient,
const ChannelDesc &desc,
243 const Type *type, std::string name)
245 name(name), context(nullptr) {}
246 virtual ~ReadCosimChannelPort() { disconnect(); }
248 void connectImpl(std::optional<unsigned> bufferSize)
override {
250 if (desc.dir() != ChannelDesc::Direction::ChannelDesc_Direction_TO_CLIENT)
251 throw std::runtime_error(
"Channel '" + name +
252 "' is not a to client channel");
253 assert(desc.name() == name);
258 context =
new ClientContext();
259 rpcClient->async()->ConnectToClientChannel(context, &desc,
this);
261 StartRead(&incomingMessage);
266 void OnReadDone(
bool ok)
override {
272 const std::string &messageString = incomingMessage.data();
273 MessageData data(
reinterpret_cast<const uint8_t *
>(messageString.data()),
274 messageString.size());
277 conn.getLogger().trace(
279 &data](std::string &subsystem, std::string &msg,
280 std::unique_ptr<std::map<std::string, std::any>> &details) {
281 subsystem =
"cosim_read";
282 msg =
"Received message from channel '" + name +
"'";
283 details = std::make_unique<std::map<std::string, std::any>>();
284 (*details)[
"channel"] = name;
285 (*details)[
"data_size"] =
data.getSize();
286 (*details)[
"message_data"] =
data.toHex();
289 while (!callback(data))
292 std::this_thread::sleep_for(std::chrono::milliseconds(10));
295 conn.getLogger().trace(
296 [
this](std::string &subsystem, std::string &msg,
297 std::unique_ptr<std::map<std::string, std::any>> &details) {
298 subsystem =
"cosim_read";
299 msg =
"Message from channel '" + name +
"' consumed";
303 StartRead(&incomingMessage);
307 void disconnect()
override {
308 Logger &logger = conn.getLogger();
309 logger.
debug(
"cosim_read",
"Disconnecting channel " + name);
312 context->TryCancel();
320 ChannelServer::Stub *rpcClient;
326 ClientContext *context;
328 esi::cosim::Message incomingMessage;
338 ClientContext context;
340 ListOfChannels response;
341 Status s = stub->ListChannels(&context, arg, &response);
343 for (
const auto &channel : response.channels())
344 if (channel.name() == channelName) {
352class CosimMMIO :
public MMIO {
356 :
MMIO(conn, clients) {
359 ChannelDesc cmdArg, cmdResp;
360 if (!rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.arg", cmdArg) ||
361 !rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.result", cmdResp))
362 throw std::runtime_error(
"Could not find MMIO channels");
367 {{
"write", new BitsType(
"i1", 1)},
368 {
"offset", new UIntType(
"ui32", 32)},
369 {
"data", new BitsType(
"i64", 64)}}));
372 cmdArgPort = std::make_unique<WriteCosimChannelPort>(
373 conn, rpcClient->
stub.get(), cmdArg, cmdType,
374 "__cosim_mmio_read_write.arg");
375 cmdRespPort = std::make_unique<ReadCosimChannelPort>(
376 conn, rpcClient->
stub.get(), cmdResp, i64Type,
377 "__cosim_mmio_read_write.result");
379 "cosimMMIO", {{
"arg", BundleType::Direction::To, cmdType},
380 {
"result", BundleType::Direction::From, i64Type}});
382 *cmdArgPort, *cmdRespPort));
395 uint64_t read(uint32_t addr)
const override {
396 MMIOCmd cmd{.offset =
addr, .write =
false};
398 std::future<MessageData> result = cmdMMIO->call(arg);
400 uint64_t ret = *result.get().as<uint64_t>();
402 [addr, ret](std::string &subsystem, std::string &msg,
403 std::unique_ptr<std::map<std::string, std::any>> &details) {
404 subsystem =
"cosim_mmio";
405 msg =
"MMIO[0x" +
toHex(addr) +
"] = 0x" +
toHex(ret);
410 void write(uint32_t addr, uint64_t data)
override {
413 data](std::string &subsystem, std::string &msg,
414 std::unique_ptr<std::map<std::string, std::any>> &details) {
415 subsystem =
"cosim_mmio";
416 msg =
"MMIO[0x" +
toHex(addr) +
"] <- 0x" +
toHex(data);
418 MMIOCmd cmd{.data =
data, .offset =
addr, .write =
true};
420 std::future<MessageData> result = cmdMMIO->call(arg);
426 if (
auto t =
ctxt.getType(type->
getID())) {
430 ctxt.registerType(type);
433 std::unique_ptr<WriteCosimChannelPort> cmdArgPort;
434 std::unique_ptr<ReadCosimChannelPort> cmdRespPort;
435 std::unique_ptr<FuncService::Function> cmdMMIO;
439struct HostMemReadReq {
445struct HostMemReadResp {
450struct HostMemWriteReq {
457using HostMemWriteResp = uint8_t;
460class CosimHostMem :
public HostMem {
466 void start()
override {
477 ChannelDesc readArg, readResp;
478 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_read_req.data", readArg) ||
479 !rpcClient->
getChannelDesc(
"__cosim_hostmem_read_resp.data", readResp))
480 throw std::runtime_error(
"Could not find HostMem read channels");
484 {{
"tag", new UIntType(
"ui8", 8)},
485 {
"data", new BitsType(
"i64", 64)}}));
488 {{
"address", new UIntType(
"ui64", 64)},
489 {
"length", new UIntType(
"ui32", 32)},
490 {
"tag", new UIntType(
"ui8", 8)}}));
494 readRespPort = std::make_unique<WriteCosimChannelPort>(
495 conn, rpcClient->
stub.get(), readResp, readRespType,
496 "__cosim_hostmem_read_resp.data");
497 readReqPort = std::make_unique<ReadCosimChannelPort>(
498 conn, rpcClient->
stub.get(), readArg, readReqType,
499 "__cosim_hostmem_read_req.data");
500 readReqPort->connect(
501 [
this](
const MessageData &req) {
return serviceRead(req); });
504 ChannelDesc writeArg, writeResp;
505 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_write.arg", writeArg) ||
506 !rpcClient->
getChannelDesc(
"__cosim_hostmem_write.result", writeResp))
507 throw std::runtime_error(
"Could not find HostMem write channels");
510 getType(ctxt,
new UIntType(writeResp.type(), 8));
513 {{
"address", new UIntType(
"ui64", 64)},
514 {
"tag", new UIntType(
"ui8", 8)},
515 {
"data", new BitsType(
"i64", 64)}}));
518 writeRespPort = std::make_unique<WriteCosimChannelPort>(
519 conn, rpcClient->
stub.get(), writeResp, writeRespType,
520 "__cosim_hostmem_write.result");
521 writeReqPort = std::make_unique<ReadCosimChannelPort>(
522 conn, rpcClient->
stub.get(), writeArg, writeReqType,
523 "__cosim_hostmem_write.arg");
529 bundleType, *writeRespPort,
531 write->connect([
this](
const MessageData &req) {
return serviceWrite(req); },
538 const HostMemReadReq *req = reqBytes.
as<HostMemReadReq>();
539 acc.getLogger().trace(
540 [&](std::string &subsystem, std::string &msg,
541 std::unique_ptr<std::map<std::string, std::any>> &details) {
542 subsystem =
"hostmem";
543 msg =
"Read request: addr=0x" +
toHex(req->address) +
544 " len=" + std::to_string(req->length) +
545 " tag=" + std::to_string(req->tag);
548 uint64_t *dataPtr =
reinterpret_cast<uint64_t *
>(req->address);
549 for (uint32_t i = 0, e = (req->length + 7) / 8; i < e; ++i) {
550 HostMemReadResp resp{.data = dataPtr[i], .tag = req->tag};
551 acc.getLogger().trace(
552 [&](std::string &subsystem, std::string &msg,
553 std::unique_ptr<std::map<std::string, std::any>> &details) {
554 subsystem =
"HostMem";
555 msg =
"Read result: data=0x" +
toHex(resp.data) +
556 " tag=" + std::to_string(resp.tag);
566 const HostMemWriteReq *req = reqBytes.
as<HostMemWriteReq>();
567 acc.getLogger().trace(
568 [&](std::string &subsystem, std::string &msg,
569 std::unique_ptr<std::map<std::string, std::any>> &details) {
570 subsystem =
"hostmem";
571 msg =
"Write request: addr=0x" +
toHex(req->address) +
" data=0x" +
573 " valid_bytes=" + std::to_string(req->valid_bytes) +
574 " tag=" + std::to_string(req->tag);
576 uint8_t *dataPtr =
reinterpret_cast<uint8_t *
>(req->address);
577 for (uint8_t i = 0; i < req->valid_bytes; ++i)
578 dataPtr[i] = (req->data >> (i * 8)) & 0xFF;
579 HostMemWriteResp resp = req->tag;
583 struct CosimHostMemRegion :
public HostMemRegion {
584 CosimHostMemRegion(std::size_t size) {
586 memset(ptr, 0xFF, size);
589 virtual ~CosimHostMemRegion() { free(ptr); }
590 virtual void *getPtr()
const override {
return ptr; }
591 virtual std::size_t getSize()
const override {
return size; }
598 virtual std::unique_ptr<HostMemRegion>
600 auto ret = std::unique_ptr<HostMemRegion>(
new CosimHostMemRegion(size));
601 acc.getLogger().debug(
602 [&](std::string &subsystem, std::string &msg,
603 std::unique_ptr<std::map<std::string, std::any>> &details) {
604 subsystem =
"HostMem";
605 msg =
"Allocated host memory region at 0x" +
toHex(ret->getPtr()) +
606 " of size " + std::to_string(size);
610 virtual bool mapMemory(
void *ptr, std::size_t size,
614 virtual void unmapMemory(
void *ptr)
const override {}
618 if (
auto t =
ctxt.getType(type->
getID())) {
622 ctxt.registerType(type);
628 std::unique_ptr<WriteCosimChannelPort> readRespPort;
629 std::unique_ptr<ReadCosimChannelPort> readReqPort;
630 std::unique_ptr<CallService::Callback> read;
631 std::unique_ptr<WriteCosimChannelPort> writeRespPort;
632 std::unique_ptr<ReadCosimChannelPort> writeReqPort;
633 std::unique_ptr<CallService::Callback> write;
646 if (prefix.size() > 0)
649 for (
auto client : clients) {
650 AppIDPath fullClientPath = prefix + client.relPath;
651 std::map<std::string, std::string> channelAssignments;
652 for (
auto assignment : client.channelAssignments)
653 if (assignment.second.type ==
"cosim")
654 channelAssignments[assignment.first] = std::any_cast<std::string>(
655 assignment.second.implOptions.at(
"name"));
661 const std::string &channelName,
663 const Type *type)
override;
667 std::map<AppIDPath, std::map<std::string, std::string>>
672std::unique_ptr<ChannelPort>
679 throw std::runtime_error(
"Could not find port for '" + idPath.
toStr() +
680 "." + channelName +
"'");
681 const std::map<std::string, std::string> &channelAssignments = f->second;
682 auto cosimChannelNameIter = channelAssignments.find(channelName);
683 if (cosimChannelNameIter == channelAssignments.end())
684 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
685 channelName +
"' in cosimulation");
691 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
692 channelName +
"' in cosimulation");
694 std::unique_ptr<ChannelPort> port;
695 std::string fullChannelName = idPath.
toStr() +
"." + channelName;
697 port = std::make_unique<WriteCosimChannelPort>(
700 port = std::make_unique<ReadCosimChannelPort>(
710 std::unique_ptr<Engine> engine =
nullptr;
711 if (engineTypeName ==
"cosim")
712 engine = std::make_unique<CosimEngine>(*
this, idPath, details, clients);
726 }
else if (svcType ==
typeid(
SysInfo)) {
731 return new MMIOSysInfo(getService<services::MMIO>());
#define REGISTER_ACCELERATOR(Name, TAccelerator)
assert(baseType &&"element must be base type")
static void checkStatus(Status s, const std::string &msg)
Abstract class representing a connection to an accelerator.
virtual void disconnect()
Disconnect from the accelerator cleanly.
Context & getCtxt() const
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...
Logger & getLogger() const
std::string toStr() const
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.
Engines implement the actual channel communication between the host and the accelerator.
void debug(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a debug message.
void trace(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Log a trace message.
A logical chunk of data representing serialized data.
const T * as() const
Cast to a type.
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
Structs are an ordered collection of fields, each with a name and a type.
Root class of the ESI type system.
A ChannelPort which sends data to the accelerator.
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.
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
StubContainer * rpcClient
Implement the magic cosim channel communication.
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.
static Callback * get(AcceleratorConnection &acc, AppID id, 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.
Parent class of all APIs modeled as 'services'.
const std::type_info & Type
Information about the Accelerator system.
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::map< std::string, std::any > ServiceImplDetails
std::string toHex(void *val)
std::vector< HWClientDetail > HWClientDetails
Hack around C++ not having a way to forward declare a nested class.
std::unique_ptr< ChannelServer::Stub > stub
bool getChannelDesc(const std::string &channelName, esi::cosim::ChannelDesc &desc)
Get the type ID for a channel name.
StubContainer(std::unique_ptr< ChannelServer::Stub > stub)
Options for allocating host memory.