CIRCT 24.0.0git
Loading...
Searching...
No Matches
Cosim.cpp
Go to the documentation of this file.
1//===- Cosim.cpp - Connection to ESI simulation ---------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// DO NOT EDIT!
10// This file is distributed as part of an ESI package. The source for this file
11// should always be modified within CIRCT
12// (lib/dialect/ESI/runtime/cpp/lib/backends/Cosim.cpp).
13//
14//===----------------------------------------------------------------------===//
15
16#include "esi/backends/Cosim.h"
17#include "esi/Engines.h"
18#include "esi/Manifest.h"
19#include "esi/Ports.h"
20#include "esi/Services.h"
21#include "esi/Utils.h"
23
24#include <algorithm>
25#include <bit>
26#include <cstdlib>
27#include <cstring>
28#include <format>
29#include <fstream>
30#include <initializer_list>
31#include <iostream>
32#include <memory>
33#include <mutex>
34#include <new>
35#include <optional>
36#include <set>
37#include <string_view>
38#include <vector>
39
40using namespace esi;
41using namespace esi::services;
42using namespace esi::backends::cosim;
43
44namespace {
45
46//===----------------------------------------------------------------------===//
47// WriteCosimChannelPort
48//===----------------------------------------------------------------------===//
49
50/// Cosim client implementation of a write channel port. Applies the cosim
51/// protocol's credit-based flow control: while the number of frames not yet
52/// consumed by the simulation is at the in-flight limit, `tryWrite()` fails
53/// and `write()` blocks. Frames sent before the simulation has connected its
54/// end are held by the server, and count as in flight. The limit is
55/// `ConnectOptions::bufferSize` (0 = unbounded) if specified, else
56/// `defaultMaxInFlight`.
57///
58/// Implements callback mode with the RpcClient's equivalent
59/// (`connectServerSender()`): the data fetch callback is called on the
60/// RpcClient's transport thread whenever the channel is below its in-flight
61/// limit (e.g. as the simulation consumes frames) and the application may have
62/// data, and each message it returns is sent immediately. So, unlike the
63/// default implementation, this needs no polling and never holds a message.
64class WriteCosimChannelPort : public WriteChannelPort {
65public:
66 WriteCosimChannelPort(
67 AcceleratorConnection &conn, RpcClient &client,
68 const RpcClient::ChannelDesc &desc, const Type *type, std::string name,
69 unsigned defaultMaxInFlight = RpcClient::DefaultToServerMaxInFlight)
70 : WriteChannelPort(type), conn(conn), client(client), desc(desc),
71 name(std::move(name)), defaultMaxInFlight(defaultMaxInFlight) {}
72 ~WriteCosimChannelPort() { disconnect(); }
73
75 void connect(DataFetchCallback fetch, WriteErrorCallback onError,
76 const ConnectOptions &options = {}) override {
77 if (!fetch)
78 throw std::invalid_argument(
79 "WriteChannelPort::connect: null data fetch callback");
80 if (!onError)
81 throw std::invalid_argument(
82 "WriteChannelPort::connect: null error callback");
83 connectCallbackMode(options);
84 // Held until `sender` is set, so a callback (which may run as soon as the
85 // sender is registered) can't see the port connected without it.
86 std::lock_guard<std::mutex> lock(callbackMutex);
87 try {
88 sender = client.connectServerSender(
89 name,
90 [this, fetch = std::move(
91 fetch)]() -> std::optional<std::vector<MessageData>> {
92 std::unique_ptr<SegmentedMessageData> msg = fetch();
93 if (!msg)
94 return std::nullopt;
95 return toFrames(*msg);
96 },
97 std::move(onError));
98 } catch (...) {
100 throw;
101 }
102 // Fetch the first message (if any) now.
103 sender->notify();
104 }
105
106 void notifyAsyncDataAvailable() override {
107 std::lock_guard<std::mutex> lock(callbackMutex);
108 if (!sender)
109 throw std::runtime_error(
110 "Cannot call `notifyAsyncDataAvailable()` on a write channel which "
111 "is not connected in callback mode.");
112 sender->notify();
113 }
114
115 void disconnect() override {
116 std::unique_ptr<RpcClient::WriteChannelConnection> oldSender;
117 {
118 std::lock_guard<std::mutex> lock(callbackMutex);
119 oldSender = std::move(sender);
120 }
121 // Waits for a callback in progress on the transport thread to return,
122 // unless it's calling this.
123 if (oldSender)
124 oldSender->disconnect();
126 }
127
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));
134 }
135
136protected:
137 void traceWrite(const MessageData &data) {
138 conn.getLogger().trace(
139 [this,
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();
148 });
149 }
150
151 void writeImpl(const MessageData &data) override {
152 auto frames = getMessageFrames(data);
153 for (const auto &frame : frames) {
154 traceWrite(data);
155 client.writeToServer(name, frame);
156 }
157 }
158 bool tryWriteImpl(const MessageData &data) override {
159 auto frames = getMessageFrames(data);
160 // Admit the rest of a translated (windowed) message once its first frame
161 // was, like the frames of a multi-frame message, so `tryWrite()` never
162 // leaves part of a message waiting for a `flush()` which may not come.
163 bool rest = translateMessages && translationBufferIdx > 0;
164 if (!client.tryWriteToServer(name, frames, /*force=*/rest))
165 return false;
166 for (size_t i = 0; i < frames.size(); ++i)
167 traceWrite(data);
168 return true;
169 }
170
171private:
172 /// Translate a message into the frames to send.
173 std::vector<MessageData> toFrames(const SegmentedMessageData &msg) {
174 MessageData scratch;
175 const MessageData &data = msg.asMessageData(scratch);
176 std::vector<MessageData> frames;
177 if (translateMessages) {
178 try {
179 translateOutgoing(data);
180 } catch (...) {
181 translationBuffer.clear();
182 throw;
183 }
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));
190 } else {
191 frames = getMessageFrames(maybePadEmptyMessage(data));
192 }
193 for (size_t i = 0; i < frames.size(); ++i)
194 traceWrite(data);
195 return frames;
196 }
197
198 AcceleratorConnection &conn;
199 RpcClient &client;
200 RpcClient::ChannelDesc desc;
201 std::string name;
202 unsigned defaultMaxInFlight;
203
204 /// Protects `sender`.
205 std::mutex callbackMutex;
206 /// The callback mode connection, if any.
207 std::unique_ptr<RpcClient::WriteChannelConnection> sender;
208};
209
210//===----------------------------------------------------------------------===//
211// ReadCosimChannelPort
212//===----------------------------------------------------------------------===//
213
214/// Cosim client implementation of a read channel port. The wire transport
215/// (see `CosimRpc`) delivers messages via callback, so this class just
216/// forwards them to the registered `ReadChannelPort` consumer.
217class ReadCosimChannelPort : public ReadChannelPort {
218public:
219 ReadCosimChannelPort(AcceleratorConnection &conn, RpcClient &client,
220 const RpcClient::ChannelDesc &desc, const Type *type,
221 std::string name)
222 : ReadChannelPort(type), conn(conn), client(client), desc(desc),
223 name(std::move(name)) {}
224
225 ~ReadCosimChannelPort() = default;
226
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");
231
232 // Connect to the channel and set up callback.
233 connection = client.connectClientReceiver(
234 name,
235 [this](std::unique_ptr<SegmentedMessageData> &data) {
236 // Add trace logging for the received message.
237 conn.getLogger().trace(
238 [this, &data](
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();
248 });
249
250 bool consumed = invokeCallback(data);
251
252 if (consumed) {
253 // Log the message consumption.
254 conn.getLogger().trace(
255 [this](
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";
260 });
261 }
262
263 return consumed;
264 },
266 }
267
268 void disconnect() override {
269 conn.getLogger().debug("cosim_read", "Disconnecting channel " + name);
270 if (connection) {
271 connection->disconnect();
272 connection.reset();
273 }
275 }
276
277private:
278 AcceleratorConnection &conn;
279 RpcClient &client;
280 RpcClient::ChannelDesc desc;
281 std::string name;
282 std::unique_ptr<RpcClient::ReadChannelConnection> connection;
283};
284
285} // anonymous namespace
286
287//===----------------------------------------------------------------------===//
288// CosimAccelerator
289//===----------------------------------------------------------------------===//
290
291/// Parse the connection std::string and instantiate the accelerator. Support
292/// the traditional 'host:port' syntax and a path to 'cosim.cfg' which is output
293/// by the cosimulation when it starts (which is useful when it chooses its own
294/// port).
295std::unique_ptr<AcceleratorConnection>
296CosimAccelerator::connect(Context &ctxt, std::string connectionString) {
297 std::string portStr;
298 std::string host = "localhost";
299
300 size_t colon;
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;
307
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);
312 if (key == "port")
313 portStr = value;
314 else if (key == "host")
315 host = value;
316 }
317
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");
322 if (hostEnv)
323 host = hostEnv;
324 else
325 host = "localhost";
326 char *portEnv = getenv("ESI_COSIM_PORT");
327 if (portEnv)
328 portStr = portEnv;
329 else
330 throw std::runtime_error("ESI_COSIM_PORT environment variable not set");
331 } else {
332 throw std::runtime_error("Invalid connection std::string '" +
333 connectionString + "'");
334 }
335 uint16_t port = stoul(portStr);
336 auto conn = make_unique<CosimAccelerator>(ctxt, host, port);
337
338 // Using the MMIO manifest method is really only for internal debugging, so it
339 // doesn't need to be part of the connection string.
340 char *manifestMethod = getenv("ESI_COSIM_MANIFEST_MMIO");
341 if (manifestMethod != nullptr)
342 conn->setManifestMethod(ManifestMethod::MMIO);
343
344 return conn;
345}
346
347/// Construct and connect to a cosim server.
349 uint16_t port)
351 // Connect to the simulation.
352 rpcClient = std::make_unique<RpcClient>(getLogger(), hostname, port);
353}
359
360namespace {
361class CosimSysInfo : public SysInfo {
362#pragma pack(push, 1)
363 struct CycleInfo {
364 uint64_t freq;
365 uint64_t cycle;
366 };
367#pragma pack(pop)
368
369public:
370 CosimSysInfo(CosimAccelerator &conn, RpcClient *rpcClient)
371 : SysInfo(conn), rpcClient(rpcClient) {
372 // This is an optional interface; if the channels aren't present, we simply
373 // report no cycle/frequency information.
374 RpcClient::ChannelDesc argDesc, resultDesc;
375 if (!rpcClient->getChannelDesc("__cosim_cycle_count.arg", argDesc) ||
376 !rpcClient->getChannelDesc("__cosim_cycle_count.result", resultDesc))
377 return;
378
379 Context &ctxt = conn.getCtxt();
380 const esi::Type *i1Type = getType(ctxt, new BitsType("i1", 1));
381 const esi::Type *i64Type = getType(ctxt, new BitsType("i64", 64));
382 const esi::Type *resultType =
383 getType(ctxt, new StructType(resultDesc.type,
384 {{"cycle", i64Type}, {"freq", i64Type}}));
385
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");
390 auto *bundleType =
391 new BundleType("cosimCycleCount",
392 {{"arg", BundleType::Direction::To, i1Type},
393 {"result", BundleType::Direction::From, resultType}});
394 func.reset(FuncService::Function::get(AppID("__cosim_cycle_count"),
395 bundleType, *reqPort, *respPort));
396 func->connect();
397 }
398
399 uint32_t getEsiVersion() const override { return rpcClient->getEsiVersion(); }
400 std::optional<uint64_t> getCycleCount() const override {
401 if (!func)
402 return std::nullopt;
403 return getCycleInfo().cycle;
404 }
405 std::optional<uint64_t> getCoreClockFrequency() const override {
406 if (!func)
407 return std::nullopt;
408 return getCycleInfo().freq;
409 }
410
411 std::vector<uint8_t> getCompressedManifest() const override {
412 return rpcClient->getCompressedManifest();
413 }
414
415private:
416 const esi::Type *getType(Context &ctxt, esi::Type *type) {
417 if (auto t = ctxt.getType(type->getID())) {
418 delete type;
419 return *t;
420 }
421 ctxt.registerType(type);
422 return type;
423 }
424
425 RpcClient *rpcClient;
426 std::unique_ptr<WriteCosimChannelPort> reqPort;
427 std::unique_ptr<ReadCosimChannelPort> respPort;
428 std::unique_ptr<FuncService::Function> func;
429
430 CycleInfo getCycleInfo() const {
431 MessageData arg({1}); // 1-bit trigger message
432 std::future<MessageData> result = func->call(arg);
433 result.wait();
434 MessageData respMsg = result.get();
435 return *respMsg.as<CycleInfo>();
436 }
437};
438} // namespace
439
440namespace {
441class CosimMMIO : public MMIO {
442public:
443 CosimMMIO(CosimAccelerator &conn, Context &ctxt, const AppIDPath &idPath,
444 RpcClient *rpcClient, const HWClientDetails &clients)
445 : MMIO(conn, idPath, clients) {
446 // We have to locate the channels ourselves since this service might be used
447 // to retrieve the manifest.
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");
452
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)}}));
458
459 // Get ports, create the function, then connect to it.
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}});
467 cmdMMIO.reset(FuncService::Function::get(AppID("__cosim_mmio"), bundleType,
468 *cmdArgPort, *cmdRespPort));
469 cmdMMIO->connect();
470 }
471
472#pragma pack(push, 1)
473 struct MMIOCmd {
474 uint64_t data;
475 uint32_t offset;
476 bool write;
477 };
478#pragma pack(pop)
479
480 // Call the read function and wait for a response.
481 uint64_t read(uint32_t addr) const override {
482 MMIOCmd cmd{.data = 0, .offset = addr, .write = false};
483 auto arg = MessageData::from(cmd);
484 std::lock_guard<std::mutex> g(mmioCmdLock);
485 std::future<MessageData> result = cmdMMIO->call(arg);
486 result.wait();
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);
493 });
494 return ret;
495 }
496
497 void write(uint32_t addr, uint64_t data) override {
498 conn.getLogger().trace(
499 [addr,
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);
504 });
505 MMIOCmd cmd{.data = data, .offset = addr, .write = true};
506 auto arg = MessageData::from(cmd);
507 std::lock_guard<std::mutex> g(mmioCmdLock);
508 std::future<MessageData> result = cmdMMIO->call(arg);
509 result.wait();
510 }
511
512private:
513 const esi::Type *getType(Context &ctxt, esi::Type *type) {
514 if (auto t = ctxt.getType(type->getID())) {
515 delete type;
516 return *t;
517 }
518 ctxt.registerType(type);
519 return type;
520 }
521 std::unique_ptr<WriteCosimChannelPort> cmdArgPort;
522 std::unique_ptr<ReadCosimChannelPort> cmdRespPort;
523 std::unique_ptr<FuncService::Function> cmdMMIO;
524};
525
526#pragma pack(push, 1)
527struct HostMemReadReq {
528 uint8_t tag;
529 uint32_t length;
530 uint64_t address;
531};
532
533using HostMemWriteResp = uint8_t;
534#pragma pack(pop)
535
536// ESI lowers a parallel-window frame MSB-first (the first-declared field
537// occupies the highest bits) into a little-endian byte buffer; array elements
538// are packed least-index-first (element[0] in the low bits). The sub-byte
539// `last` / `data_size` fields make these frames bit-packed and not
540// byte-aligned, so -- to stay ABI-portable across toolchains (bit-field and
541// sub-byte `#pragma pack` layout is not guaranteed under MSVC) -- each frame is
542// a plain byte array whose bits are assembled/extracted explicitly with these
543// helpers. `bitOff` counts from the LSB (bit 0 of byte 0).
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));
548}
549uint64_t getBits(const uint8_t *buf, size_t bitOff, size_t width) {
550 uint64_t val = 0;
551 for (size_t i = 0; i < width; ++i)
552 if (buf[(bitOff + i) >> 3] & (1u << ((bitOff + i) & 7)))
553 val |= (1ULL << i);
554 return val;
555}
556
557const StructType &getHostMemPayload(const Type *type,
558 std::string_view direction) {
559 auto *payload = getUnwrappedAs<StructType>(type);
560 if (!payload)
561 throw std::runtime_error(
562 std::format("Invalid HostMem {} channel layout", direction));
563 return *payload;
564}
565
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";
571 });
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));
580 return width / 8;
581}
582
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));
598 ++field;
599 }
600}
601
602// One read response beat, packed MSB-first: tag | data | last. The data starts
603// at bit 1, and unused bytes in a partial final beat are zero-filled.
604class HostMemReadRespFrame {
605public:
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);
613 }
614
615 MessageData toMessage() const {
616 return MessageData(bytes.data(), bytes.size());
617 }
618
619private:
620 std::vector<uint8_t> bytes;
621};
622
623// Write-request frame: one bus beat of a burst write. The upstream write
624// request is packed MSB-first: address | tag | data | data_size | last.
625// `data_size` holds (valid_bytes - 1), with log2(bus bytes) bits.
626// The data width is discovered from the advertised channel type.
627class HostMemWriteReqFrame {
628public:
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) {}
632
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);
637 }
638 // Number of valid data bytes in this beat (data_size holds valid_bytes - 1).
639 size_t validBytes() const { return getBits(bytes, 1, sizeWidth) + 1; }
640 bool last() const { return getBits(bytes, 0, 1) != 0; }
641
642private:
643 const uint8_t *bytes;
644 size_t sizeWidth, dataOff, tagOff, addrOff;
645};
646
647// PCIe caps a single memory read request at the Max_Read_Request_Size, whose
648// largest encoding (PCIe Gen 4 and earlier) is 4096 bytes, but root ports often
649// negotiate a smaller limit. Model a conservative 64-double-word (256-byte) cap
650// here, raised to one beat if the configured cosim word is larger.
651static constexpr uint32_t kPcieMaxReadRequestBytes = 64 * 4;
652
653class CosimHostMem : public HostMem {
654public:
655 CosimHostMem(AcceleratorConnection &acc, Context &ctxt, RpcClient *rpcClient)
656 : HostMem(acc), acc(acc), ctxt(ctxt), rpcClient(rpcClient) {}
657
658 void start() override {
659 // We have to locate the channels ourselves since this service might be used
660 // to retrieve the manifest.
661
662 if (writeRespPort)
663 return;
664
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");
669
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");
674
675 // HostMem may be started before the caller has parsed the manifest.
676 if (!ctxt.getType(writeArg.type) || !ctxt.getType(readResp.type))
677 Manifest manifest(ctxt, acc.getService<SysInfo>()->getJsonManifest());
678 auto channelType = [this](const RpcClient::ChannelDesc &desc) {
679 auto type = ctxt.getType(desc.type);
680 if (!type)
681 throw std::runtime_error("HostMem channel type not in manifest: " +
682 desc.type);
683 return *type;
684 };
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,
690 {{"address", 64},
691 {"tag", 8},
692 {"data", writeDataBytes * 8},
693 {"data_size", writeSizeWidth},
694 {"last", 1}},
695 "write");
696 writeFrameBytes =
697 (64 + 8 + writeDataBytes * 8 + writeSizeWidth + 1 + 7) / 8;
698
699 // Setup the read side callback.
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}},
705 "read");
706 const esi::Type *readReqType = channelType(readArg);
707
708 // Get ports. Unfortunately, we can't model this as a callback since there
709 // will sometimes be multiple responses per request. Like PCIe read
710 // completions, responses are not flow controlled: the requester must
711 // already have room for them, so give them no in-flight limit.
712 readRespPort = std::make_unique<WriteCosimChannelPort>(
713 conn, *rpcClient, readResp, readRespType,
714 "__cosim_hostmem_read_resp.data", /*defaultMaxInFlight=*/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); });
721
722 // Setup the write side callback.
723 const esi::Type *writeRespType = channelType(writeResp);
724
725 // Get ports, create the function, then connect to it. Write completions
726 // are unbounded for the same reason as read responses.
727 writeRespPort = std::make_unique<WriteCosimChannelPort>(
728 conn, *rpcClient, writeResp, writeRespType,
729 "__cosim_hostmem_write.result", /*defaultMaxInFlight=*/0);
730 writeReqPort = std::make_unique<ReadCosimChannelPort>(
731 conn, *rpcClient, writeArg, writeReqType, "__cosim_hostmem_write.arg");
732 auto *bundleType = new BundleType(
733 "cosimHostMem",
734 {{"arg", BundleType::Direction::To, writeReqType},
735 {"result", BundleType::Direction::From, writeRespType}});
736 write.reset(CallService::Callback::get(acc, AppID("__cosim_hostmem_write"),
737 bundleType, *writeRespPort,
738 *writeReqPort));
739 write->connect([this](const MessageData &req) { return serviceWrite(req); },
740 true);
741 }
742
743 // Service the read request as a callback. Simply reads the data from the
744 // location specified. TODO: check that the memory has been mapped.
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);
754 });
755 // Send one response per bus word. Zero-length reads (e.g. void / zero-width
756 // types) indicates a bug in the hardware and we log an error, but we still
757 // send a single response.
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(
763 "hostmem",
764 std::format("Read request with length=0 from addr=0x{} tag={}. "
765 "Reads of length 0 are not valid and indicate a bug "
766 "in the requester.",
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(
772 "hostmem",
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,
778 maxReadBytes));
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);
793 });
794 readRespPort->write(frame.toMessage());
795 }
796 return true;
797 }
798
799 // Service a write request as a callback. Simply write the data to the
800 // location specified. TODO: check that the memory has been mapped.
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) +
806 ".");
807 HostMemWriteReqFrame req(reqBytes.getBytes(), writeDataBytes,
808 writeSizeWidth);
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());
817 });
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();
823 return MessageData::from(resp);
824 }
825
826 struct CosimHostMemRegion : public HostMemRegion {
827 CosimHostMemRegion(std::size_t size) : ptr(malloc(size)), size(size) {
828 if (ptr)
829 memset(ptr, 0xFF, size);
830 }
831 virtual ~CosimHostMemRegion() { free(ptr); }
832 virtual void *getPtr() const override { return ptr; }
833 virtual std::size_t getSize() const override { return size; }
834
835 private:
836 void *ptr;
837 std::size_t size;
838 };
839
840 virtual std::unique_ptr<HostMemRegion>
841 allocate(std::size_t size, HostMem::Options opts) const override {
842 if (size == 0)
843 return nullptr;
844 std::unique_ptr<HostMemRegion> ret(new (std::nothrow)
845 CosimHostMemRegion(size));
846 if (!ret || !ret->getPtr())
847 return nullptr;
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);
854 });
855 return ret;
856 }
857 virtual bool mapMemory(void *ptr, std::size_t size,
858 HostMem::Options opts) const override {
859 return true;
860 }
861 virtual void unmapMemory(void *ptr) const override {}
862
863private:
864 AcceleratorConnection &acc;
865 Context &ctxt;
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;
877};
878} // namespace
879
880namespace esi::backends::cosim {
881/// Implement the magic cosim channel communication.
882class CosimEngine : public Engine {
883public:
885 const ServiceImplDetails &details, const HWClientDetails &clients)
886 : Engine(conn), conn(conn) {
887 // Compute our parents idPath path.
888 AppIDPath prefix = std::move(idPath);
889 if (prefix.size() > 0)
890 prefix.pop_back();
891
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"));
899 clientChannelAssignments[fullClientPath] = std::move(channelAssignments);
900 }
901 }
902
903 std::unique_ptr<ChannelPort> createPort(AppIDPath idPath,
904 const std::string &channelName,
906 const Type *type) override;
907
908private:
910 std::map<AppIDPath, std::map<std::string, std::string>>
912};
913} // namespace esi::backends::cosim
914
915std::unique_ptr<ChannelPort>
916CosimEngine::createPort(AppIDPath idPath, const std::string &channelName,
917 BundleType::Direction dir, const Type *type) {
918
919 // Find the client details for the port at 'fullPath'.
920 auto f = clientChannelAssignments.find(idPath);
921 if (f == clientChannelAssignments.end())
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");
929
930 // Get the endpoint, which may or may not exist. Construct the port.
931 // Everything is validated when the client calls 'connect()' on the port.
933 if (!conn.rpcClient->getChannelDesc(cosimChannelNameIter->second, chDesc))
934 throw std::runtime_error("Could not find channel '" + idPath.toStr() + "." +
935 channelName + "' in cosimulation");
936
937 std::unique_ptr<ChannelPort> port;
938 std::string fullChannelName = idPath.toStr() + "." + channelName;
939 if (BundlePort::isWrite(dir))
940 port = std::make_unique<WriteCosimChannelPort>(
941 conn, *conn.rpcClient, chDesc, type, fullChannelName);
942 else
943 port = std::make_unique<ReadCosimChannelPort>(conn, *conn.rpcClient, chDesc,
944 type, fullChannelName);
945 return port;
946}
947
948void CosimAccelerator::createEngine(const std::string &engineTypeName,
949 AppIDPath idPath,
950 const ServiceImplDetails &details,
951 const HWClientDetails &clients) {
952
953 std::unique_ptr<Engine> engine = nullptr;
954 if (engineTypeName == "cosim")
955 engine = std::make_unique<CosimEngine>(*this, idPath, details, clients);
956 else
957 engine = ::esi::registry::createEngine(*this, engineTypeName, idPath,
958 details, clients);
959 registerEngine(idPath, std::move(engine), clients);
960}
962 AppIDPath idPath, std::string implName,
963 const ServiceImplDetails &details,
964 const HWClientDetails &clients) {
965 if (svcType == typeid(services::MMIO)) {
966 return new CosimMMIO(*this, getCtxt(), idPath, rpcClient.get(), clients);
967 } else if (svcType == typeid(services::HostMem)) {
968 return new CosimHostMem(*this, getCtxt(), rpcClient.get());
969 } else if (svcType == typeid(SysInfo)) {
970 switch (manifestMethod) {
972 return new CosimSysInfo(*this, rpcClient.get());
975 }
976 }
977 return nullptr;
978}
979
983
#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...
Definition RpcClient.h:73
static constexpr unsigned DefaultToServerMaxInFlight
Default maximum number of frames sent to a server-bound channel which the simulation has not yet cons...
Definition RpcClient.h:70
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
Definition Manifest.cpp:816
Bits are just an array of bits.
Definition Types.h:224
static bool isWrite(BundleType::Direction bundleDir)
Compute the direction of a channel given the bundle direction and the bundle port's direction.
Definition Ports.h:757
Bundles represent a collection of channels.
Definition Types.h:104
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Definition Context.h:34
std::optional< const Type * > getType(Type::ID id) const
Resolve a type id to the type.
Definition Context.h:50
void registerType(Type *type)
Register a type with the context. Takes ownership of the pointer type.
Definition Context.cpp:33
Engine(AcceleratorConnection &conn)
Definition Engines.h:44
const uint8_t * getBytes() const
Definition Common.h:216
const T * as() const
Cast to a type.
Definition Common.h:240
size_t getSize() const
Get the size of the data in bytes.
Definition Common.h:230
static MessageData from(T &t)
Cast from a type to its raw bytes.
Definition Common.h:250
A ChannelPort which reads data from the accelerator.
Definition Ports.h:595
virtual void disconnect() override
Disconnect the channel.
Definition Ports.cpp:71
const MessageData & asMessageData(MessageData &scratch) const
Return this message as a MessageData without copying if it already is one.
Definition Common.cpp:62
Structs are an ordered collection of fields, each with a name and a type.
Definition Types.h:264
const FieldVector & getFields() const
Definition Types.h:272
Root class of the ESI type system.
Definition Types.h:36
ID getID() const
Definition Types.h:42
A ChannelPort which sends data to the accelerator.
Definition Ports.h:315
virtual void disconnect() override
Disconnect the port.
Definition Ports.cpp:902
virtual void connect(const ConnectOptions &options={}) override
Connect in sync mode. Throws if connected in callback mode.
Definition Ports.cpp:867
Connect to an ESI simulation.
Definition Cosim.h:36
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.
Definition Cosim.cpp:948
std::unique_ptr< RpcClient > rpcClient
Definition Cosim.h:65
void setManifestMethod(ManifestMethod method)
Definition Cosim.cpp:980
static std::unique_ptr< AcceleratorConnection > connect(Context &, std::string connectionString)
Parse the connection std::string and instantiate the accelerator.
Definition Cosim.cpp:296
virtual Service * createService(Service::Type service, AppIDPath path, std::string implName, const ServiceImplDetails &details, const HWClientDetails &clients) override
Called by getServiceImpl exclusively.
Definition Cosim.cpp:961
CosimAccelerator(Context &, std::string hostname, uint16_t port)
Construct and connect to a cosim server.
Definition Cosim.cpp:348
std::set< std::unique_ptr< ChannelPort > > channels
Definition Cosim.h:69
CosimEngine(CosimAccelerator &conn, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients)
Definition Cosim.cpp:884
std::map< AppIDPath, std::map< std::string, std::string > > clientChannelAssignments
Definition Cosim.cpp:911
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.
Definition Cosim.cpp:916
A client for the cosim RPC server.
Definition RpcClient.h:36
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)
Definition Services.cpp:357
static Function * get(AppID id, BundleType *type, WriteChannelPort &arg, ReadChannelPort &result)
Definition Services.cpp:308
Implement the SysInfo API for a standard MMIO protocol.
Definition Services.h:213
const std::type_info & Type
Definition Services.h:61
Information about the Accelerator system.
Definition Services.h:113
connect(destination, source)
Definition support.py:39
std::unique_ptr< Engine > createEngine(AcceleratorConnection &conn, const std::string &dmaEngineName, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients)
Create an engine by name.
Definition Engines.cpp:562
Definition esi.py:1
std::string toHex(void *val)
Definition Common.cpp:38
std::vector< HWClientDetail > HWClientDetails
Definition Common.h:108
std::map< std::string, std::any > ServiceImplDetails
Definition Common.h:109
const T * getUnwrappedAs(const Type *type)
Unwrap aliases and channels, then cast the payload to T.
Definition Types.h:203
write(addr, data)
Definition xrt_cosim.py:30
read(addr)
Definition xrt_cosim.py:23
Description of a channel from the server.
Definition RpcClient.h:55
std::optional< unsigned > bufferSize
The buffer size is optional and should be considered merely a hint.
Definition Ports.h:128
Description of a channel from the server.
Definition RpcClient.h:55