CIRCT 22.0.0git
Loading...
Searching...
No Matches
Services.cpp
Go to the documentation of this file.
1//===- StdServices.cpp - implementations of std services ------------------===//
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/Services.h"
17#include "esi/Accelerator.h"
18#include "esi/Engines.h"
19
20#include "zlib.h"
21
22#include <cassert>
23#include <stdexcept>
24
25using namespace esi;
26using namespace esi::services;
27
29 std::string implName,
30 ServiceImplDetails details,
31 HWClientDetails clients) {
32 return conn.getService(service, id, implName, details, clients);
33}
34
35std::string SysInfo::getServiceSymbol() const { return "__builtin_SysInfo"; }
36
37// Allocate 10MB for the uncompressed manifest. This should be plenty.
38constexpr uint32_t MAX_MANIFEST_SIZE = 10 << 20;
39/// Get the compressed manifest, uncompress, and return it.
40std::string SysInfo::getJsonManifest() const {
41 std::vector<uint8_t> compressed = getCompressedManifest();
42 std::vector<Bytef> dst(MAX_MANIFEST_SIZE);
43 uLongf dstSize = MAX_MANIFEST_SIZE;
44 int rc =
45 uncompress(dst.data(), &dstSize, compressed.data(), compressed.size());
46 if (rc != Z_OK)
47 throw std::runtime_error("zlib uncompress failed with rc=" +
48 std::to_string(rc));
49 return std::string(reinterpret_cast<char *>(dst.data()), dstSize);
50}
51
52//===----------------------------------------------------------------------===//
53// MMIO class implementations.
54//===----------------------------------------------------------------------===//
55
57 const HWClientDetails &clients)
58 : Service(conn) {
59 AppIDPath idParent = idPath.parent();
60 for (const HWClientDetail &client : clients) {
61 auto offsetIter = client.implOptions.find("offset");
62 if (offsetIter == client.implOptions.end())
63 throw std::runtime_error("MMIO client missing 'offset' option");
64 const Constant *offset = std::any_cast<Constant>(&offsetIter->second);
65 if (!offset)
66 throw std::runtime_error(
67 "MMIO client 'offset' option must be a constant");
68 const uint64_t *offsetVal = std::any_cast<uint64_t>(&offset->value);
69 if (!offsetVal)
70 throw std::runtime_error(
71 "MMIO client 'offset' option must be an integer");
72 if (*offsetVal >= 1ull << 32)
73 throw std::runtime_error("MMIO client offset mustn't exceed 32 bits");
74
75 auto sizeIter = client.implOptions.find("size");
76 if (sizeIter == client.implOptions.end())
77 throw std::runtime_error("MMIO client missing 'size' option");
78 const Constant *size = std::any_cast<Constant>(&sizeIter->second);
79 if (!size)
80 throw std::runtime_error("MMIO client 'size' option must be a constant");
81 const uint64_t *sizeVal = std::any_cast<uint64_t>(&size->value);
82 if (!sizeVal)
83 throw std::runtime_error("MMIO client 'size' option must be an integer");
84 if (*sizeVal >= 1ull << 32)
85 throw std::runtime_error("MMIO client size mustn't exceed 32 bits");
86 regions[client.relPath] = RegionDescriptor{
87 static_cast<uint32_t>(*offsetVal), static_cast<uint32_t>(*sizeVal)};
88 }
89}
90
91std::string MMIO::getServiceSymbol() const {
92 return std::string(MMIO::StdName);
93}
95 auto regionIter = regions.find(id);
96 if (regionIter == regions.end())
97 return nullptr;
98 return new MMIORegion(id.back(), const_cast<MMIO *>(this),
99 regionIter->second);
100}
101
102namespace {
103class MMIOPassThrough : public MMIO {
104public:
105 MMIOPassThrough(const HWClientDetails &clients, const AppIDPath &idPath,
106 MMIO *parent)
107 : MMIO(parent->getConnection(), idPath, clients), parent(parent) {}
108 uint64_t read(uint32_t addr) const override { return parent->read(addr); }
109 void write(uint32_t addr, uint64_t data) override {
110 parent->write(addr, data);
111 }
112
113private:
114 MMIO *parent;
115};
116} // namespace
117
119 std::string implName, ServiceImplDetails details,
120 HWClientDetails clients) {
121 if (service != typeid(MMIO))
122 return Service::getChildService(service, id, implName, details, clients);
123 return new MMIOPassThrough(clients, id, this);
124}
125
126//===----------------------------------------------------------------------===//
127// MMIO Region service port class implementations.
128//===----------------------------------------------------------------------===//
129
131 : ServicePort(id, nullptr, {}), parent(parent), desc(desc) {}
132uint64_t MMIO::MMIORegion::read(uint32_t addr) const {
133 if (addr >= desc.size)
134 throw std::runtime_error("MMIO read out of bounds: " + toHex(addr));
135 return parent->read(desc.base + addr);
136}
137void MMIO::MMIORegion::write(uint32_t addr, uint64_t data) {
138 if (addr >= desc.size)
139 throw std::runtime_error("MMIO write out of bounds: " + toHex(addr));
140 parent->write(desc.base + addr, data);
141}
142
144 : SysInfo(mmio->getConnection()), mmio(mmio) {}
145
147 uint64_t reg;
148 if ((reg = mmio->read(MetadataOffset)) != MagicNumber)
149 throw std::runtime_error("Invalid magic number: " + toHex(reg));
150 return mmio->read(MetadataOffset + 8);
151}
152
153std::vector<uint8_t> MMIOSysInfo::getCompressedManifest() const {
154 uint64_t version = getEsiVersion();
155 if (version != 0)
156 throw std::runtime_error("Unsupported ESI header version: " +
157 std::to_string(version));
158 uint64_t manifestPtr = mmio->read(MetadataOffset + 0x10);
159 uint64_t size = mmio->read(manifestPtr);
160 uint64_t numWords = (size + 7) / 8;
161 std::vector<uint64_t> manifestWords(numWords);
162 for (size_t i = 0; i < numWords; ++i)
163 manifestWords[i] = mmio->read(manifestPtr + 8 + (i * 8));
164
165 std::vector<uint8_t> manifest;
166 for (size_t i = 0; i < size; ++i) {
167 uint64_t word = manifestWords[i / 8];
168 manifest.push_back(word >> (8 * (i % 8)));
169 }
170 return manifest;
171}
172
173std::string HostMem::getServiceSymbol() const { return "__builtin_HostMem"; }
174
176 const ServiceImplDetails &details,
177 const HWClientDetails &clients)
178 : Service(conn), id(idPath) {
179 if (auto f = details.find("service"); f != details.end()) {
180 serviceSymbol = std::any_cast<std::string>(f->second);
181 // Strip off initial '@'.
182 serviceSymbol = serviceSymbol.substr(1);
183 }
184}
185
187 return new BundlePort(id.back(), type,
188 conn.getEngineMapFor(id).requestPorts(id, type));
189}
190
192 ServiceImplDetails details, HWClientDetails clients)
193 : Service(conn) {
194
195 if (auto f = details.find("service"); f != details.end())
196 // Strip off initial '@'.
197 symbol = std::any_cast<std::string>(f->second).substr(1);
198}
199
200std::string FuncService::getServiceSymbol() const { return symbol; }
201
203 return new Function(id.back(), type,
204 conn.getEngineMapFor(id).requestPorts(id, type));
205}
206
208 WriteChannelPort &arg,
209 ReadChannelPort &result) {
210 return new Function(
211 id, type, {{std::string("arg"), arg}, {std::string("result"), result}});
212 return nullptr;
213}
214
216 if (connected)
217 throw std::runtime_error("Function is already connected");
218 if (channels.size() != 2)
219 throw std::runtime_error("FuncService must have exactly two channels");
220 arg = &getRawWrite("arg");
221 arg->connect();
222 result = &getRawRead("result");
223 result->connect();
224 connected = true;
225}
226
227std::future<MessageData>
229 if (!connected)
230 throw std::runtime_error("Function must be 'connect'ed before calling");
231 std::scoped_lock<std::mutex> lock(callMutex);
232 arg->write(argData);
233 return result->readAsync();
234}
235
237 ServiceImplDetails details)
238 : Service(acc) {
239 if (auto f = details.find("service"); f != details.end())
240 // Strip off initial '@'.
241 symbol = std::any_cast<std::string>(f->second).substr(1);
242}
243
244std::string CallService::getServiceSymbol() const { return symbol; }
245
247 return new Callback(conn, id.back(), type,
248 conn.getEngineMapFor(id).requestPorts(id, type));
249}
250
252 const BundleType *type, PortMap channels)
253 : ServicePort(id, type, channels), acc(acc) {}
254
256 AppID id,
257 const BundleType *type,
258 WriteChannelPort &result,
259 ReadChannelPort &arg) {
260 return new Callback(acc, id, type, {{"arg", arg}, {"result", result}});
261}
262
264 std::function<MessageData(const MessageData &)> callback, bool quick) {
265 if (channels.size() != 2)
266 throw std::runtime_error("CallService must have exactly two channels");
267 result = &getRawWrite("result");
268 result->connect();
269 arg = &getRawRead("arg");
270 if (quick) {
271 // If it's quick, we can just call the callback directly.
272 arg->connect([this, callback](MessageData argMsg) -> bool {
273 MessageData resultMsg = callback(std::move(argMsg));
274 this->result->write(std::move(resultMsg));
275 return true;
276 });
277 } else {
278 // If it's not quick, we need to use the service thread.
279 arg->connect();
280 acc.getServiceThread()->addListener(
281 {arg}, [this, callback](ReadChannelPort *, MessageData argMsg) -> void {
282 MessageData resultMsg = callback(std::move(argMsg));
283 this->result->write(std::move(resultMsg));
284 });
285 }
286}
287
290 ServiceImplDetails details,
291 HWClientDetails clients)
292 : Service(conn), id(idPath), mmio(nullptr) {
293 // Compute our parents idPath path.
294 AppIDPath prefix = std::move(idPath);
295 if (prefix.size() > 0)
296 prefix.pop_back();
297 for (const HWClientDetail &client : clients) {
298 if (client.implOptions.contains("type") &&
299 std::any_cast<std::string>(client.implOptions.at("type")) != "mmio")
300 continue; // Not an MMIO assignment.
301 AppIDPath fullClientPath = prefix + client.relPath;
302 auto offsetIter = client.implOptions.find("offset");
303 if (offsetIter == client.implOptions.end()) {
304 conn.getLogger().warning("Telemetry",
305 "mmio client " + fullClientPath.toStr() +
306 " missing 'offset' option, skipping");
307 continue;
308 }
309 const Constant *offset = std::any_cast<Constant>(&offsetIter->second);
310 if (offset == nullptr) {
312 "Telemetry", "mmio client " + fullClientPath.toStr() +
313 " 'offset' option must be a constant, skipping");
314 continue;
315 }
316 const uint64_t *offsetVal = std::any_cast<uint64_t>(&offset->value);
317 if (offsetVal == nullptr) {
319 "Telemetry", "mmio client " + fullClientPath.toStr() +
320 " 'offset' option must be an integer, skipping");
321 continue;
322 }
323 portAddressAssignments.emplace(fullClientPath, *offsetVal);
324 }
325}
326
328 return std::string(TelemetryService::StdName);
329}
330
332 if (!mmio) {
333 AppIDPath lastPath;
334 AppIDPath mmioPath = id;
335 mmioPath.pop_back();
336 mmioPath.push_back(AppID("__telemetry_mmio"));
337 auto port = conn.getAccelerator().resolvePort(mmioPath, lastPath);
338 if (!port)
339 throw std::runtime_error("TelemetryService: could not resolve port " +
340 id.toStr() + ". Got as far as " +
341 lastPath.toStr());
342 mmio = dynamic_cast<MMIO::MMIORegion *>(port);
343 if (!mmio)
344 throw std::runtime_error("TelemetryService: port " + id.toStr() +
345 " is not a MMIO region");
346 }
347 return mmio;
348}
349
351 const BundleType *type) const {
352 auto offsetIter = portAddressAssignments.find(id);
353 auto *port = new Metric(id.back(), type, {}, this,
354 offsetIter != portAddressAssignments.end()
355 ? std::optional<uint64_t>(offsetIter->second)
356 : std::nullopt);
357 telemetryPorts.insert(std::make_pair(id, port));
358 return port;
359}
360
362 std::string implName,
363 ServiceImplDetails details,
364 HWClientDetails clients) {
365 TelemetryService *child = new TelemetryService(id, conn, details, clients);
366 children.push_back(child);
367 return child;
368}
369
371 PortMap channels,
372 const TelemetryService *telemetryService,
373 std::optional<uint64_t> offset)
374 : ServicePort(id, type, channels), telemetryService(telemetryService),
375 mmio(nullptr), offset(offset) {}
376
377/// Connect to a particular telemetry port. Offset should be non-nullopt.
379 if (!offset.has_value())
380 throw std::runtime_error("Telemetry offset not found for " + id.toString());
381 mmio = telemetryService->getMMIORegion();
382 assert(mmio && "TelemetryService: MMIO region not found");
383}
384
385std::future<MessageData> TelemetryService::Metric::read() {
386 return std::async(std::launch::async, [this]() {
387 uint64_t data = readInt();
388 return MessageData::from(data);
389 });
390}
391
393 assert(offset.has_value() &&
394 "Telemetry offset must be set. Checked in connect().");
395 assert(mmio && "TelemetryService: MMIO region not set");
396 return mmio->read(*offset);
397}
398
399void TelemetryService::getTelemetryPorts(std::map<AppIDPath, Metric *> &ports) {
400 for (const auto &entry : telemetryPorts)
401 ports[entry.first] = entry.second;
402 for (TelemetryService *child : children)
403 child->getTelemetryPorts(ports);
404}
405
407 Service::Type svcType, AppIDPath id,
408 std::string implName,
409 ServiceImplDetails details,
410 HWClientDetails clients) {
411 // TODO: Add a proper registration mechanism.
412 if (svcType == typeid(FuncService))
413 return new FuncService(id, *acc, details, clients);
414 if (svcType == typeid(CallService))
415 return new CallService(*acc, id, details);
416 if (svcType == typeid(TelemetryService))
417 return new TelemetryService(id, *acc, details, clients);
418 if (svcType == typeid(CustomService))
419 return new CustomService(id, *acc, details, clients);
420 return nullptr;
421}
422
424 // TODO: Add a proper registration mechanism.
425 if (svcName == "esi.service.std.func")
426 return typeid(FuncService);
427 if (svcName == "esi.service.std.call")
428 return typeid(CallService);
429 if (svcName == MMIO::StdName)
430 return typeid(MMIO);
431 if (svcName == HostMem::StdName)
432 return typeid(HostMem);
433 if (svcName == TelemetryService::StdName)
434 return typeid(TelemetryService);
435 return typeid(CustomService);
436}
assert(baseType &&"element must be base type")
constexpr uint32_t MAX_MANIFEST_SIZE
Definition Services.cpp:38
Abstract class representing a connection to an accelerator.
Definition Accelerator.h:79
ServiceClass * getService(AppIDPath id={}, std::string implName={}, ServiceImplDetails details={}, HWClientDetails clients={})
Get a typed reference to a particular service type.
Accelerator & getAccelerator()
virtual const BundleEngineMap & getEngineMapFor(AppIDPath id)
Logger & getLogger() const
Definition Accelerator.h:84
std::string toStr() const
Definition Manifest.cpp:739
AppIDPath parent() const
Definition Manifest.cpp:732
PortMap requestPorts(const AppIDPath &idPath, const BundleType *bundleType) const
Request ports for all the channels in a bundle.
Definition Engines.cpp:468
Services provide connections to 'bundles' – collections of named, unidirectional communication channe...
Definition Ports.h:226
const BundleType * type
Definition Ports.h:269
Bundles represent a collection of channels.
Definition Types.h:97
BundlePort * resolvePort(const AppIDPath &path, AppIDPath &lastLookup) const
Attempt to resolve a path to a port.
Definition Design.cpp:72
virtual void warning(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a warning.
Definition Logging.h:70
A logical chunk of data representing serialized data.
Definition Common.h:113
static MessageData from(T &t)
Cast from a type to its raw bytes.
Definition Common.h:158
A ChannelPort which reads data from the accelerator.
Definition Ports.h:124
A ChannelPort which sends data to the accelerator.
Definition Ports.h:77
A function call which gets attached to a service port.
Definition Services.h:324
static Callback * get(AcceleratorConnection &acc, AppID id, const BundleType *type, WriteChannelPort &result, ReadChannelPort &arg)
Definition Services.cpp:255
Callback(AcceleratorConnection &acc, AppID id, const BundleType *, PortMap channels)
Definition Services.cpp:251
void connect(std::function< MessageData(const MessageData &)> callback, bool quick=false)
Connect a callback to code which will be executed when the accelerator invokes the callback.
Definition Services.cpp:263
Service for servicing function calls from the accelerator.
Definition Services.h:314
virtual std::string getServiceSymbol() const override
Definition Services.cpp:244
CallService(AcceleratorConnection &acc, AppIDPath id, ServiceImplDetails details)
Definition Services.cpp:236
virtual BundlePort * getPort(AppIDPath id, const BundleType *type) const override
Get specialized port for this service to attach to the given appid path.
Definition Services.cpp:246
A service for which there are no standard services registered.
Definition Services.h:92
virtual BundlePort * getPort(AppIDPath id, const BundleType *type) const override
Get specialized port for this service to attach to the given appid path.
Definition Services.cpp:186
CustomService(AppIDPath idPath, AcceleratorConnection &, const ServiceImplDetails &details, const HWClientDetails &clients)
Definition Services.cpp:175
A function call which gets attached to a service port.
Definition Services.h:274
std::future< MessageData > call(const MessageData &arg)
Definition Services.cpp:228
static Function * get(AppID id, BundleType *type, WriteChannelPort &arg, ReadChannelPort &result)
Definition Services.cpp:207
Service for calling functions.
Definition Services.h:264
virtual std::string getServiceSymbol() const override
Definition Services.cpp:200
virtual BundlePort * getPort(AppIDPath id, const BundleType *type) const override
Get specialized port for this service to attach to the given appid path.
Definition Services.cpp:202
FuncService(AppIDPath id, AcceleratorConnection &, ServiceImplDetails details, HWClientDetails clients)
Definition Services.cpp:191
virtual std::string getServiceSymbol() const override
Definition Services.cpp:173
static constexpr std::string_view StdName
Definition Services.h:212
virtual std::vector< uint8_t > getCompressedManifest() const override
Return the zlib compressed JSON system manifest.
Definition Services.cpp:153
uint32_t getEsiVersion() const override
Get the ESI version number to check version compatibility.
Definition Services.cpp:146
A "slice" of some parent MMIO space.
Definition Services.h:171
virtual uint64_t read(uint32_t addr) const
Read a 64-bit value from this region, not the global address space.
Definition Services.cpp:132
MMIORegion(AppID id, MMIO *parent, RegionDescriptor desc)
Definition Services.cpp:130
virtual void write(uint32_t addr, uint64_t data)
Write a 64-bit value to this region, not the global address space.
Definition Services.cpp:137
virtual uint64_t read(uint32_t addr) const =0
Read a 64-bit value from the global MMIO space.
MMIO(AcceleratorConnection &, const AppIDPath &idPath, const HWClientDetails &clients)
Definition Services.cpp:56
virtual BundlePort * getPort(AppIDPath id, const BundleType *type) const override
Get a MMIO region port for a particular region descriptor.
Definition Services.cpp:94
std::map< AppIDPath, RegionDescriptor > regions
MMIO base address table.
Definition Services.h:167
static constexpr std::string_view StdName
Definition Services.h:130
virtual Service * getChildService(Service::Type service, AppIDPath id={}, std::string implName={}, ServiceImplDetails details={}, HWClientDetails clients={}) override
If the service is a MMIO service, return a region of the MMIO space which peers into ours.
Definition Services.cpp:118
virtual std::string getServiceSymbol() const override
Definition Services.cpp:91
Add a custom interface to a service client at a particular point in the design hierarchy.
Definition Services.h:47
static Service::Type lookupServiceType(const std::string &)
Resolve a service type from a string.
Definition Services.cpp:423
static Service * createService(AcceleratorConnection *acc, Service::Type svcType, AppIDPath id, std::string implName, ServiceImplDetails details, HWClientDetails clients)
Create a service instance from the given details.
Definition Services.cpp:406
Parent class of all APIs modeled as 'services'.
Definition Services.h:57
AcceleratorConnection & getConnection() const
Definition Services.h:83
const std::type_info & Type
Definition Services.h:59
virtual Service * getChildService(Service::Type service, AppIDPath id={}, std::string implName={}, ServiceImplDetails details={}, HWClientDetails clients={})
Create a "child" service of this service.
Definition Services.cpp:28
AcceleratorConnection & conn
Definition Services.h:86
Information about the Accelerator system.
Definition Services.h:111
virtual std::string getJsonManifest() const
Return the JSON-formatted system manifest.
Definition Services.cpp:40
virtual std::vector< uint8_t > getCompressedManifest() const =0
Return the zlib compressed JSON system manifest.
virtual std::string getServiceSymbol() const override
Definition Services.cpp:35
A telemetry port which gets attached to a service port.
Definition Services.h:386
void connect()
Connect to a particular telemetry port. Offset should be non-nullopt.
Definition Services.cpp:378
std::future< MessageData > read()
Definition Services.cpp:385
Metric(AppID id, const BundleType *type, PortMap channels, const TelemetryService *telemetryService, std::optional< uint64_t > offset)
Definition Services.cpp:370
Service for retrieving telemetry data from the accelerator.
Definition Services.h:369
std::list< TelemetryService * > children
Definition Services.h:422
std::map< AppIDPath, Metric * > getTelemetryPorts()
Definition Services.h:410
MMIO::MMIORegion * mmio
Definition Services.h:419
MMIO::MMIORegion * getMMIORegion() const
Definition Services.cpp:331
std::map< AppIDPath, Metric * > telemetryPorts
Definition Services.h:421
std::map< AppIDPath, uint64_t > portAddressAssignments
Definition Services.h:420
static constexpr std::string_view StdName
Definition Services.h:371
TelemetryService(AppIDPath id, AcceleratorConnection &, ServiceImplDetails details, HWClientDetails clients)
Definition Services.cpp:288
virtual std::string getServiceSymbol() const override
Definition Services.cpp:327
virtual BundlePort * getPort(AppIDPath id, const BundleType *type) const override
Get specialized port for this service to attach to the given appid path.
Definition Services.cpp:350
virtual Service * getChildService(Service::Type service, AppIDPath id={}, std::string implName={}, ServiceImplDetails details={}, HWClientDetails clients={}) override
Create a "child" service of this service.
Definition Services.cpp:361
Definition esi.py:1
std::string toString(const std::any &a)
'Stringify' a std::any. This is used to log std::any values by some loggers.
Definition Logging.cpp:132
constexpr uint64_t MagicNumber
Definition Accelerator.h:48
std::map< std::string, std::any > ServiceImplDetails
Definition Common.h:108
std::string toHex(void *val)
Definition Common.cpp:37
constexpr uint32_t MetadataOffset
Definition Accelerator.h:45
std::map< std::string, ChannelPort & > PortMap
Definition Ports.h:29
std::vector< HWClientDetail > HWClientDetails
Definition Common.h:107
std::any value
Definition Common.h:68
A description of a hardware client.
Definition Common.h:101
Describe a region (slice) of MMIO space.
Definition Services.h:133