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 for (
const auto &frame : frames) {
58 conn.getLogger().trace(
60 &data](std::string &subsystem, std::string &msg,
61 std::unique_ptr<std::map<std::string, std::any>> &details) {
62 subsystem =
"cosim_write";
63 msg =
"Writing message to channel '" + name +
"'";
64 details = std::make_unique<std::map<std::string, std::any>>();
65 (*details)[
"channel"] = name;
66 (*details)[
"data_size"] =
data.getSize();
67 (*details)[
"message_data"] =
data.toHex();
70 client.writeToServer(name, frame);
100 name(std::move(name)) {}
102 ~ReadCosimChannelPort() =
default;
105 if (desc.dir != RpcClient::ChannelDirection::ToClient)
106 throw std::runtime_error(
"Channel '" + name +
107 "' is not a to client channel");
111 client.connectClientReceiver(name, [
this](
const MessageData &data) {
113 conn.getLogger().trace(
115 std::string &subsystem, std::string &msg,
116 std::unique_ptr<std::map<std::string, std::any>> &details) {
117 subsystem =
"cosim_read";
118 msg =
"Received message from channel '" + name +
"'";
119 details = std::make_unique<std::map<std::string, std::any>>();
120 (*details)[
"channel"] = name;
121 (*details)[
"data_size"] =
data.getSize();
122 (*details)[
"message_data"] =
data.toHex();
129 conn.getLogger().trace(
131 std::string &subsystem, std::string &msg,
132 std::unique_ptr<std::map<std::string, std::any>> &details) {
133 subsystem =
"cosim_read";
134 msg =
"Message from channel '" + name +
"' consumed";
143 conn.getLogger().debug(
"cosim_read",
"Disconnecting channel " + name);
145 connection->disconnect();
156 std::unique_ptr<RpcClient::ReadChannelConnection> connection;
169std::unique_ptr<AcceleratorConnection>
172 std::string host =
"localhost";
175 if ((colon = connectionString.find(
':')) != std::string::npos) {
176 portStr = connectionString.substr(colon + 1);
177 host = connectionString.substr(0, colon);
178 }
else if (connectionString.ends_with(
"cosim.cfg")) {
179 std::ifstream cfg(connectionString);
180 std::string line, key, value;
182 while (getline(cfg, line))
183 if ((colon = line.find(
":")) != std::string::npos) {
184 key = line.substr(0, colon);
185 value = line.substr(colon + 1);
188 else if (key ==
"host")
192 if (portStr.size() == 0)
193 throw std::runtime_error(
"port line not found in file");
194 }
else if (connectionString ==
"env") {
195 char *hostEnv = getenv(
"ESI_COSIM_HOST");
200 char *portEnv = getenv(
"ESI_COSIM_PORT");
204 throw std::runtime_error(
"ESI_COSIM_PORT environment variable not set");
206 throw std::runtime_error(
"Invalid connection std::string '" +
207 connectionString +
"'");
209 uint16_t port = stoul(portStr);
210 auto conn = make_unique<CosimAccelerator>(
ctxt, host, port);
226 rpcClient = std::make_unique<RpcClient>(hostname, port);
234class CosimSysInfo :
public SysInfo {
244 :
SysInfo(conn), rpcClient(rpcClient) {
248 if (!rpcClient->
getChannelDesc(
"__cosim_cycle_count.arg", argDesc) ||
249 !rpcClient->
getChannelDesc(
"__cosim_cycle_count.result", resultDesc))
252 Context &ctxt = conn.getCtxt();
257 {{
"cycle", i64Type}, {
"freq", i64Type}}));
259 reqPort = std::make_unique<WriteCosimChannelPort>(
260 conn, *rpcClient, argDesc, i1Type,
"__cosim_cycle_count.arg");
261 respPort = std::make_unique<ReadCosimChannelPort>(
262 conn, *rpcClient, resultDesc, resultType,
"__cosim_cycle_count.result");
265 {{
"arg", BundleType::Direction::To, i1Type},
266 {
"result", BundleType::Direction::From, resultType}});
268 bundleType, *reqPort, *respPort));
272 uint32_t getEsiVersion()
const override {
return rpcClient->
getEsiVersion(); }
273 std::optional<uint64_t> getCycleCount()
const override {
276 return getCycleInfo().cycle;
278 std::optional<uint64_t> getCoreClockFrequency()
const override {
281 return getCycleInfo().freq;
284 std::vector<uint8_t> getCompressedManifest()
const override {
299 std::unique_ptr<WriteCosimChannelPort> reqPort;
300 std::unique_ptr<ReadCosimChannelPort> respPort;
301 std::unique_ptr<FuncService::Function> func;
303 CycleInfo getCycleInfo()
const {
305 std::future<MessageData> result = func->call(arg);
308 return *respMsg.
as<CycleInfo>();
314class CosimMMIO :
public MMIO {
322 if (!rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.arg", cmdArg) ||
323 !rpcClient->
getChannelDesc(
"__cosim_mmio_read_write.result", cmdResp))
324 throw std::runtime_error(
"Could not find MMIO channels");
328 ctxt,
new StructType(cmdArg.
type, {{
"write", new BitsType(
"i1", 1)},
329 {
"offset", new UIntType(
"ui32", 32)},
330 {
"data", new BitsType(
"i64", 64)}}));
333 cmdArgPort = std::make_unique<WriteCosimChannelPort>(
334 conn, *rpcClient, cmdArg, cmdType,
"__cosim_mmio_read_write.arg");
335 cmdRespPort = std::make_unique<ReadCosimChannelPort>(
336 conn, *rpcClient, cmdResp, i64Type,
"__cosim_mmio_read_write.result");
338 "cosimMMIO", {{
"arg", BundleType::Direction::To, cmdType},
339 {
"result", BundleType::Direction::From, i64Type}});
341 *cmdArgPort, *cmdRespPort));
354 uint64_t
read(uint32_t addr)
const override {
355 MMIOCmd cmd{.data = 0, .offset =
addr, .write =
false};
357 std::future<MessageData> result = cmdMMIO->call(arg);
359 uint64_t ret = *result.get().as<uint64_t>();
360 conn.getLogger().trace(
361 [addr, ret](std::string &subsystem, std::string &msg,
362 std::unique_ptr<std::map<std::string, std::any>> &details) {
363 subsystem =
"cosim_mmio";
364 msg =
"MMIO[0x" +
toHex(addr) +
"] = 0x" +
toHex(ret);
369 void write(uint32_t addr, uint64_t data)
override {
370 conn.getLogger().trace(
372 data](std::string &subsystem, std::string &msg,
373 std::unique_ptr<std::map<std::string, std::any>> &details) {
374 subsystem =
"cosim_mmio";
375 msg =
"MMIO[0x" +
toHex(addr) +
"] <- 0x" +
toHex(data);
377 MMIOCmd cmd{.data =
data, .offset =
addr, .write =
true};
379 std::future<MessageData> result = cmdMMIO->call(arg);
392 std::unique_ptr<WriteCosimChannelPort> cmdArgPort;
393 std::unique_ptr<ReadCosimChannelPort> cmdRespPort;
394 std::unique_ptr<FuncService::Function> cmdMMIO;
398struct HostMemReadReq {
404struct HostMemReadResp {
409struct HostMemWriteReq {
416using HostMemWriteResp = uint8_t;
419class CosimHostMem :
public HostMem {
424 void start()
override {
436 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_read_req.data", readArg) ||
437 !rpcClient->
getChannelDesc(
"__cosim_hostmem_read_resp.data", readResp))
438 throw std::runtime_error(
"Could not find HostMem read channels");
442 {{
"tag", new UIntType(
"ui8", 8)},
443 {
"data", new BitsType(
"i64", 64)}}));
446 {{
"address", new UIntType(
"ui64", 64)},
447 {
"length", new UIntType(
"ui32", 32)},
448 {
"tag", new UIntType(
"ui8", 8)}}));
452 readRespPort = std::make_unique<WriteCosimChannelPort>(
453 conn, *rpcClient, readResp, readRespType,
454 "__cosim_hostmem_read_resp.data");
455 readReqPort = std::make_unique<ReadCosimChannelPort>(
456 conn, *rpcClient, readArg, readReqType,
457 "__cosim_hostmem_read_req.data");
458 readReqPort->connect(
459 [
this](
const MessageData &req) {
return serviceRead(req); });
463 if (!rpcClient->
getChannelDesc(
"__cosim_hostmem_write.arg", writeArg) ||
464 !rpcClient->
getChannelDesc(
"__cosim_hostmem_write.result", writeResp))
465 throw std::runtime_error(
"Could not find HostMem write channels");
471 {{
"address", new UIntType(
"ui64", 64)},
472 {
"tag", new UIntType(
"ui8", 8)},
473 {
"data", new BitsType(
"i64", 64)}}));
476 writeRespPort = std::make_unique<WriteCosimChannelPort>(
477 conn, *rpcClient, writeResp, writeRespType,
478 "__cosim_hostmem_write.result");
479 writeReqPort = std::make_unique<ReadCosimChannelPort>(
480 conn, *rpcClient, writeArg, writeReqType,
"__cosim_hostmem_write.arg");
486 bundleType, *writeRespPort,
488 write->connect([
this](
const MessageData &req) {
return serviceWrite(req); },
495 const HostMemReadReq *req = reqBytes.
as<HostMemReadReq>();
496 acc.getLogger().trace(
497 [&](std::string &subsystem, std::string &msg,
498 std::unique_ptr<std::map<std::string, std::any>> &details) {
499 subsystem =
"hostmem";
500 msg =
"Read request: addr=0x" +
toHex(req->address) +
501 " len=" + std::to_string(req->length) +
502 " tag=" + std::to_string(req->tag);
505 uint64_t *dataPtr =
reinterpret_cast<uint64_t *
>(req->address);
506 for (uint32_t i = 0, e = (req->length + 7) / 8; i < e; ++i) {
507 HostMemReadResp
resp{.data = dataPtr[i], .tag = req->tag};
508 acc.getLogger().trace(
509 [&](std::string &subsystem, std::string &msg,
510 std::unique_ptr<std::map<std::string, std::any>> &details) {
511 subsystem =
"HostMem";
512 msg =
"Read result: data=0x" +
toHex(
resp.data) +
513 " tag=" + std::to_string(
resp.tag);
523 const HostMemWriteReq *req = reqBytes.
as<HostMemWriteReq>();
524 acc.getLogger().trace(
525 [&](std::string &subsystem, std::string &msg,
526 std::unique_ptr<std::map<std::string, std::any>> &details) {
527 subsystem =
"hostmem";
528 msg =
"Write request: addr=0x" +
toHex(req->address) +
" data=0x" +
530 " valid_bytes=" + std::to_string(req->valid_bytes) +
531 " tag=" + std::to_string(req->tag);
533 uint8_t *dataPtr =
reinterpret_cast<uint8_t *
>(req->address);
534 for (uint8_t i = 0; i < req->valid_bytes; ++i)
535 dataPtr[i] = (req->data >> (i * 8)) & 0xFF;
536 HostMemWriteResp
resp = req->tag;
540 struct CosimHostMemRegion :
public HostMemRegion {
541 CosimHostMemRegion(std::size_t size) {
543 memset(ptr, 0xFF, size);
546 virtual ~CosimHostMemRegion() { free(ptr); }
547 virtual void *getPtr()
const override {
return ptr; }
548 virtual std::size_t getSize()
const override {
return size; }
555 virtual std::unique_ptr<HostMemRegion>
557 auto ret = std::unique_ptr<HostMemRegion>(
new CosimHostMemRegion(size));
558 acc.getLogger().debug(
559 [&](std::string &subsystem, std::string &msg,
560 std::unique_ptr<std::map<std::string, std::any>> &details) {
561 subsystem =
"HostMem";
562 msg =
"Allocated host memory region at 0x" +
toHex(ret->getPtr()) +
563 " of size " + std::to_string(size);
567 virtual bool mapMemory(
void *ptr, std::size_t size,
571 virtual void unmapMemory(
void *ptr)
const override {}
585 std::unique_ptr<WriteCosimChannelPort> readRespPort;
586 std::unique_ptr<ReadCosimChannelPort> readReqPort;
587 std::unique_ptr<CallService::Callback>
read;
588 std::unique_ptr<WriteCosimChannelPort> writeRespPort;
589 std::unique_ptr<ReadCosimChannelPort> writeReqPort;
590 std::unique_ptr<CallService::Callback>
write;
603 if (prefix.size() > 0)
606 for (
auto client : clients) {
607 AppIDPath fullClientPath = prefix + client.relPath;
608 std::map<std::string, std::string> channelAssignments;
609 for (
auto assignment : client.channelAssignments)
610 if (assignment.second.type ==
"cosim")
611 channelAssignments[assignment.first] = std::any_cast<std::string>(
612 assignment.second.implOptions.at(
"name"));
618 const std::string &channelName,
620 const Type *type)
override;
624 std::map<AppIDPath, std::map<std::string, std::string>>
629std::unique_ptr<ChannelPort>
636 throw std::runtime_error(
"Could not find port for '" + idPath.
toStr() +
637 "." + channelName +
"'");
638 const std::map<std::string, std::string> &channelAssignments = f->second;
639 auto cosimChannelNameIter = channelAssignments.find(channelName);
640 if (cosimChannelNameIter == channelAssignments.end())
641 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
642 channelName +
"' in cosimulation");
647 if (!
conn.
rpcClient->getChannelDesc(cosimChannelNameIter->second, chDesc))
648 throw std::runtime_error(
"Could not find channel '" + idPath.
toStr() +
"." +
649 channelName +
"' in cosimulation");
651 std::unique_ptr<ChannelPort> port;
652 std::string fullChannelName = idPath.
toStr() +
"." + channelName;
654 port = std::make_unique<WriteCosimChannelPort>(
658 type, fullChannelName);
667 std::unique_ptr<Engine> engine =
nullptr;
668 if (engineTypeName ==
"cosim")
669 engine = std::make_unique<CosimEngine>(*
this, idPath, details, clients);
683 }
else if (svcType ==
typeid(
SysInfo)) {
686 return new CosimSysInfo(*
this,
rpcClient.get());
688 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.
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.
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.
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.
std::vector< MessageData > getMessageFrames(const MessageData &data)
Break a message into its frames.
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.
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.
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.