29#include <linux/limits.h>
40 : ctxt(ctxt), serviceThread(nullptr) {}
53 *
this, engineTypeName, idPath, details, clients);
58 std::unique_ptr<Engine> engine,
61 auto [engineIter, _] =
ownedEngines.emplace(idPath, std::move(engine));
65 Engine *enginePtr = engineIter->second.get();
68 if (prefix.size() > 0)
71 for (
const auto &client : clients) {
72 AppIDPath fullClientPath = prefix + client.relPath;
73 for (
const auto &channel : client.channelAssignments)
74 clientEngines[fullClientPath].setEngine(channel.first, enginePtr);
83 std::unique_ptr<Service> &cacheEntry =
84 serviceCache[make_tuple(std::string(svcType.name()),
id)];
85 if (cacheEntry ==
nullptr) {
92 cacheEntry = std::unique_ptr<Service>(svc);
94 return cacheEntry.get();
100 throw std::runtime_error(
101 "AcceleratorConnection already owns an accelerator");
109 char result[PATH_MAX];
110 ssize_t count = readlink(
"/proc/self/exe", result, PATH_MAX);
112 throw std::runtime_error(
"Could not get executable path");
113 return std::filesystem::path(std::string(result, count));
115 char buffer[MAX_PATH];
116 DWORD length = GetModuleFileNameA(NULL, buffer, MAX_PATH);
118 throw std::runtime_error(
"Could not get executable path");
119 return std::filesystem::path(std::string(buffer, length));
121#eror "Unsupported platform"
130 return std::filesystem::path(std::string(dl_info.dli_fname));
132 HMODULE hModule = NULL;
133 if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
134 GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
135 reinterpret_cast<LPCSTR
>(&
getLibPath), &hModule)) {
137 return std::filesystem::path();
140 char buffer[MAX_PATH];
141 DWORD length = GetModuleFileNameA(hModule, buffer, MAX_PATH);
143 throw std::runtime_error(
"Could not get library path");
145 return std::filesystem::path(std::string(buffer, length));
147#eror "Unsupported platform"
153 std::vector<std::filesystem::path> directories;
156 directories.push_back(std::filesystem::current_path());
159 const char *esiBackends = std::getenv(
"ESI_BACKENDS");
163 const char separator =
';';
165 const char separator =
':';
168 std::string pathsStr(esiBackends);
169 std::stringstream ss(pathsStr);
172 while (std::getline(ss, path, separator))
174 directories.emplace_back(path);
178 directories.push_back(
getExePath().parent_path());
180 directories.push_back(
getLibPath().parent_path());
191 backend[0] = toupper(backend[0]);
195 std::string backendFileName =
"lib" + backend +
"Backend.so";
197 std::string backendFileName = backend +
"Backend.dll";
199#eror "Unsupported platform"
203 std::filesystem::path backendPath;
205 std::vector<std::filesystem::path> esiBackendDirs =
208 for (
const auto &dir : esiBackendDirs) {
209 backendPath = dir / backendFileName;
210 logger.
debug(
"CONNECT",
211 "trying to find backend plugin: " + backendPath.string());
212 if (std::filesystem::exists(backendPath)) {
220 backendPath = std::filesystem::absolute(backendPath);
221 logger.
debug(
"CONNECT",
"found backend plugin: " + backendPath.string());
224 backendPath = backendFileName;
225 logger.
debug(
"CONNECT",
226 "trying to find backend plugin: " + backendFileName);
231 void *handle = dlopen(backendPath.string().c_str(), RTLD_NOW | RTLD_GLOBAL);
233 std::string error(dlerror());
234 logger.
error(
"CONNECT",
235 "while attempting to load backend plugin: " + error);
236 throw std::runtime_error(
"While attempting to load backend plugin: " +
243 std::filesystem::path backendPathParent = backendPath.parent_path();
248 if (backendPathParent.empty())
249 backendPathParent = std::filesystem::current_path();
250 logger.
debug(
"CONNECT",
"setting DLL search directory to: " +
251 backendPathParent.string());
252 if (SetDllDirectoryA(backendPathParent.string().c_str()) == 0)
253 throw std::runtime_error(
"While setting DLL directory: " +
254 std::to_string(GetLastError()));
258 HMODULE handle = LoadLibraryA(backendPath.string().c_str());
260 DWORD error = GetLastError();
262 LPSTR messageBuffer =
nullptr;
263 size_t size = FormatMessageA(
264 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
265 FORMAT_MESSAGE_IGNORE_INSERTS,
266 nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
267 (LPSTR)&messageBuffer, 0,
nullptr);
269 std::string errorMessage;
270 if (size > 0 && messageBuffer !=
nullptr) {
271 errorMessage = std::string(messageBuffer, size);
272 LocalFree(messageBuffer);
274 errorMessage =
"Unknown error";
277 std::string fullError =
"While attempting to load backend plugin '" +
278 backendPath.string() +
"': " + errorMessage +
279 " (error code: " + std::to_string(error) +
")";
281 logger.
error(
"CONNECT", fullError);
282 throw std::runtime_error(fullError);
285#eror "Unsupported platform"
287 logger.
info(
"CONNECT",
"loaded backend plugin: " + backendPath.string());
295 static std::map<std::string, BackendCreate> &
get() {
306 if (registry.count(name))
307 throw std::runtime_error(
"Backend already exists in registry");
308 registry[name] = create;
315 std::string connection) {
317 auto f = registry.find(backend);
318 if (f == registry.end()) {
321 f = registry.find(backend);
322 if (f == registry.end()) {
324 details[
"backend"] = backend;
325 std::ostringstream loaded_backends;
327 for (
const auto &b : registry) {
329 loaded_backends <<
", ";
330 loaded_backends << b.first;
333 details[
"loaded_backends"] = loaded_backends.str();
334 getLogger().
error(
"CONNECT",
"backend '" + backend +
"' not found",
336 throw std::runtime_error(
"Backend '" + backend +
"' not found");
339 getLogger().
info(
"CONNECT",
"connecting to backend " + backend +
" via '" +
341 auto conn = f->second(*
this, connection);
342 auto *connPtr = conn.get();
349 void start() {
me = std::thread(&Impl::loop,
this); }
357 addListener(std::initializer_list<ReadChannelPort *> listenPorts,
360 void addTask(std::function<
void(
void)> task) {
361 std::lock_guard<std::mutex> g(
m);
376 std::future<MessageData>>>
383void AcceleratorServiceThread::Impl::loop() {
390 std::vector<std::function<void(
void)>> taskListCopy;
398 std::this_thread::yield();
403 std::lock_guard<std::mutex> g(
m);
404 for (
auto &[channel, cbfPair] :
listeners) {
405 assert(channel &&
"Null channel in listener list");
406 std::future<MessageData> &f = cbfPair.second;
407 if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
408 portUnlockWorkList.emplace_back(channel, cbfPair.first, f.get());
409 f = channel->readAsync();
415 for (
auto [channel, cb, data] : portUnlockWorkList)
416 cb(channel, std::move(data));
419 portUnlockWorkList.clear();
424 std::lock_guard<std::mutex> g(
m);
427 for (
auto &task : taskListCopy)
432void AcceleratorServiceThread::Impl::addListener(
433 std::initializer_list<ReadChannelPort *> listenPorts,
435 std::lock_guard<std::mutex> g(m);
436 for (
auto port : listenPorts) {
437 if (listeners.count(port))
438 throw std::runtime_error(
"Port already has a listener");
439 listeners[port] = std::make_pair(callback, port->readAsync());
460 std::initializer_list<ReadChannelPort *> listenPorts,
463 impl->addListener(listenPorts, callback);
468 impl->addTask([&module]() {
module.poll(); });
assert(baseType &&"element must be base type")
Abstract class representing a connection to an accelerator.
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.
virtual void disconnect()
Disconnect from the accelerator cleanly.
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.
AcceleratorServiceThread()
std::unique_ptr< Impl > impl
void stop()
Instruct the service thread to stop running.
void addPoll(HWModule &module)
Poll this module.
~AcceleratorServiceThread()
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.
Top level accelerator class.
AcceleratorConnections, Accelerators, and Manifests must all share a context.
std::vector< std::unique_ptr< AcceleratorConnection > > connections
AcceleratorConnection * connect(std::string backend, std::string connection)
Connect to an accelerator backend.
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< 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.
static std::vector< std::filesystem::path > getESIBackendDirectories()
Get the list of directories to search for backend plugins.
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.