Loading [MathJax]/extensions/tex2jax.js
CIRCT 21.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
Accelerator.cpp
Go to the documentation of this file.
1//===- Accelerator.cpp - ESI accelerator system API -----------------------===//
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 (lib/dialect/ESI/runtime/cpp/).
12//
13//===----------------------------------------------------------------------===//
14
15#include "esi/Accelerator.h"
16
17#include <cassert>
18#include <filesystem>
19#include <map>
20#include <stdexcept>
21
22#include <iostream>
23
24#ifdef __linux__
25#include <dlfcn.h>
26#include <linux/limits.h>
27#include <unistd.h>
28#elif _WIN32
29#include <windows.h>
30#endif
31
32using namespace esi;
33using namespace esi::services;
34
35namespace esi {
37 : ctxt(ctxt), serviceThread(nullptr) {}
39
41 if (!serviceThread)
42 serviceThread = std::make_unique<AcceleratorServiceThread>();
43 return serviceThread.get();
44}
45void AcceleratorConnection::createEngine(const std::string &engineTypeName,
46 AppIDPath idPath,
47 const ServiceImplDetails &details,
48 const HWClientDetails &clients) {
49 std::unique_ptr<Engine> engine = ::esi::registry::createEngine(
50 *this, engineTypeName, idPath, details, clients);
51 registerEngine(idPath, std::move(engine), clients);
52}
53
55 std::unique_ptr<Engine> engine,
56 const HWClientDetails &clients) {
57 assert(engine);
58 auto [engineIter, _] = ownedEngines.emplace(idPath, std::move(engine));
59
60 // Engine is now owned by the accelerator connection, so the std::unique_ptr
61 // is no longer valid. Resolve a new one from the map iter.
62 Engine *enginePtr = engineIter->second.get();
63 // Compute our parents idPath path.
64 AppIDPath prefix = std::move(idPath);
65 if (prefix.size() > 0)
66 prefix.pop_back();
67
68 for (const auto &client : clients) {
69 AppIDPath fullClientPath = prefix + client.relPath;
70 for (const auto &channel : client.channelAssignments)
71 clientEngines[fullClientPath].setEngine(channel.first, enginePtr);
72 }
73}
74
76 AppIDPath id,
77 std::string implName,
78 ServiceImplDetails details,
79 HWClientDetails clients) {
80 std::unique_ptr<Service> &cacheEntry = serviceCache[make_tuple(&svcType, id)];
81 if (cacheEntry == nullptr) {
82 Service *svc = createService(svcType, id, implName, details, clients);
83 if (!svc)
84 svc = ServiceRegistry::createService(this, svcType, id, implName, details,
85 clients);
86 if (!svc)
87 return nullptr;
88 cacheEntry = std::unique_ptr<Service>(svc);
89 }
90 return cacheEntry.get();
91}
92
94AcceleratorConnection::takeOwnership(std::unique_ptr<Accelerator> acc) {
96 throw std::runtime_error(
97 "AcceleratorConnection already owns an accelerator");
98 ownedAccelerator = std::move(acc);
99 return ownedAccelerator.get();
100}
101
102/// Get the path to the currently running executable.
103static std::filesystem::path getExePath() {
104#ifdef __linux__
105 char result[PATH_MAX];
106 ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
107 if (count == -1)
108 throw std::runtime_error("Could not get executable path");
109 return std::filesystem::path(std::string(result, count));
110#elif _WIN32
111 char buffer[MAX_PATH];
112 DWORD length = GetModuleFileNameA(NULL, buffer, MAX_PATH);
113 if (length == 0)
114 throw std::runtime_error("Could not get executable path");
115 return std::filesystem::path(std::string(buffer, length));
116#else
117#eror "Unsupported platform"
118#endif
119}
120
121/// Get the path to the currently running shared library.
122static std::filesystem::path getLibPath() {
123#ifdef __linux__
124 Dl_info dl_info;
125 dladdr((void *)getLibPath, &dl_info);
126 return std::filesystem::path(std::string(dl_info.dli_fname));
127#elif _WIN32
128 HMODULE hModule = NULL;
129 if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
130 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
131 reinterpret_cast<LPCSTR>(&getLibPath), &hModule)) {
132 // Handle error
133 return std::filesystem::path();
134 }
135
136 char buffer[MAX_PATH];
137 DWORD length = GetModuleFileNameA(hModule, buffer, MAX_PATH);
138 if (length == 0)
139 throw std::runtime_error("Could not get library path");
140
141 return std::filesystem::path(std::string(buffer, length));
142#else
143#eror "Unsupported platform"
144#endif
145}
146
147/// Load a backend plugin dynamically. Plugins are expected to be named
148/// lib<BackendName>Backend.so and located in one of 1) CWD, 2) in the same
149/// directory as the application, or 3) in the same directory as this library.
150static void loadBackend(Context &ctxt, std::string backend) {
151 Logger &logger = ctxt.getLogger();
152 backend[0] = toupper(backend[0]);
153
154 // Get the file name we are looking for.
155#ifdef __linux__
156 std::string backendFileName = "lib" + backend + "Backend.so";
157#elif _WIN32
158 std::string backendFileName = backend + "Backend.dll";
159#else
160#eror "Unsupported platform"
161#endif
162
163 // Look for library using the C++ std API.
164 // TODO: once the runtime has a logging framework, log the paths we are
165 // trying.
166
167 // First, try the current directory.
168 std::filesystem::path backendPath = backendFileName;
169 std::string backendPathStr;
170 logger.debug("CONNECT",
171 "trying to load backend plugin: " + backendPath.string());
172 if (!std::filesystem::exists(backendPath)) {
173 // Next, try the directory of the executable.
174 backendPath = getExePath().parent_path().append(backendFileName);
175 logger.debug("CONNECT",
176 "trying to load backend plugin: " + backendPath.string());
177 if (!std::filesystem::exists(backendPath)) {
178 // Finally, try the directory of the library.
179 backendPath = getLibPath().parent_path().append(backendFileName);
180 logger.debug("CONNECT",
181 "trying to load backend plugin: " + backendPath.string());
182 if (!std::filesystem::exists(backendPath)) {
183 // If all else fails, just try the name.
184 backendPathStr = backendFileName;
185 logger.debug("CONNECT",
186 "trying to load backend plugin: " + backendPathStr);
187 }
188 }
189 }
190 // If the path was found, convert it to a string.
191 if (backendPathStr.empty())
192 backendPathStr = backendPath.string();
193 else
194 // Otherwise, signal that the path wasn't found by clearing the path and
195 // just use the name. (This is only used on Windows to add the same
196 // directory as the backend DLL to the DLL search path.)
197 backendPath.clear();
198
199 // Attempt to load it.
200#ifdef __linux__
201 void *handle = dlopen(backendPathStr.c_str(), RTLD_NOW | RTLD_GLOBAL);
202 if (!handle) {
203 std::string error(dlerror());
204 logger.error("CONNECT",
205 "while attempting to load backend plugin: " + error);
206 throw std::runtime_error("While attempting to load backend plugin: " +
207 error);
208 }
209#elif _WIN32
210 // Set the DLL directory to the same directory as the backend DLL in case it
211 // has transitive dependencies.
212 if (backendPath != std::filesystem::path()) {
213 std::filesystem::path backendPathParent = backendPath.parent_path();
214 if (SetDllDirectoryA(backendPathParent.string().c_str()) == 0)
215 throw std::runtime_error("While setting DLL directory: " +
216 std::to_string(GetLastError()));
217 }
218
219 // Load the backend plugin.
220 HMODULE handle = LoadLibraryA(backendPathStr.c_str());
221 if (!handle) {
222 DWORD error = GetLastError();
223 if (error == ERROR_MOD_NOT_FOUND) {
224 logger.error("CONNECT", "while attempting to load backend plugin: " +
225 backendPathStr + " not found");
226 throw std::runtime_error("While attempting to load backend plugin: " +
227 backendPathStr + " not found");
228 }
229 logger.error("CONNECT", "while attempting to load backend plugin: " +
230 std::to_string(error));
231 throw std::runtime_error("While attempting to load backend plugin: " +
232 std::to_string(error));
233 }
234#else
235#eror "Unsupported platform"
236#endif
237 logger.info("CONNECT", "loaded backend plugin: " + backendPathStr);
238}
239
240namespace registry {
241namespace internal {
242
244public:
245 static std::map<std::string, BackendCreate> &get() {
246 static BackendRegistry instance;
247 return instance.backendRegistry;
248 }
249
250private:
251 std::map<std::string, BackendCreate> backendRegistry;
252};
253
254void registerBackend(const std::string &name, BackendCreate create) {
255 auto &registry = BackendRegistry::get();
256 if (registry.count(name))
257 throw std::runtime_error("Backend already exists in registry");
258 registry[name] = create;
259}
260} // namespace internal
261
262std::unique_ptr<AcceleratorConnection> connect(Context &ctxt,
263 const std::string &backend,
264 const std::string &connection) {
265 auto &registry = internal::BackendRegistry::get();
266 auto f = registry.find(backend);
267 if (f == registry.end()) {
268 // If it's not already found in the registry, try to load it dynamically.
269 loadBackend(ctxt, backend);
270 f = registry.find(backend);
271 if (f == registry.end()) {
272 ctxt.getLogger().error("CONNECT", "backend '" + backend + "' not found");
273 throw std::runtime_error("Backend '" + backend + "' not found");
274 }
275 }
276 ctxt.getLogger().info("CONNECT", "connecting to backend " + backend +
277 " via '" + connection + "'");
278 return f->second(ctxt, connection);
279}
280
281} // namespace registry
282
284 Impl() {}
285 void start() { me = std::thread(&Impl::loop, this); }
286 void stop() {
287 shutdown = true;
288 me.join();
289 }
290 /// When there's data on any of the listenPorts, call the callback. This
291 /// method can be called from any thread.
292 void
293 addListener(std::initializer_list<ReadChannelPort *> listenPorts,
294 std::function<void(ReadChannelPort *, MessageData)> callback);
295
296 void addTask(std::function<void(void)> task) {
297 std::lock_guard<std::mutex> g(m);
298 taskList.push_back(task);
299 }
300
301private:
302 void loop();
303 volatile bool shutdown = false;
304 std::thread me;
305
306 // Protect the shared data structures.
307 std::mutex m;
308
309 // Map of read ports to callbacks.
310 std::map<ReadChannelPort *,
311 std::pair<std::function<void(ReadChannelPort *, MessageData)>,
312 std::future<MessageData>>>
314
315 /// Tasks which should be called on every loop iteration.
316 std::vector<std::function<void(void)>> taskList;
317};
318
319void AcceleratorServiceThread::Impl::loop() {
320 // These two variables should logically be in the loop, but this avoids
321 // reconstructing them on each iteration.
322 std::vector<std::tuple<ReadChannelPort *,
323 std::function<void(ReadChannelPort *, MessageData)>,
325 portUnlockWorkList;
326 std::vector<std::function<void(void)>> taskListCopy;
327 MessageData data;
328
329 while (!shutdown) {
330 // Ideally we'd have some wake notification here, but this sufficies for
331 // now.
332 // TODO: investigate better ways to do this. For now, just play nice with
333 // the other processes but don't waste time in between polling intervals.
334 std::this_thread::yield();
335
336 // Check and gather data from all the read ports we are monitoring. Put the
337 // callbacks to be called later so we can release the lock.
338 {
339 std::lock_guard<std::mutex> g(m);
340 for (auto &[channel, cbfPair] : listeners) {
341 assert(channel && "Null channel in listener list");
342 std::future<MessageData> &f = cbfPair.second;
343 if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
344 portUnlockWorkList.emplace_back(channel, cbfPair.first, f.get());
345 f = channel->readAsync();
346 }
347 }
348 }
349
350 // Call the callbacks outside the lock.
351 for (auto [channel, cb, data] : portUnlockWorkList)
352 cb(channel, std::move(data));
353
354 // Clear the worklist for the next iteration.
355 portUnlockWorkList.clear();
356
357 // Call any tasks that have been added. Copy it first so we can release the
358 // lock ASAP.
359 {
360 std::lock_guard<std::mutex> g(m);
361 taskListCopy = taskList;
362 }
363 for (auto &task : taskListCopy)
364 task();
365 }
366}
367
368void AcceleratorServiceThread::Impl::addListener(
369 std::initializer_list<ReadChannelPort *> listenPorts,
370 std::function<void(ReadChannelPort *, MessageData)> callback) {
371 std::lock_guard<std::mutex> g(m);
372 for (auto port : listenPorts) {
373 if (listeners.count(port))
374 throw std::runtime_error("Port already has a listener");
375 listeners[port] = std::make_pair(callback, port->readAsync());
376 }
377}
378
379} // namespace esi
380
382 : impl(std::make_unique<Impl>()) {
383 impl->start();
384}
386
388 if (impl) {
389 impl->stop();
390 impl.reset();
391 }
392}
393
394// When there's data on any of the listenPorts, call the callback. This is
395// kinda silly now that we have callback port support, especially given the
396// polling loop. Keep the functionality for now.
398 std::initializer_list<ReadChannelPort *> listenPorts,
399 std::function<void(ReadChannelPort *, MessageData)> callback) {
400 assert(impl && "Service thread not running");
401 impl->addListener(listenPorts, callback);
402}
403
405 assert(impl && "Service thread not running");
406 impl->addTask([&module]() { module.poll(); });
407}
408
410 if (serviceThread) {
411 serviceThread->stop();
412 serviceThread.reset();
413 }
414}
assert(baseType &&"element must be base type")
virtual void disconnect()
Disconnect from the accelerator cleanly.
virtual Service * createService(Service::Type service, AppIDPath idPath, std::string implName, const ServiceImplDetails &details, const HWClientDetails &clients)=0
Called by getServiceImpl exclusively.
ServiceClass * getService(AppIDPath id={}, std::string implName={}, ServiceImplDetails details={}, HWClientDetails clients={})
Get a typed reference to a particular service type.
std::map< AppIDPath, BundleEngineMap > clientEngines
Mapping of clients to their servicing engines.
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...
std::map< ServiceCacheKey, std::unique_ptr< Service > > serviceCache
std::unique_ptr< AcceleratorServiceThread > serviceThread
std::unique_ptr< Accelerator > ownedAccelerator
Accelerator object owned by this connection.
std::map< AppIDPath, std::unique_ptr< Engine > > ownedEngines
Collection of owned engines.
virtual void createEngine(const std::string &engineTypeName, AppIDPath idPath, const ServiceImplDetails &details, const HWClientDetails &clients)
Create a new engine for channel communication with the accelerator.
AcceleratorServiceThread * getServiceThread()
Return a pointer to the accelerator 'service' thread (or threads).
AcceleratorConnection(Context &ctxt)
Accelerator * takeOwnership(std::unique_ptr< Accelerator > accel)
Assume ownership of an accelerator object.
Background thread which services various requests.
void stop()
Instruct the service thread to stop running.
void addListener(std::initializer_list< ReadChannelPort * > listenPorts, std::function< void(ReadChannelPort *, MessageData)> callback)
When there's data on any of the listenPorts, call the callback.
std::unique_ptr< Impl > impl
void addPoll(HWModule &module)
Poll this module.
Top level accelerator class.
Definition Accelerator.h:60
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Definition Context.h:31
Engines implement the actual channel communication between the host and the accelerator.
Definition Engines.h:42
Represents either the top level or an instance of a hardware module.
Definition Design.h:47
virtual void error(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an error.
Definition Logging.h:60
virtual void info(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an informational message.
Definition Logging.h:71
void debug(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a debug message.
Definition Logging.h:79
A logical chunk of data representing serialized data.
Definition Common.h:103
A ChannelPort which reads data from the accelerator.
Definition Ports.h:124
std::map< std::string, BackendCreate > backendRegistry
static std::map< std::string, BackendCreate > & get()
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:269
Parent class of all APIs modeled as 'services'.
Definition Services.h:46
const std::type_info & Type
Definition Services.h:48
void registerBackend(const std::string &name, BackendCreate create)
std::function< std::unique_ptr< AcceleratorConnection >(Context &, std::string)> BackendCreate
Backends can register themselves to be connected via a connection string.
std::unique_ptr< AcceleratorConnection > connect(Context &ctxt, const std::string &backend, const std::string &connection)
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:463
Definition esi.py:1
static std::filesystem::path getExePath()
Get the path to the currently running executable.
std::map< std::string, std::any > ServiceImplDetails
Definition Common.h:98
static void loadBackend(Context &ctxt, std::string backend)
Load a backend plugin dynamically.
static std::filesystem::path getLibPath()
Get the path to the currently running shared library.
std::vector< HWClientDetail > HWClientDetails
Definition Common.h:97
std::map< ReadChannelPort *, std::pair< std::function< void(ReadChannelPort *, MessageData)>, std::future< MessageData > > > listeners
void addTask(std::function< void(void)> task)
void addListener(std::initializer_list< ReadChannelPort * > listenPorts, std::function< void(ReadChannelPort *, MessageData)> callback)
When there's data on any of the listenPorts, call the callback.
std::vector< std::function< void(void)> > taskList
Tasks which should be called on every loop iteration.