Loading [MathJax]/extensions/tex2jax.js
CIRCT 21.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
esiCppAccel.cpp
Go to the documentation of this file.
1//===- esiaccel.cpp - ESI runtime python bindings ---------------*- C++ -*-===//
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// Simply wrap the C++ API into a Python module called 'esiaccel'.
10//
11//===----------------------------------------------------------------------===//
12
13#include "esi/Accelerator.h"
14#include "esi/Services.h"
15
16#include "esi/backends/Cosim.h"
17
18#include <ranges>
19#include <sstream>
20
21// pybind11 includes
22#include <pybind11/pybind11.h>
23namespace py = pybind11;
24
25#include <pybind11/functional.h>
26#include <pybind11/stl.h>
27
28using namespace esi;
29using namespace esi::services;
30
31namespace pybind11 {
32/// Pybind11 needs a little help downcasting with non-bound instances.
33template <>
34struct polymorphic_type_hook<ChannelPort> {
35 static const void *get(const ChannelPort *port, const std::type_info *&type) {
36 if (auto p = dynamic_cast<const WriteChannelPort *>(port)) {
37 type = &typeid(WriteChannelPort);
38 return p;
39 }
40 if (auto p = dynamic_cast<const ReadChannelPort *>(port)) {
41 type = &typeid(ReadChannelPort);
42 return p;
43 }
44 return port;
45 }
46};
47template <>
48struct polymorphic_type_hook<Service> {
49 static const void *get(const Service *svc, const std::type_info *&type) {
50 if (auto p = dynamic_cast<const MMIO *>(svc)) {
51 type = &typeid(MMIO);
52 return p;
53 }
54 if (auto p = dynamic_cast<const SysInfo *>(svc)) {
55 type = &typeid(SysInfo);
56 return p;
57 }
58 if (auto p = dynamic_cast<const HostMem *>(svc)) {
59 type = &typeid(HostMem);
60 return p;
61 }
62 if (auto p = dynamic_cast<const TelemetryService *>(svc)) {
63 type = &typeid(TelemetryService);
64 return p;
65 }
66 return svc;
67 }
68};
69
70namespace detail {
71/// Pybind11 doesn't have a built-in type caster for std::any
72/// (https://github.com/pybind/pybind11/issues/1590). We must provide one which
73/// knows about all of the potential types which the any might be.
74template <>
75struct type_caster<std::any> {
76public:
77 PYBIND11_TYPE_CASTER(std::any, const_name("object"));
78
79 static handle cast(std::any src, return_value_policy /* policy */,
80 handle /* parent */) {
81 const std::type_info &t = src.type();
82 if (t == typeid(std::string))
83 return py::str(std::any_cast<std::string>(src));
84 else if (t == typeid(int64_t))
85 return py::int_(std::any_cast<int64_t>(src));
86 else if (t == typeid(uint64_t))
87 return py::int_(std::any_cast<uint64_t>(src));
88 else if (t == typeid(double))
89 return py::float_(std::any_cast<double>(src));
90 else if (t == typeid(bool))
91 return py::bool_(std::any_cast<bool>(src));
92 else if (t == typeid(std::nullptr_t))
93 return py::none();
94 return py::none();
95 }
96};
97} // namespace detail
98} // namespace pybind11
99
100/// Resolve a Type to the Python wrapper object.
101py::object getPyType(std::optional<const Type *> t) {
102 py::object typesModule = py::module_::import("esiaccel.types");
103 if (!t)
104 return py::none();
105 return typesModule.attr("_get_esi_type")(*t);
106}
107
108// NOLINTNEXTLINE(readability-identifier-naming)
109PYBIND11_MODULE(esiCppAccel, m) {
110 py::class_<Type>(m, "Type")
111 .def_property_readonly("id", &Type::getID)
112 .def("__repr__", [](Type &t) { return "<" + t.getID() + ">"; });
113 py::class_<ChannelType, Type>(m, "ChannelType")
114 .def_property_readonly("inner", &ChannelType::getInner,
115 py::return_value_policy::reference);
116 py::enum_<BundleType::Direction>(m, "Direction")
117 .value("To", BundleType::Direction::To)
118 .value("From", BundleType::Direction::From)
119 .export_values();
120 py::class_<BundleType, Type>(m, "BundleType")
121 .def_property_readonly("channels", &BundleType::getChannels,
122 py::return_value_policy::reference);
123 py::class_<VoidType, Type>(m, "VoidType");
124 py::class_<AnyType, Type>(m, "AnyType");
125 py::class_<BitVectorType, Type>(m, "BitVectorType")
126 .def_property_readonly("width", &BitVectorType::getWidth);
127 py::class_<BitsType, BitVectorType>(m, "BitsType");
128 py::class_<IntegerType, BitVectorType>(m, "IntegerType");
129 py::class_<SIntType, IntegerType>(m, "SIntType");
130 py::class_<UIntType, IntegerType>(m, "UIntType");
131 py::class_<StructType, Type>(m, "StructType")
132 .def_property_readonly("fields", &StructType::getFields,
133 py::return_value_policy::reference);
134 py::class_<ArrayType, Type>(m, "ArrayType")
135 .def_property_readonly("element", &ArrayType::getElementType,
136 py::return_value_policy::reference)
137 .def_property_readonly("size", &ArrayType::getSize);
138
139 py::class_<Constant>(m, "Constant")
140 .def_property_readonly("value", [](Constant &c) { return c.value; })
141 .def_property_readonly(
142 "type", [](Constant &c) { return getPyType(*c.type); },
143 py::return_value_policy::reference);
144
145 py::class_<AppID>(m, "AppID")
146 .def(py::init<std::string, std::optional<uint32_t>>(), py::arg("name"),
147 py::arg("idx") = std::nullopt)
148 .def_property_readonly("name", [](AppID &id) { return id.name; })
149 .def_property_readonly("idx",
150 [](AppID &id) -> py::object {
151 if (id.idx)
152 return py::cast(id.idx);
153 return py::none();
154 })
155 .def("__repr__",
156 [](AppID &id) {
157 std::string ret = "<" + id.name;
158 if (id.idx)
159 ret = ret + "[" + std::to_string(*id.idx) + "]";
160 ret = ret + ">";
161 return ret;
162 })
163 .def("__eq__", [](AppID &a, AppID &b) { return a == b; })
164 .def("__hash__", [](AppID &id) {
165 return utils::hash_combine(std::hash<std::string>{}(id.name),
166 std::hash<uint32_t>{}(id.idx.value_or(-1)));
167 });
168 py::class_<AppIDPath>(m, "AppIDPath").def("__repr__", &AppIDPath::toStr);
169
170 py::class_<ModuleInfo>(m, "ModuleInfo")
171 .def_property_readonly("name", [](ModuleInfo &info) { return info.name; })
172 .def_property_readonly("summary",
173 [](ModuleInfo &info) { return info.summary; })
174 .def_property_readonly("version",
175 [](ModuleInfo &info) { return info.version; })
176 .def_property_readonly("repo", [](ModuleInfo &info) { return info.repo; })
177 .def_property_readonly("commit_hash",
178 [](ModuleInfo &info) { return info.commitHash; })
179 .def_property_readonly("constants",
180 [](ModuleInfo &info) { return info.constants; })
181 // TODO: "extra" field.
182 .def("__repr__", [](ModuleInfo &info) {
183 std::string ret;
184 std::stringstream os(ret);
185 os << info;
186 return os.str();
187 });
188
189 py::enum_<Logger::Level>(m, "LogLevel")
190 .value("Debug", Logger::Level::Debug)
191 .value("Info", Logger::Level::Info)
192 .value("Warning", Logger::Level::Warning)
193 .value("Error", Logger::Level::Error)
194 .export_values();
195 py::class_<Logger>(m, "Logger");
196
197 py::class_<services::Service>(m, "Service");
198
199 py::class_<SysInfo, services::Service>(m, "SysInfo")
200 .def("esi_version", &SysInfo::getEsiVersion)
201 .def("json_manifest", &SysInfo::getJsonManifest);
202
203 py::class_<MMIO::RegionDescriptor>(m, "MMIORegionDescriptor")
204 .def_property_readonly("base",
205 [](MMIO::RegionDescriptor &r) { return r.base; })
206 .def_property_readonly("size",
207 [](MMIO::RegionDescriptor &r) { return r.size; });
208 py::class_<services::MMIO, services::Service>(m, "MMIO")
209 .def("read", &services::MMIO::read)
210 .def("write", &services::MMIO::write)
211 .def_property_readonly("regions", &services::MMIO::getRegions,
212 py::return_value_policy::reference);
213
214 py::class_<services::HostMem::HostMemRegion>(m, "HostMemRegion")
215 .def_property_readonly("ptr",
217 return reinterpret_cast<uintptr_t>(mem.getPtr());
218 })
219 .def_property_readonly("size",
221
222 py::class_<services::HostMem::Options>(m, "HostMemOptions")
223 .def(py::init<>())
224 .def_readwrite("writeable", &services::HostMem::Options::writeable)
225 .def_readwrite("use_large_pages",
227 .def("__repr__", [](services::HostMem::Options &opts) {
228 std::string ret = "HostMemOptions(";
229 if (opts.writeable)
230 ret += "writeable ";
231 if (opts.useLargePages)
232 ret += "use_large_pages";
233 ret += ")";
234 return ret;
235 });
236
237 py::class_<services::HostMem, services::Service>(m, "HostMem")
238 .def("allocate", &services::HostMem::allocate, py::arg("size"),
239 py::arg("options") = services::HostMem::Options(),
240 py::return_value_policy::take_ownership)
241 .def(
242 "map_memory",
243 [](HostMem &self, uintptr_t ptr, size_t size, HostMem::Options opts) {
244 return self.mapMemory(reinterpret_cast<void *>(ptr), size, opts);
245 },
246 py::arg("ptr"), py::arg("size"),
247 py::arg("options") = services::HostMem::Options())
248 .def(
249 "unmap_memory",
250 [](HostMem &self, uintptr_t ptr) {
251 return self.unmapMemory(reinterpret_cast<void *>(ptr));
252 },
253 py::arg("ptr"));
254
255 // py::class_<std::__basic_future<MessageData>>(m, "MessageDataFuture");
256 py::class_<std::future<MessageData>>(m, "MessageDataFuture")
257 .def("valid",
258 [](std::future<MessageData> &f) {
259 // For some reason, if we just pass the function pointer, pybind11
260 // sees `std::__basic_future` as the type and pybind11_stubgen
261 // emits an error.
262 return f.valid();
263 })
264 .def("wait", &std::future<MessageData>::wait)
265 .def("get", [](std::future<MessageData> &f) {
266 MessageData data = f.get();
267 return py::bytearray((const char *)data.getBytes(), data.getSize());
268 });
269
270 py::class_<ChannelPort>(m, "ChannelPort")
271 .def("connect", &ChannelPort::connect,
272 py::arg("buffer_size") = std::nullopt)
273 .def("disconnect", &ChannelPort::disconnect)
274 .def_property_readonly("type", &ChannelPort::getType,
275 py::return_value_policy::reference);
276
277 py::class_<WriteChannelPort, ChannelPort>(m, "WriteChannelPort")
278 .def("write",
279 [](WriteChannelPort &p, py::bytearray &data) {
280 py::buffer_info info(py::buffer(data).request());
281 std::vector<uint8_t> dataVec((uint8_t *)info.ptr,
282 (uint8_t *)info.ptr + info.size);
283 p.write(dataVec);
284 })
285 .def("tryWrite", [](WriteChannelPort &p, py::bytearray &data) {
286 py::buffer_info info(py::buffer(data).request());
287 std::vector<uint8_t> dataVec((uint8_t *)info.ptr,
288 (uint8_t *)info.ptr + info.size);
289 return p.tryWrite(dataVec);
290 });
291 py::class_<ReadChannelPort, ChannelPort>(m, "ReadChannelPort")
292 .def(
293 "read",
294 [](ReadChannelPort &p) -> py::bytearray {
295 MessageData data;
296 p.read(data);
297 return py::bytearray((const char *)data.getBytes(), data.getSize());
298 },
299 "Read data from the channel. Blocking.")
300 .def("read_async", &ReadChannelPort::readAsync);
301
302 py::class_<BundlePort>(m, "BundlePort")
303 .def_property_readonly("id", &BundlePort::getID)
304 .def_property_readonly("channels", &BundlePort::getChannels,
305 py::return_value_policy::reference)
306 .def("getWrite", &BundlePort::getRawWrite,
307 py::return_value_policy::reference)
308 .def("getRead", &BundlePort::getRawRead,
309 py::return_value_policy::reference);
310
311 py::class_<ServicePort, BundlePort>(m, "ServicePort");
312
313 py::class_<MMIO::MMIORegion, ServicePort>(m, "MMIORegion")
314 .def_property_readonly("descriptor", &MMIO::MMIORegion::getDescriptor)
315 .def("read", &MMIO::MMIORegion::read)
316 .def("write", &MMIO::MMIORegion::write);
317
318 py::class_<FuncService::Function, ServicePort>(m, "Function")
319 .def(
320 "call",
321 [](FuncService::Function &self,
322 py::bytearray msg) -> std::future<MessageData> {
323 py::buffer_info info(py::buffer(msg).request());
324 std::vector<uint8_t> dataVec((uint8_t *)info.ptr,
325 (uint8_t *)info.ptr + info.size);
326 MessageData data(dataVec);
327 return self.call(data);
328 },
329 py::return_value_policy::take_ownership)
330 .def("connect", &FuncService::Function::connect);
331
332 py::class_<CallService::Callback, ServicePort>(m, "Callback")
333 .def("connect", [](CallService::Callback &self,
334 std::function<py::object(py::object)> pyCallback) {
335 // TODO: Under certain conditions this will cause python to crash. I
336 // don't remember how to replicate these crashes, but IIRC they are
337 // deterministic.
338 self.connect([pyCallback](const MessageData &req) -> MessageData {
339 py::gil_scoped_acquire acquire{};
340 std::vector<uint8_t> arg(req.getBytes(),
341 req.getBytes() + req.getSize());
342 py::bytearray argObj((const char *)arg.data(), arg.size());
343 auto ret = pyCallback(argObj);
344 if (ret.is_none())
345 return MessageData();
346 py::buffer_info info(py::buffer(ret).request());
347 std::vector<uint8_t> dataVec((uint8_t *)info.ptr,
348 (uint8_t *)info.ptr + info.size);
349 return MessageData(dataVec);
350 });
351 });
352
353 py::class_<TelemetryService::Telemetry, ServicePort>(m, "Telemetry")
356
357 // Store this variable (not commonly done) as the "children" method needs for
358 // "Instance" to be defined first.
359 auto hwmodule =
360 py::class_<HWModule>(m, "HWModule")
361 .def_property_readonly("info", &HWModule::getInfo)
362 .def_property_readonly("ports", &HWModule::getPorts,
363 py::return_value_policy::reference)
364 .def_property_readonly("services", &HWModule::getServices,
365 py::return_value_policy::reference);
366
367 // In order to inherit methods from "HWModule", it needs to be defined first.
368 py::class_<Instance, HWModule>(m, "Instance")
369 .def_property_readonly("id", &Instance::getID);
370
371 py::class_<Accelerator, HWModule>(m, "Accelerator");
372
373 // Since this returns a vector of Instance*, we need to define Instance first
374 // or else pybind11-stubgen complains.
375 hwmodule.def_property_readonly("children", &HWModule::getChildren,
376 py::return_value_policy::reference);
377
378 auto accConn = py::class_<AcceleratorConnection>(m, "AcceleratorConnection");
379
380 py::class_<Context>(m, "Context")
381 .def(py::init<>())
382 .def("connect", &Context::connect)
383 .def("set_stdio_logger", [](Context &ctxt, Logger::Level level) {
384 ctxt.setLogger(std::make_unique<StreamLogger>(level));
385 });
386
387 accConn.def(py::init(&registry::connect))
388 .def(
389 "sysinfo",
390 [](AcceleratorConnection &acc) {
391 return acc.getService<services::SysInfo>({});
392 },
393 py::return_value_policy::reference)
394 .def(
395 "get_service_mmio",
396 [](AcceleratorConnection &acc) {
397 return acc.getService<services::MMIO>({});
398 },
399 py::return_value_policy::reference)
400 .def(
401 "get_service_hostmem",
402 [](AcceleratorConnection &acc) {
403 return acc.getService<services::HostMem>({});
404 },
405 py::return_value_policy::reference);
406
407 py::class_<Manifest>(m, "Manifest")
408 .def(py::init<Context &, std::string>())
409 .def_property_readonly("api_version", &Manifest::getApiVersion)
410 .def(
411 "build_accelerator",
412 [&](Manifest &m, AcceleratorConnection &conn) {
413 auto acc = m.buildAccelerator(conn);
414 conn.getServiceThread()->addPoll(*acc);
415 return acc;
416 },
417 py::return_value_policy::reference)
418 .def_property_readonly("type_table",
419 [](Manifest &m) {
420 std::vector<py::object> ret;
421 std::ranges::transform(m.getTypeTable(),
422 std::back_inserter(ret),
423 getPyType);
424 return ret;
425 })
426 .def_property_readonly("module_infos", &Manifest::getModuleInfos);
427}
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.
AcceleratorServiceThread * getServiceThread()
Return a pointer to the accelerator 'service' thread (or threads).
std::string toStr() const
Definition Manifest.cpp:733
uint64_t getWidth() const
Definition Types.h:103
Unidirectional channels are the basic communication primitive between the host and accelerator.
Definition Ports.h:36
const Type * getType() const
Definition Ports.h:62
virtual void disconnect()=0
virtual void connect(std::optional< unsigned > bufferSize=std::nullopt)=0
Set up a connection to the accelerator.
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Definition Context.h:31
std::unique_ptr< AcceleratorConnection > connect(std::string backend, std::string connection)
Connect to an accelerator backend.
Definition Context.cpp:27
const std::map< AppID, BundlePort & > & getPorts() const
Access the module's ports by ID.
Definition Design.h:76
const std::map< AppID, Instance * > & getChildren() const
Access the module's children by ID.
Definition Design.h:67
const std::vector< services::Service * > & getServices() const
Access the services provided by this module.
Definition Design.h:78
std::optional< ModuleInfo > getInfo() const
Access the module's metadata, if any.
Definition Design.h:58
const AppID getID() const
Get the instance's ID, which it will always have.
Definition Design.h:119
Class to parse a manifest.
Definition Manifest.h:39
A logical chunk of data representing serialized data.
Definition Common.h:103
const uint8_t * getBytes() const
Definition Common.h:111
size_t getSize() const
Get the size of the data in bytes.
Definition Common.h:113
A ChannelPort which reads data from the accelerator.
Definition Ports.h:124
virtual std::future< MessageData > readAsync()
Asynchronous read.
Definition Ports.cpp:77
Root class of the ESI type system.
Definition Types.h:27
ID getID() const
Definition Types.h:33
A ChannelPort which sends data to the accelerator.
Definition Ports.h:77
virtual void write(const MessageData &)=0
A very basic blocking write API.
virtual bool tryWrite(const MessageData &data)=0
A basic non-blocking write API.
A function call which gets attached to a service port.
Definition Services.h:304
A function call which gets attached to a service port.
Definition Services.h:262
virtual std::unique_ptr< HostMemRegion > allocate(std::size_t size, Options opts) const =0
Allocate a region of host memory in accelerator accessible address space.
virtual void unmapMemory(void *ptr) const
Unmap memory which was previously mapped with 'mapMemory'.
Definition Services.h:248
virtual bool mapMemory(void *ptr, std::size_t size, Options opts) const
Try to make a region of host memory accessible to the accelerator.
Definition Services.h:243
virtual uint64_t read(uint32_t addr) const
Read a 64-bit value from this region, not the global address space.
Definition Services.cpp:119
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:124
virtual RegionDescriptor getDescriptor() const
Get the offset (and size) of the region in the parent (usually global) MMIO address space.
Definition Services.h:166
virtual uint64_t read(uint32_t addr) const =0
Read a 64-bit value from the global MMIO space.
virtual void write(uint32_t addr, uint64_t data)=0
Write a 64-bit value to the global MMIO space.
const std::map< AppIDPath, RegionDescriptor > & getRegions() const
Get the regions of MMIO space that this service manages.
Definition Services.h:136
Parent class of all APIs modeled as 'services'.
Definition Services.h:46
Information about the Accelerator system.
Definition Services.h:100
virtual std::string getJsonManifest() const
Return the JSON-formatted system manifest.
Definition Services.cpp:40
virtual uint32_t getEsiVersion() const =0
Get the ESI version number to check version compatibility.
std::future< MessageData > read()
Definition Services.cpp:313
void connect()
Connect to a particular telemetry port.
Definition Services.cpp:299
Service for retrieving telemetry data from the accelerator.
Definition Services.h:341
PYBIND11_MODULE(esiCppAccel, m)
py::object getPyType(std::optional< const Type * > t)
Resolve a Type to the Python wrapper object.
std::unique_ptr< AcceleratorConnection > connect(Context &ctxt, const std::string &backend, const std::string &connection)
size_t hash_combine(size_t h1, size_t h2)
C++'s stdlib doesn't have a hash_combine function. This is a simple one.
Definition Utils.h:32
Definition esi.py:1
std::any value
Definition Common.h:58
std::optional< const Type * > type
Definition Common.h:59
RAII memory region for host memory.
Definition Services.h:208
virtual void * getPtr() const =0
Get a pointer to the host memory.
virtual std::size_t getSize() const =0
Options for allocating host memory.
Definition Services.h:226
Describe a region (slice) of MMIO space.
Definition Services.h:122
static handle cast(std::any src, return_value_policy, handle)
PYBIND11_TYPE_CASTER(std::any, const_name("object"))
static const void * get(const ChannelPort *port, const std::type_info *&type)
static const void * get(const Service *svc, const std::type_info *&type)