26#include <linux/limits.h>
37 : ctxt(ctxt), serviceThread(nullptr) {}
50 *
this, engineTypeName, idPath, details, clients);
55 std::unique_ptr<Engine> engine,
58 auto [engineIter, _] =
ownedEngines.emplace(idPath, std::move(engine));
62 Engine *enginePtr = engineIter->second.get();
65 if (prefix.size() > 0)
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);
80 std::unique_ptr<Service> &cacheEntry =
serviceCache[make_tuple(&svcType,
id)];
81 if (cacheEntry ==
nullptr) {
88 cacheEntry = std::unique_ptr<Service>(svc);
90 return cacheEntry.get();
96 throw std::runtime_error(
97 "AcceleratorConnection already owns an accelerator");
105 char result[PATH_MAX];
106 ssize_t count = readlink(
"/proc/self/exe", result, PATH_MAX);
108 throw std::runtime_error(
"Could not get executable path");
109 return std::filesystem::path(std::string(result, count));
111 char buffer[MAX_PATH];
112 DWORD length = GetModuleFileNameA(NULL, buffer, MAX_PATH);
114 throw std::runtime_error(
"Could not get executable path");
115 return std::filesystem::path(std::string(buffer, length));
117#eror "Unsupported platform"
126 return std::filesystem::path(std::string(dl_info.dli_fname));
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)) {
133 return std::filesystem::path();
136 char buffer[MAX_PATH];
137 DWORD length = GetModuleFileNameA(hModule, buffer, MAX_PATH);
139 throw std::runtime_error(
"Could not get library path");
141 return std::filesystem::path(std::string(buffer, length));
143#eror "Unsupported platform"
151 Logger &logger = ctxt.getLogger();
152 backend[0] = toupper(backend[0]);
156 std::string backendFileName =
"lib" + backend +
"Backend.so";
158 std::string backendFileName = backend +
"Backend.dll";
160#eror "Unsupported platform"
166 std::filesystem::path backendPath = backendFileName;
167 std::string backendPathStr;
168 logger.
debug(
"CONNECT",
169 "trying to find backend plugin: " + backendPath.string());
170 if (!std::filesystem::exists(backendPath)) {
172 backendPath =
getExePath().parent_path().append(backendFileName);
173 logger.
debug(
"CONNECT",
174 "trying to find backend plugin: " + backendPath.string());
175 if (!std::filesystem::exists(backendPath)) {
177 backendPath =
getLibPath().parent_path().append(backendFileName);
178 logger.
debug(
"CONNECT",
179 "trying to find backend plugin: " + backendPath.string());
180 if (!std::filesystem::exists(backendPath)) {
182 backendPathStr = backendFileName;
183 logger.
debug(
"CONNECT",
184 "trying to find backend plugin: " + backendPathStr);
189 if (backendPathStr.empty()) {
190 backendPath = std::filesystem::absolute(backendPath);
191 logger.
debug(
"CONNECT",
"found backend plugin: " + backendPath.string());
192 backendPathStr = backendPath.string();
202 void *handle = dlopen(backendPathStr.c_str(), RTLD_NOW | RTLD_GLOBAL);
204 std::string error(dlerror());
205 logger.
error(
"CONNECT",
206 "while attempting to load backend plugin: " + error);
207 throw std::runtime_error(
"While attempting to load backend plugin: " +
213 if (backendPath != std::filesystem::path()) {
214 std::filesystem::path backendPathParent = backendPath.parent_path();
219 if (backendPathParent.empty())
220 backendPathParent = std::filesystem::current_path();
221 logger.
debug(
"CONNECT",
"setting DLL search directory to: " +
222 backendPathParent.string());
223 if (SetDllDirectoryA(backendPathParent.string().c_str()) == 0)
224 throw std::runtime_error(
"While setting DLL directory: " +
225 std::to_string(GetLastError()));
229 HMODULE handle = LoadLibraryA(backendPathStr.c_str());
231 DWORD error = GetLastError();
233 LPSTR messageBuffer =
nullptr;
234 size_t size = FormatMessageA(
235 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
236 FORMAT_MESSAGE_IGNORE_INSERTS,
237 nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
238 (LPSTR)&messageBuffer, 0,
nullptr);
240 std::string errorMessage;
241 if (size > 0 && messageBuffer !=
nullptr) {
242 errorMessage = std::string(messageBuffer, size);
243 LocalFree(messageBuffer);
245 errorMessage =
"Unknown error";
248 std::string fullError =
"While attempting to load backend plugin '" +
249 backendPathStr +
"': " + errorMessage +
250 " (error code: " + std::to_string(error) +
")";
252 logger.
error(
"CONNECT", fullError);
253 throw std::runtime_error(fullError);
256#eror "Unsupported platform"
258 logger.
info(
"CONNECT",
"loaded backend plugin: " + backendPathStr);
266 static std::map<std::string, BackendCreate> &
get() {
277 if (registry.count(name))
278 throw std::runtime_error(
"Backend already exists in registry");
279 registry[name] = create;
284 const std::string &backend,
285 const std::string &connection) {
287 auto f = registry.find(backend);
288 if (f == registry.end()) {
291 f = registry.find(backend);
292 if (f == registry.end()) {
294 details[
"backend"] = backend;
295 std::ostringstream loaded_backends;
297 for (
const auto &b : registry) {
299 loaded_backends <<
", ";
300 loaded_backends << b.first;
303 details[
"loaded_backends"] = loaded_backends.str();
304 ctxt.getLogger().error(
"CONNECT",
"backend '" + backend +
"' not found",
306 throw std::runtime_error(
"Backend '" + backend +
"' not found");
309 ctxt.getLogger().info(
"CONNECT",
"connecting to backend " + backend +
310 " via '" + connection +
"'");
311 return f->second(ctxt, connection);
318 void start() {
me = std::thread(&Impl::loop,
this); }
326 addListener(std::initializer_list<ReadChannelPort *> listenPorts,
329 void addTask(std::function<
void(
void)> task) {
330 std::lock_guard<std::mutex> g(
m);
345 std::future<MessageData>>>
352void AcceleratorServiceThread::Impl::loop() {
359 std::vector<std::function<void(
void)>> taskListCopy;
367 std::this_thread::yield();
372 std::lock_guard<std::mutex> g(
m);
373 for (
auto &[channel, cbfPair] :
listeners) {
374 assert(channel &&
"Null channel in listener list");
375 std::future<MessageData> &f = cbfPair.second;
376 if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
377 portUnlockWorkList.emplace_back(channel, cbfPair.first, f.get());
378 f = channel->readAsync();
384 for (
auto [channel, cb, data] : portUnlockWorkList)
385 cb(channel, std::move(data));
388 portUnlockWorkList.clear();
393 std::lock_guard<std::mutex> g(
m);
396 for (
auto &task : taskListCopy)
401void AcceleratorServiceThread::Impl::addListener(
402 std::initializer_list<ReadChannelPort *> listenPorts,
404 std::lock_guard<std::mutex> g(m);
405 for (
auto port : listenPorts) {
406 if (listeners.count(port))
407 throw std::runtime_error(
"Port already has a listener");
408 listeners[port] = std::make_pair(callback, port->readAsync());
415 : impl(std::make_unique<
Impl>()) {
431 std::initializer_list<ReadChannelPort *> listenPorts,
434 impl->addListener(listenPorts, callback);
439 impl->addTask([&module]() {
module.poll(); });
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.
virtual ~AcceleratorConnection()
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.
AcceleratorServiceThread()
std::unique_ptr< Impl > impl
void addPoll(HWModule &module)
Poll this module.
~AcceleratorServiceThread()
Top level accelerator class.
AcceleratorConnections, Accelerators, and Manifests must all share a context.
Engines implement the actual channel communication between the host and the accelerator.
Represents either the top level or an instance of a hardware module.
virtual void error(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an error.
virtual void info(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report an informational message.
void debug(const std::string &subsystem, const std::string &msg, const std::map< std::string, std::any > *details=nullptr)
Report a debug message.
A logical chunk of data representing serialized data.
A ChannelPort which reads data from the accelerator.
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.
Parent class of all APIs modeled as 'services'.
const std::type_info & Type
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.
static std::filesystem::path getExePath()
Get the path to the currently running executable.
std::map< std::string, std::any > ServiceImplDetails
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
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.