CIRCT 21.0.0git
Loading...
Searching...
No Matches
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) {
95 Accelerator *ret = acc.get();
96 ownedAccelerators.push_back(std::move(acc));
97 return ret;
98}
99
100/// Get the path to the currently running executable.
101static std::filesystem::path getExePath() {
102#ifdef __linux__
103 char result[PATH_MAX];
104 ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
105 if (count == -1)
106 throw std::runtime_error("Could not get executable path");
107 return std::filesystem::path(std::string(result, count));
108#elif _WIN32
109 char buffer[MAX_PATH];
110 DWORD length = GetModuleFileNameA(NULL, buffer, MAX_PATH);
111 if (length == 0)
112 throw std::runtime_error("Could not get executable path");
113 return std::filesystem::path(std::string(buffer, length));
114#else
115#eror "Unsupported platform"
116#endif
117}
118
119/// Get the path to the currently running shared library.
120static std::filesystem::path getLibPath() {
121#ifdef __linux__
122 Dl_info dl_info;
123 dladdr((void *)getLibPath, &dl_info);
124 return std::filesystem::path(std::string(dl_info.dli_fname));
125#elif _WIN32
126 HMODULE hModule = NULL;
127 if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
128 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
129 reinterpret_cast<LPCSTR>(&getLibPath), &hModule)) {
130 // Handle error
131 return std::filesystem::path();
132 }
133
134 char buffer[MAX_PATH];
135 DWORD length = GetModuleFileNameA(hModule, buffer, MAX_PATH);
136 if (length == 0)
137 throw std::runtime_error("Could not get library path");
138
139 return std::filesystem::path(std::string(buffer, length));
140#else
141#eror "Unsupported platform"
142#endif
143}
144
145/// Load a backend plugin dynamically. Plugins are expected to be named
146/// lib<BackendName>Backend.so and located in one of 1) CWD, 2) in the same
147/// directory as the application, or 3) in the same directory as this library.
148static void loadBackend(Context &ctxt, std::string backend) {
149 Logger &logger = ctxt.getLogger();
150 backend[0] = toupper(backend[0]);
151
152 // Get the file name we are looking for.
153#ifdef __linux__
154 std::string backendFileName = "lib" + backend + "Backend.so";
155#elif _WIN32
156 std::string backendFileName = backend + "Backend.dll";
157#else
158#eror "Unsupported platform"
159#endif
160
161 // Look for library using the C++ std API.
162 // TODO: once the runtime has a logging framework, log the paths we are
163 // trying.
164
165 // First, try the current directory.
166 std::filesystem::path backendPath = backendFileName;
167 std::string backendPathStr;
168 logger.debug("CONNECT",
169 "trying to load backend plugin: " + backendPath.string());
170 if (!std::filesystem::exists(backendPath)) {
171 // Next, try the directory of the executable.
172 backendPath = getExePath().parent_path().append(backendFileName);
173 logger.debug("CONNECT",
174 "trying to load backend plugin: " + backendPath.string());
175 if (!std::filesystem::exists(backendPath)) {
176 // Finally, try the directory of the library.
177 backendPath = getLibPath().parent_path().append(backendFileName);
178 logger.debug("CONNECT",
179 "trying to load backend plugin: " + backendPath.string());
180 if (!std::filesystem::exists(backendPath)) {
181 // If all else fails, just try the name.
182 backendPathStr = backendFileName;
183 logger.debug("CONNECT",
184 "trying to load backend plugin: " + backendPathStr);
185 }
186 }
187 }
188 // If the path was found, convert it to a string.
189 if (backendPathStr.empty())
190 backendPathStr = backendPath.string();
191 else
192 // Otherwise, signal that the path wasn't found by clearing the path and
193 // just use the name. (This is only used on Windows to add the same
194 // directory as the backend DLL to the DLL search path.)
195 backendPath.clear();
196
197 // Attempt to load it.
198#ifdef __linux__
199 void *handle = dlopen(backendPathStr.c_str(), RTLD_NOW | RTLD_GLOBAL);
200 if (!handle) {
201 std::string error(dlerror());
202 logger.error("CONNECT",
203 "while attempting to load backend plugin: " + error);
204 throw std::runtime_error("While attempting to load backend plugin: " +
205 error);
206 }
207#elif _WIN32
208 // Set the DLL directory to the same directory as the backend DLL in case it
209 // has transitive dependencies.
210 if (backendPath != std::filesystem::path()) {
211 std::filesystem::path backendPathParent = backendPath.parent_path();
212 if (SetDllDirectoryA(backendPathParent.string().c_str()) == 0)
213 throw std::runtime_error("While setting DLL directory: " +
214 std::to_string(GetLastError()));
215 }
216
217 // Load the backend plugin.
218 HMODULE handle = LoadLibraryA(backendPathStr.c_str());
219 if (!handle) {
220 DWORD error = GetLastError();
221 if (error == ERROR_MOD_NOT_FOUND) {
222 logger.error("CONNECT", "while attempting to load backend plugin: " +
223 backendPathStr + " not found");
224 throw std::runtime_error("While attempting to load backend plugin: " +
225 backendPathStr + " not found");
226 }
227 logger.error("CONNECT", "while attempting to load backend plugin: " +
228 std::to_string(error));
229 throw std::runtime_error("While attempting to load backend plugin: " +
230 std::to_string(error));
231 }
232#else
233#eror "Unsupported platform"
234#endif
235 logger.info("CONNECT", "loaded backend plugin: " + backendPathStr);
236}
237
238namespace registry {
239namespace internal {
240
242public:
243 static std::map<std::string, BackendCreate> &get() {
244 static BackendRegistry instance;
245 return instance.backendRegistry;
246 }
247
248private:
249 std::map<std::string, BackendCreate> backendRegistry;
250};
251
252void registerBackend(const std::string &name, BackendCreate create) {
253 auto &registry = BackendRegistry::get();
254 if (registry.count(name))
255 throw std::runtime_error("Backend already exists in registry");
256 registry[name] = create;
257}
258} // namespace internal
259
260std::unique_ptr<AcceleratorConnection> connect(Context &ctxt,
261 const std::string &backend,
262 const std::string &connection) {
263 auto &registry = internal::BackendRegistry::get();
264 auto f = registry.find(backend);
265 if (f == registry.end()) {
266 // If it's not already found in the registry, try to load it dynamically.
267 loadBackend(ctxt, backend);
268 f = registry.find(backend);
269 if (f == registry.end()) {
270 ctxt.getLogger().error("CONNECT", "backend '" + backend + "' not found");
271 throw std::runtime_error("Backend '" + backend + "' not found");
272 }
273 }
274 ctxt.getLogger().info("CONNECT", "connecting to backend " + backend +
275 " via '" + connection + "'");
276 return f->second(ctxt, connection);
277}
278
279} // namespace registry
280
282 Impl() {}
283 void start() { me = std::thread(&Impl::loop, this); }
284 void stop() {
285 shutdown = true;
286 me.join();
287 }
288 /// When there's data on any of the listenPorts, call the callback. This
289 /// method can be called from any thread.
290 void
291 addListener(std::initializer_list<ReadChannelPort *> listenPorts,
292 std::function<void(ReadChannelPort *, MessageData)> callback);
293
294 void addTask(std::function<void(void)> task) {
295 std::lock_guard<std::mutex> g(m);
296 taskList.push_back(task);
297 }
298
299private:
300 void loop();
301 volatile bool shutdown = false;
302 std::thread me;
303
304 // Protect the shared data structures.
305 std::mutex m;
306
307 // Map of read ports to callbacks.
308 std::map<ReadChannelPort *,
309 std::pair<std::function<void(ReadChannelPort *, MessageData)>,
310 std::future<MessageData>>>
312
313 /// Tasks which should be called on every loop iteration.
314 std::vector<std::function<void(void)>> taskList;
315};
316
317void AcceleratorServiceThread::Impl::loop() {
318 // These two variables should logically be in the loop, but this avoids
319 // reconstructing them on each iteration.
320 std::vector<std::tuple<ReadChannelPort *,
321 std::function<void(ReadChannelPort *, MessageData)>,
323 portUnlockWorkList;
324 std::vector<std::function<void(void)>> taskListCopy;
325 MessageData data;
326
327 while (!shutdown) {
328 // Ideally we'd have some wake notification here, but this sufficies for
329 // now.
330 // TODO: investigate better ways to do this.
331 std::this_thread::sleep_for(std::chrono::microseconds(100));
332
333 // Check and gather data from all the read ports we are monitoring. Put the
334 // callbacks to be called later so we can release the lock.
335 {
336 std::lock_guard<std::mutex> g(m);
337 for (auto &[channel, cbfPair] : listeners) {
338 assert(channel && "Null channel in listener list");
339 std::future<MessageData> &f = cbfPair.second;
340 if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
341 portUnlockWorkList.emplace_back(channel, cbfPair.first, f.get());
342 f = channel->readAsync();
343 }
344 }
345 }
346
347 // Call the callbacks outside the lock.
348 for (auto [channel, cb, data] : portUnlockWorkList)
349 cb(channel, std::move(data));
350
351 // Clear the worklist for the next iteration.
352 portUnlockWorkList.clear();
353
354 // Call any tasks that have been added. Copy it first so we can release the
355 // lock ASAP.
356 {
357 std::lock_guard<std::mutex> g(m);
358 taskListCopy = taskList;
359 }
360 for (auto &task : taskListCopy)
361 task();
362 }
363}
364
365void AcceleratorServiceThread::Impl::addListener(
366 std::initializer_list<ReadChannelPort *> listenPorts,
367 std::function<void(ReadChannelPort *, MessageData)> callback) {
368 std::lock_guard<std::mutex> g(m);
369 for (auto port : listenPorts) {
370 if (listeners.count(port))
371 throw std::runtime_error("Port already has a listener");
372 listeners[port] = std::make_pair(callback, port->readAsync());
373 }
374}
375
376} // namespace esi
377
379 : impl(std::make_unique<Impl>()) {
380 impl->start();
381}
383
385 if (impl) {
386 impl->stop();
387 impl.reset();
388 }
389}
390
391// When there's data on any of the listenPorts, call the callback. This is
392// kinda silly now that we have callback port support, especially given the
393// polling loop. Keep the functionality for now.
395 std::initializer_list<ReadChannelPort *> listenPorts,
396 std::function<void(ReadChannelPort *, MessageData)> callback) {
397 assert(impl && "Service thread not running");
398 impl->addListener(listenPorts, callback);
399}
400
402 assert(impl && "Service thread not running");
403 impl->addTask([&module]() { module.poll(); });
404}
405
407 if (serviceThread) {
408 serviceThread->stop();
409 serviceThread.reset();
410 }
411}
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::vector< std::unique_ptr< Accelerator > > ownedAccelerators
List of accelerator objects 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:41
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:100
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.