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();
103 char result[PATH_MAX];
104 ssize_t count = readlink(
"/proc/self/exe", result, PATH_MAX);
106 throw std::runtime_error(
"Could not get executable path");
107 return std::filesystem::path(std::string(result, count));
109 char buffer[MAX_PATH];
110 DWORD length = GetModuleFileNameA(NULL, buffer, MAX_PATH);
112 throw std::runtime_error(
"Could not get executable path");
113 return std::filesystem::path(std::string(buffer, length));
115#eror "Unsupported platform"
124 return std::filesystem::path(std::string(dl_info.dli_fname));
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)) {
131 return std::filesystem::path();
134 char buffer[MAX_PATH];
135 DWORD length = GetModuleFileNameA(hModule, buffer, MAX_PATH);
137 throw std::runtime_error(
"Could not get library path");
139 return std::filesystem::path(std::string(buffer, length));
141#eror "Unsupported platform"
149 Logger &logger = ctxt.getLogger();
150 backend[0] = toupper(backend[0]);
154 std::string backendFileName =
"lib" + backend +
"Backend.so";
156 std::string backendFileName = backend +
"Backend.dll";
158#eror "Unsupported platform"
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)) {
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)) {
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)) {
182 backendPathStr = backendFileName;
183 logger.
debug(
"CONNECT",
184 "trying to load backend plugin: " + backendPathStr);
189 if (backendPathStr.empty())
190 backendPathStr = backendPath.string();
199 void *handle = dlopen(backendPathStr.c_str(), RTLD_NOW | RTLD_GLOBAL);
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: " +
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()));
218 HMODULE handle = LoadLibraryA(backendPathStr.c_str());
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");
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));
233#eror "Unsupported platform"
235 logger.
info(
"CONNECT",
"loaded backend plugin: " + backendPathStr);
243 static std::map<std::string, BackendCreate> &
get() {
254 if (registry.count(name))
255 throw std::runtime_error(
"Backend already exists in registry");
256 registry[name] = create;
261 const std::string &backend,
262 const std::string &connection) {
264 auto f = registry.find(backend);
265 if (f == registry.end()) {
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");
274 ctxt.getLogger().info(
"CONNECT",
"connecting to backend " + backend +
275 " via '" + connection +
"'");
276 return f->second(ctxt, connection);
283 void start() {
me = std::thread(&Impl::loop,
this); }
291 addListener(std::initializer_list<ReadChannelPort *> listenPorts,
294 void addTask(std::function<
void(
void)> task) {
295 std::lock_guard<std::mutex> g(
m);
310 std::future<MessageData>>>
317void AcceleratorServiceThread::Impl::loop() {
324 std::vector<std::function<void(
void)>> taskListCopy;
331 std::this_thread::sleep_for(std::chrono::microseconds(100));
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();
348 for (
auto [channel, cb, data] : portUnlockWorkList)
349 cb(channel, std::move(data));
352 portUnlockWorkList.clear();
357 std::lock_guard<std::mutex> g(
m);
360 for (
auto &task : taskListCopy)
365void AcceleratorServiceThread::Impl::addListener(
366 std::initializer_list<ReadChannelPort *> listenPorts,
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());
379 : impl(std::make_unique<
Impl>()) {
395 std::initializer_list<ReadChannelPort *> listenPorts,
398 impl->addListener(listenPorts, callback);
403 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::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.
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.