45 name(std::move(name)) {}
46 ~WriteCosimChannelPort() =
default;
49 if (desc.dir != RpcClient::ChannelDirection::ToServer)
50 throw std::runtime_error(
"Channel '" + name +
51 "' is not a to server channel");
57 conn.getLogger().trace(
59 &data](std::string &subsystem, std::string &msg,
60 std::unique_ptr<std::map<std::string, std::any>> &details) {
61 subsystem =
"cosim_write";
62 msg =
"Writing message to channel '" + name +
"'";
63 details = std::make_unique<std::map<std::string, std::any>>();
64 (*details)[
"channel"] = name;
65 (*details)[
"data_size"] =
data.getSize();
66 (*details)[
"message_data"] =
data.toHex();
69 client.writeToServer(name, data);
96 name(std::move(name)) {}
98 ~ReadCosimChannelPort() =
default;
101 if (desc.dir != RpcClient::ChannelDirection::ToClient)
102 throw std::runtime_error(
"Channel '" + name +
103 "' is not a to client channel");
107 client.connectClientReceiver(name, [
this](
const MessageData &data) {
109 conn.getLogger().trace(
111 std::string &subsystem, std::string &msg,
112 std::unique_ptr<std::map<std::string, std::any>> &details) {
113 subsystem =
"cosim_read";
114 msg =
"Received message from channel '" + name +
"'";
115 details = std::make_unique<std::map<std::string, std::any>>();
116 (*details)[
"channel"] = name;
117 (*details)[
"data_size"] =
data.getSize();
118 (*details)[
"message_data"] =
data.toHex();
125 conn.getLogger().trace(
127 std::string &subsystem, std::string &msg,
128 std::unique_ptr<std::map<std::string, std::any>> &details) {
129 subsystem =
"cosim_read";
130 msg =
"Message from channel '" + name +
"' consumed";
139 conn.getLogger().debug(
"cosim_read",
"Disconnecting channel " + name);
141 connection->disconnect();
152 std::unique_ptr<RpcClient::ReadChannelConnection> connection;
165std::unique_ptr<AcceleratorConnection>
168 std::string host =
"localhost";
171 if ((colon = connectionString.find(
':')) != std::string::npos) {
172 portStr = connectionString.substr(colon + 1);
173 host = connectionString.substr(0, colon);
174 }
else if (connectionString.ends_with(
"cosim.cfg")) {
175 std::ifstream cfg(connectionString);
176 std::string line, key, value;
178 while (getline(cfg, line))
179 if ((colon = line.find(
":")) != std::string::npos) {
180 key = line.substr(0, colon);
181 value = line.substr(colon + 1);
184 else if (key ==
"host")
188 if (portStr.size() == 0)
189 throw std::runtime_error(
"port line not found in file");
190 }
else if (connectionString ==
"env") {
191 char *hostEnv = getenv(
"ESI_COSIM_HOST");
196 char *portEnv = getenv(
"ESI_COSIM_PORT");
200 throw std::runtime_error(
"ESI_COSIM_PORT environment variable not set");
202 throw std::runtime_error(
"Invalid connection std::string '" +
203 connectionString +
"'");
205 uint16_t port = stoul(portStr);
206 auto conn = make_unique<CosimAccelerator>(
ctxt, host, port);
222 rpcClient = std::make_unique<RpcClient>(hostname, port);
230class CosimSysInfo :
public SysInfo {
233 :
SysInfo(conn), rpcClient(rpcClient) {}
235 uint32_t getEsiVersion()
const override {
return rpcClient->
getEsiVersion(); }
237 std::vector<uint8_t> getCompressedManifest()
const override {
238 return rpcClient->getCompressedManifest();
247class CosimMMIO :
public MMIO {
251 :
MMIO(conn, idPath, clients) {
255 if (!rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.arg", cmdArg) ||
256 !rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.result", cmdResp))
257 throw std::runtime_error(
"Could not find MMIO channels");
261 ctxt,
new StructType(cmdArg.
type, {{
"write", new BitsType(
"i1", 1)},
262 {
"offset", new UIntType(
"ui32", 32)},
263 {
"data", new BitsType(
"i64", 64)}}));
266 cmdArgPort = std::make_unique<WriteCosimChannelPort>(
267 conn, *rpcClient, cmdArg, cmdType,
"__cosim_mmio_read_write.arg");
268 cmdRespPort = std::make_unique<ReadCosimChannelPort>(
269 conn, *rpcClient, cmdResp, i64Type,
"__cosim_mmio_read_write.result");
271 "cosimMMIO", {{
"arg", BundleType::Direction::To, cmdType},
272 {
"result", BundleType::Direction::From, i64Type}});
274 *cmdArgPort, *cmdRespPort));
287 uint64_t read(uint32_t addr)
const override {
288 MMIOCmd cmd{.data = 0, .offset =
addr, .write =
false};
290 std::future<MessageData> result = cmdMMIO->call(arg);
292 uint64_t ret = *result.get().as<uint64_t>();
294 [addr, ret](std::string &subsystem, std::string &msg,
295 std::unique_ptr<std::map<std::string, std::any>> &details) {
296 subsystem =
"cosim_mmio";
297 msg =
"MMIO[0x" +
toHex(addr) +
"] = 0x" +
toHex(ret);
302 void write(uint32_t addr, uint64_t data)
override {
305 data](std::string &subsystem, std::string &msg,
306 std::unique_ptr<std::map<std::string, std::any>> &details) {
307 subsystem =
"cosim_mmio";
308 msg =
"MMIO[0x" +
toHex(addr) +
"] <- 0x" +
toHex(data);
310 MMIOCmd cmd{.data =
data, .offset =
addr, .write =
true};
312 std::future<MessageData> result = cmdMMIO->call(arg);
325 std::unique_ptr<WriteCosimChannelPort> cmdArgPort;
326 std::unique_ptr<ReadCosimChannelPort> cmdRespPort;
327 std::unique_ptr<FuncService::Function> cmdMMIO;
331struct HostMemReadReq {
337struct HostMemReadResp {
342struct HostMemWriteReq {
349using HostMemWriteResp = uint8_t;
352class CosimHostMem :
public HostMem {
355 :
HostMem(acc), acc(acc), ctxt(ctxt), rpcClient(rpcClient) {}
357 void start()
override {
369 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_read_req.data", readArg) ||
370 !rpcClient->
getChannelDesc(
"__cosim_hostmem_read_resp.data", readResp))
371 throw std::runtime_error(
"Could not find HostMem read channels");
375 {{
"tag", new UIntType(
"ui8", 8)},
376 {
"data", new BitsType(
"i64", 64)}}));
379 {{
"address", new UIntType(
"ui64", 64)},
380 {
"length", new UIntType(
"ui32", 32)},
381 {
"tag", new UIntType(
"ui8", 8)}}));
385 readRespPort = std::make_unique<WriteCosimChannelPort>(
386 conn, *rpcClient, readResp, readRespType,
387 "__cosim_hostmem_read_resp.data");
388 readReqPort = std::make_unique<ReadCosimChannelPort>(
389 conn, *rpcClient, readArg, readReqType,
390 "__cosim_hostmem_read_req.data");
391 readReqPort->connect(
392 [
this](
const MessageData &req) {
return serviceRead(req); });
396 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_write.arg", writeArg) ||
397 !rpcClient->
getChannelDesc(
"__cosim_hostmem_write.result", writeResp))
398 throw std::runtime_error(
"Could not find HostMem write channels");
404 {{
"address", new UIntType(
"ui64", 64)},
405 {
"tag", new UIntType(
"ui8", 8)},
406 {
"data", new BitsType(
"i64", 64)}}));
409 writeRespPort = std::make_unique<WriteCosimChannelPort>(
410 conn, *rpcClient, writeResp, writeRespType,
411 "__cosim_hostmem_write.result");
412 writeReqPort = std::make_unique<ReadCosimChannelPort>(
413 conn, *rpcClient, writeArg, writeReqType,
"__cosim_hostmem_write.arg");
419 bundleType, *writeRespPort,
421 write->connect([
this](
const MessageData &req) {
return serviceWrite(req); },
428 const HostMemReadReq *req = reqBytes.
as<HostMemReadReq>();
429 acc.getLogger().trace(
430 [&](std::string &subsystem, std::string &msg,
431 std::unique_ptr<std::map<std::string, std::any>> &details) {
432 subsystem =
"hostmem";
433 msg =
"Read request: addr=0x" +
toHex(req->address) +
434 " len=" + std::to_string(req->length) +
435 " tag=" + std::to_string(req->tag);
438 uint64_t *dataPtr =
reinterpret_cast<uint64_t *
>(req->address);
439 for (uint32_t i = 0, e = (req->length + 7) / 8; i < e; ++i) {
440 HostMemReadResp resp{.data = dataPtr[i], .tag = req->tag};
441 acc.getLogger().trace(
442 [&](std::string &subsystem, std::string &msg,
443 std::unique_ptr<std::map<std::string, std::any>> &details) {
444 subsystem =
"HostMem";
445 msg =
"Read result: data=0x" +
toHex(resp.data) +
446 " tag=" + std::to_string(resp.tag);
456 const HostMemWriteReq *req = reqBytes.
as<HostMemWriteReq>();
457 acc.getLogger().trace(
458 [&](std::string &subsystem, std::string &msg,
459 std::unique_ptr<std::map<std::string, std::any>> &details) {
460 subsystem =
"hostmem";
461 msg =
"Write request: addr=0x" +
toHex(req->address) +
" data=0x" +
463 " valid_bytes=" + std::to_string(req->valid_bytes) +
464 " tag=" + std::to_string(req->tag);
466 uint8_t *dataPtr =
reinterpret_cast<uint8_t *
>(req->address);
467 for (uint8_t i = 0; i < req->valid_bytes; ++i)
468 dataPtr[i] = (req->data >> (i * 8)) & 0xFF;
469 HostMemWriteResp resp = req->tag;
473 struct CosimHostMemRegion :
public HostMemRegion {
474 CosimHostMemRegion(std::size_t size) {
476 memset(ptr, 0xFF, size);
479 virtual ~CosimHostMemRegion() { free(ptr); }
480 virtual void *getPtr()
const override {
return ptr; }
481 virtual std::size_t getSize()
const override {
return size; }
488 virtual std::unique_ptr<HostMemRegion>
490 auto ret = std::unique_ptr<HostMemRegion>(
new CosimHostMemRegion(size));
491 acc.getLogger().debug(
492 [&](std::string &subsystem, std::string &msg,
493 std::unique_ptr<std::map<std::string, std::any>> &details) {
494 subsystem =
"HostMem";
495 msg =
"Allocated host memory region at 0x" +
toHex(ret->getPtr()) +
496 " of size " + std::to_string(size);
500 virtual bool mapMemory(
void *ptr, std::size_t size,
504 virtual void unmapMemory(
void *ptr)
const override {}
518 std::unique_ptr<WriteCosimChannelPort> readRespPort;
519 std::unique_ptr<ReadCosimChannelPort> readReqPort;
520 std::unique_ptr<CallService::Callback> read;
521 std::unique_ptr<WriteCosimChannelPort> writeRespPort;
522 std::unique_ptr<ReadCosimChannelPort> writeReqPort;
523 std::unique_ptr<CallService::Callback> write;
536 if (prefix.size() > 0)
539 for (
auto client : clients) {
540 AppIDPath fullClientPath = prefix + client.relPath;
541 std::map<std::string, std::string> channelAssignments;
542 for (
auto assignment : client.channelAssignments)
543 if (assignment.second.type ==
"cosim")
544 channelAssignments[assignment.first] = std::any_cast<std::string>(
545 assignment.second.implOptions.at(
"name"));
551 const std::string &channelName,
553 const Type *type)
override;
557 std::map<AppIDPath, std::map<std::string, std::string>>
562std::unique_ptr<ChannelPort>
569 throw std::runtime_error(
"Could not find port for '" + idPath.
toStr() +
570 "." + channelName +
"'");
571 const std::map<std::string, std::string> &channelAssignments = f->second;
572 auto cosimChannelNameIter = channelAssignments.find(channelName);
573 if (cosimChannelNameIter == channelAssignments.end())
574 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
575 channelName +
"' in cosimulation");
580 if (!
conn.
rpcClient->getChannelDesc(cosimChannelNameIter->second, chDesc))
581 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
582 channelName +
"' in cosimulation");
584 std::unique_ptr<ChannelPort> port;
585 std::string fullChannelName = idPath.
toStr() +
"." + channelName;
587 port = std::make_unique<WriteCosimChannelPort>(
591 type, fullChannelName);
600 std::unique_ptr<Engine> engine =
nullptr;
601 if (engineTypeName ==
"cosim")
602 engine = std::make_unique<CosimEngine>(*
this, idPath, details, clients);
616 }
else if (svcType ==
typeid(
SysInfo)) {
619 return new CosimSysInfo(*
this,
rpcClient.get());
621 return new MMIOSysInfo(getService<services::MMIO>());
#define REGISTER_ACCELERATOR(Name, TAccelerator)
Abstract class representing a connection to an accelerator.
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...
virtual void disconnect()
Disconnect from the accelerator cleanly.
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.
virtual void connectImpl(const ConnectOptions &options)
Called by all connect methods to let backends initiate the underlying connections.
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.
Engines implement the actual channel communication between the host and the accelerator.
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.
std::function< bool(MessageData)> callback
Backends call this callback when new data is available.
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.
virtual bool tryWriteImpl(const MessageData &data)=0
Implementation for tryWrite(). Subclasses must implement this.
virtual void writeImpl(const MessageData &)=0
Implementation for write(). Subclasses must implement this.
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
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.
A gRPC client for communicating with the cosimulation 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.
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
Description of a channel from the server.
Options for allocating host memory.