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;
177 WriteCosimChannelPort(ChannelServer::Stub *rpcClient,
const ChannelDesc &desc,
178 const Type *type, std::string name)
180 ~WriteCosimChannelPort() =
default;
182 void connectImpl(std::optional<unsigned> bufferSize)
override {
183 if (desc.type() != getType()->getID())
184 throw std::runtime_error(
"Channel '" + name +
185 "' has wrong type. Expected " +
186 getType()->getID() +
", got " + desc.type());
187 if (desc.dir() != ChannelDesc::Direction::ChannelDesc_Direction_TO_SERVER)
188 throw std::runtime_error(
"Channel '" + name +
189 "' is not a to server channel");
190 assert(desc.name() == name);
195 ClientContext context;
196 AddressedMessage msg;
197 msg.set_channel_name(name);
198 msg.mutable_message()->set_data(
data.getBytes(),
data.getSize());
199 VoidMessage response;
200 grpc::Status sendStatus = rpcClient->SendToServer(&context, msg, &response);
201 if (!sendStatus.ok())
202 throw std::runtime_error(
"Failed to write to channel '" + name +
203 "': " + std::to_string(sendStatus.error_code()) +
204 " " + sendStatus.error_message() +
205 ". Details: " + sendStatus.error_details());
214 ChannelServer::Stub *rpcClient;
225class ReadCosimChannelPort
227 public grpc::ClientReadReactor<esi::cosim::Message> {
230 ChannelServer::Stub *rpcClient,
const ChannelDesc &desc,
231 const Type *type, std::string name)
233 name(name), context(nullptr) {}
234 virtual ~ReadCosimChannelPort() { disconnect(); }
236 void connectImpl(std::optional<unsigned> bufferSize)
override {
238 if (desc.type() != getType()->getID())
239 throw std::runtime_error(
"Channel '" + name +
240 "' has wrong type. Expected " +
241 getType()->getID() +
", got " + desc.type());
242 if (desc.dir() != ChannelDesc::Direction::ChannelDesc_Direction_TO_CLIENT)
243 throw std::runtime_error(
"Channel '" + name +
244 "' is not a to client channel");
245 assert(desc.name() == name);
250 context =
new ClientContext();
251 rpcClient->async()->ConnectToClientChannel(context, &desc,
this);
253 StartRead(&incomingMessage);
258 void OnReadDone(
bool ok)
override {
264 const std::string &messageString = incomingMessage.data();
265 MessageData data(
reinterpret_cast<const uint8_t *
>(messageString.data()),
266 messageString.size());
267 while (!callback(data))
270 std::this_thread::sleep_for(std::chrono::milliseconds(10));
273 StartRead(&incomingMessage);
277 void disconnect()
override {
278 Logger &logger = conn.getLogger();
279 logger.
debug(
"cosim_read",
"Disconnecting channel " + name);
282 context->TryCancel();
290 ChannelServer::Stub *rpcClient;
296 ClientContext *context;
298 esi::cosim::Message incomingMessage;
308 ClientContext context;
310 ListOfChannels response;
311 Status s = stub->ListChannels(&context, arg, &response);
313 for (
const auto &channel : response.channels())
314 if (channel.name() == channelName) {
322class CosimMMIO :
public MMIO {
326 :
MMIO(conn, clients) {
329 ChannelDesc cmdArg, cmdResp;
330 if (!rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.arg", cmdArg) ||
331 !rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.result", cmdResp))
332 throw std::runtime_error(
"Could not find MMIO channels");
337 {{
"write", new BitsType(
"i1", 1)},
338 {
"offset", new UIntType(
"ui32", 32)},
339 {
"data", new BitsType(
"i64", 64)}}));
342 cmdArgPort = std::make_unique<WriteCosimChannelPort>(
343 rpcClient->
stub.get(), cmdArg, cmdType,
"__cosim_mmio_read_write.arg");
344 cmdRespPort = std::make_unique<ReadCosimChannelPort>(
345 conn, rpcClient->
stub.get(), cmdResp, i64Type,
346 "__cosim_mmio_read_write.result");
348 "cosimMMIO", {{
"arg", BundleType::Direction::To, cmdType},
349 {
"result", BundleType::Direction::From, i64Type}});
351 *cmdArgPort, *cmdRespPort));
364 uint64_t read(uint32_t addr)
const override {
365 MMIOCmd cmd{.offset =
addr, .write =
false};
367 std::future<MessageData> result = cmdMMIO->call(arg);
369 uint64_t ret = *result.get().as<uint64_t>();
371 [addr, ret](std::string &subsystem, std::string &msg,
372 std::unique_ptr<std::map<std::string, std::any>> &details) {
373 subsystem =
"cosim_mmio";
374 msg =
"MMIO[0x" +
toHex(addr) +
"] = 0x" +
toHex(ret);
379 void write(uint32_t addr, uint64_t data)
override {
382 data](std::string &subsystem, std::string &msg,
383 std::unique_ptr<std::map<std::string, std::any>> &details) {
384 subsystem =
"cosim_mmio";
385 msg =
"MMIO[0x" +
toHex(addr) +
"] <- 0x" +
toHex(data);
387 MMIOCmd cmd{.data =
data, .offset =
addr, .write =
true};
389 std::future<MessageData> result = cmdMMIO->call(arg);
395 if (
auto t =
ctxt.getType(type->
getID())) {
399 ctxt.registerType(type);
402 std::unique_ptr<WriteCosimChannelPort> cmdArgPort;
403 std::unique_ptr<ReadCosimChannelPort> cmdRespPort;
404 std::unique_ptr<FuncService::Function> cmdMMIO;
408struct HostMemReadReq {
414struct HostMemReadResp {
419struct HostMemWriteReq {
426using HostMemWriteResp = uint8_t;
429class CosimHostMem :
public HostMem {
435 void start()
override {
446 ChannelDesc readArg, readResp;
447 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_read_req.data", readArg) ||
448 !rpcClient->
getChannelDesc(
"__cosim_hostmem_read_resp.data", readResp))
449 throw std::runtime_error(
"Could not find HostMem read channels");
453 {{
"tag", new UIntType(
"ui8", 8)},
454 {
"data", new BitsType(
"i64", 64)}}));
457 {{
"address", new UIntType(
"ui64", 64)},
458 {
"length", new UIntType(
"ui32", 32)},
459 {
"tag", new UIntType(
"ui8", 8)}}));
463 readRespPort = std::make_unique<WriteCosimChannelPort>(
464 rpcClient->
stub.get(), readResp, readRespType,
465 "__cosim_hostmem_read_resp.data");
466 readReqPort = std::make_unique<ReadCosimChannelPort>(
467 conn, rpcClient->
stub.get(), readArg, readReqType,
468 "__cosim_hostmem_read_req.data");
469 readReqPort->connect(
470 [
this](
const MessageData &req) {
return serviceRead(req); });
473 ChannelDesc writeArg, writeResp;
474 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_write.arg", writeArg) ||
475 !rpcClient->
getChannelDesc(
"__cosim_hostmem_write.result", writeResp))
476 throw std::runtime_error(
"Could not find HostMem write channels");
479 getType(ctxt,
new UIntType(writeResp.type(), 8));
482 {{
"address", new UIntType(
"ui64", 64)},
483 {
"tag", new UIntType(
"ui8", 8)},
484 {
"data", new BitsType(
"i64", 64)}}));
487 writeRespPort = std::make_unique<WriteCosimChannelPort>(
488 rpcClient->
stub.get(), writeResp, writeRespType,
489 "__cosim_hostmem_write.result");
490 writeReqPort = std::make_unique<ReadCosimChannelPort>(
491 conn, rpcClient->
stub.get(), writeArg, writeReqType,
492 "__cosim_hostmem_write.arg");
498 bundleType, *writeRespPort,
500 write->connect([
this](
const MessageData &req) {
return serviceWrite(req); },
507 const HostMemReadReq *req = reqBytes.
as<HostMemReadReq>();
508 acc.getLogger().debug(
509 [&](std::string &subsystem, std::string &msg,
510 std::unique_ptr<std::map<std::string, std::any>> &details) {
511 subsystem =
"HostMem";
512 msg =
"Read request: addr=0x" +
toHex(req->address) +
513 " len=" + std::to_string(req->length) +
514 " tag=" + std::to_string(req->tag);
517 uint64_t *dataPtr =
reinterpret_cast<uint64_t *
>(req->address);
518 for (uint32_t i = 0, e = (req->length + 7) / 8; i < e; ++i) {
519 HostMemReadResp resp{.data = dataPtr[i], .tag = req->tag};
520 acc.getLogger().debug(
521 [&](std::string &subsystem, std::string &msg,
522 std::unique_ptr<std::map<std::string, std::any>> &details) {
523 subsystem =
"HostMem";
524 msg =
"Read result: data=0x" +
toHex(resp.data) +
525 " tag=" + std::to_string(resp.tag);
535 const HostMemWriteReq *req = reqBytes.
as<HostMemWriteReq>();
536 acc.getLogger().debug(
537 [&](std::string &subsystem, std::string &msg,
538 std::unique_ptr<std::map<std::string, std::any>> &details) {
539 subsystem =
"HostMem";
540 msg =
"Write request: addr=0x" +
toHex(req->address) +
" data=0x" +
542 " valid_bytes=" + std::to_string(req->valid_bytes) +
543 " tag=" + std::to_string(req->tag);
545 uint8_t *dataPtr =
reinterpret_cast<uint8_t *
>(req->address);
546 for (uint8_t i = 0; i < req->valid_bytes; ++i)
547 dataPtr[i] = (req->data >> (i * 8)) & 0xFF;
548 HostMemWriteResp resp = req->tag;
552 struct CosimHostMemRegion :
public HostMemRegion {
553 CosimHostMemRegion(std::size_t size) {
555 memset(ptr, 0xFF, size);
558 virtual ~CosimHostMemRegion() { free(ptr); }
559 virtual void *getPtr()
const override {
return ptr; }
560 virtual std::size_t getSize()
const override {
return size; }
567 virtual std::unique_ptr<HostMemRegion>
569 auto ret = std::unique_ptr<HostMemRegion>(
new CosimHostMemRegion(size));
570 acc.getLogger().debug(
571 [&](std::string &subsystem, std::string &msg,
572 std::unique_ptr<std::map<std::string, std::any>> &details) {
573 subsystem =
"HostMem";
574 msg =
"Allocated host memory region at 0x" +
toHex(ret->getPtr()) +
575 " of size " + std::to_string(size);
579 virtual bool mapMemory(
void *ptr, std::size_t size,
583 virtual void unmapMemory(
void *ptr)
const override {}
587 if (
auto t =
ctxt.getType(type->
getID())) {
591 ctxt.registerType(type);
597 std::unique_ptr<WriteCosimChannelPort> readRespPort;
598 std::unique_ptr<ReadCosimChannelPort> readReqPort;
599 std::unique_ptr<CallService::Callback> read;
600 std::unique_ptr<WriteCosimChannelPort> writeRespPort;
601 std::unique_ptr<ReadCosimChannelPort> writeReqPort;
602 std::unique_ptr<CallService::Callback> write;
615 if (prefix.size() > 0)
618 for (
auto client : clients) {
619 AppIDPath fullClientPath = prefix + client.relPath;
620 std::map<std::string, std::string> channelAssignments;
621 for (
auto assignment : client.channelAssignments)
622 if (assignment.second.type ==
"cosim")
623 channelAssignments[assignment.first] = std::any_cast<std::string>(
624 assignment.second.implOptions.at(
"name"));
630 const std::string &channelName,
632 const Type *type)
override;
636 std::map<AppIDPath, std::map<std::string, std::string>>
641std::unique_ptr<ChannelPort>
648 throw std::runtime_error(
"Could not find port for '" + idPath.
toStr() +
649 "." + channelName +
"'");
650 const std::map<std::string, std::string> &channelAssignments = f->second;
651 auto cosimChannelNameIter = channelAssignments.find(channelName);
652 if (cosimChannelNameIter == channelAssignments.end())
653 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
654 channelName +
"' in cosimulation");
660 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
661 channelName +
"' in cosimulation");
663 std::unique_ptr<ChannelPort> port;
664 std::string fullChannelName = idPath.
toStr() +
"." + channelName;
666 port = std::make_unique<WriteCosimChannelPort>(
669 port = std::make_unique<ReadCosimChannelPort>(
679 std::unique_ptr<Engine> engine =
nullptr;
680 if (engineTypeName ==
"cosim")
681 engine = std::make_unique<CosimEngine>(*
this, idPath, details, clients);
695 }
else if (svcType ==
typeid(
SysInfo)) {
700 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.
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.