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";
199#if defined(_MSC_VER) && defined(_DEBUG)
200 std::string backendFileName = backend +
"Backend_d.dll";
202 std::string backendFileName = backend +
"Backend.dll";
205#error "Unsupported platform"
209 std::filesystem::path backendPath;
211 std::vector<std::filesystem::path> esiBackendDirs =
214 for (
const auto &dir : esiBackendDirs) {
215 backendPath = dir / backendFileName;
216 logger.
debug(
"CONNECT",
217 "trying to find backend plugin: " + backendPath.string());
218 if (std::filesystem::exists(backendPath)) {
226 backendPath = std::filesystem::absolute(backendPath);
227 logger.
debug(
"CONNECT",
"found backend plugin: " + backendPath.string());
230 backendPath = backendFileName;
231 logger.
debug(
"CONNECT",
232 "trying to find backend plugin: " + backendFileName);
237 void *handle = dlopen(backendPath.string().c_str(), RTLD_NOW | RTLD_GLOBAL);
239 std::string error(dlerror());
240 logger.
error(
"CONNECT",
241 "while attempting to load backend plugin: " + error);
242 throw std::runtime_error(
"While attempting to load backend plugin: " +
249 std::filesystem::path backendPathParent = backendPath.parent_path();
254 if (backendPathParent.empty())
255 backendPathParent = std::filesystem::current_path();
256 logger.
debug(
"CONNECT",
"setting DLL search directory to: " +
257 backendPathParent.string());
258 if (SetDllDirectoryA(backendPathParent.string().c_str()) == 0)
259 throw std::runtime_error(
"While setting DLL directory: " +
260 std::to_string(GetLastError()));
264 HMODULE handle = LoadLibraryA(backendPath.string().c_str());
266 DWORD error = GetLastError();
268 LPSTR messageBuffer =
nullptr;
269 size_t size = FormatMessageA(
270 FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
271 FORMAT_MESSAGE_IGNORE_INSERTS,
272 nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
273 (LPSTR)&messageBuffer, 0,
nullptr);
275 std::string errorMessage;
276 if (size > 0 && messageBuffer !=
nullptr) {
277 errorMessage = std::string(messageBuffer, size);
278 LocalFree(messageBuffer);
280 errorMessage =
"Unknown error";
283 std::string fullError =
"While attempting to load backend plugin '" +
284 backendPath.string() +
"': " + errorMessage +
285 " (error code: " + std::to_string(error) +
")";
287 logger.
error(
"CONNECT", fullError);
288 throw std::runtime_error(fullError);
291#eror "Unsupported platform"
293 logger.
info(
"CONNECT",
"loaded backend plugin: " + backendPath.string());
301 static std::map<std::string, BackendCreate> &
get() {
312 if (registry.count(name))
313 throw std::runtime_error(
"Backend already exists in registry");
314 registry[name] = create;
321 std::string connection) {
323 auto f = registry.find(backend);
324 if (f == registry.end()) {
327 f = registry.find(backend);
328 if (f == registry.end()) {
330 details[
"backend"] = backend;
331 std::ostringstream loaded_backends;
333 for (
const auto &b : registry) {
335 loaded_backends <<
", ";
336 loaded_backends << b.first;
339 details[
"loaded_backends"] = loaded_backends.str();
340 getLogger().
error(
"CONNECT",
"backend '" + backend +
"' not found",
342 throw std::runtime_error(
"Backend '" + backend +
"' not found");
345 getLogger().
info(
"CONNECT",
"connecting to backend " + backend +
" via '" +
347 auto conn = f->second(*
this, connection);
348 auto *connPtr = conn.get();
355 void start() {
me = std::thread(&Impl::loop,
this); }
363 addListener(std::initializer_list<ReadChannelPort *> listenPorts,
366 void addTask(std::function<
void(
void)> task) {
367 std::lock_guard<std::mutex> g(
m);
382 std::future<MessageData>>>
389void AcceleratorServiceThread::Impl::loop() {
396 std::vector<std::function<void(
void)>> taskListCopy;
404 std::this_thread::yield();
409 std::lock_guard<std::mutex> g(
m);
410 for (
auto &[channel, cbfPair] :
listeners) {
411 assert(channel &&
"Null channel in listener list");
412 std::future<MessageData> &f = cbfPair.second;
413 if (f.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
414 portUnlockWorkList.emplace_back(channel, cbfPair.first, f.get());
415 f = channel->readAsync();
421 for (
auto [channel, cb, data] : portUnlockWorkList)
422 cb(channel, std::move(data));
425 portUnlockWorkList.clear();
430 std::lock_guard<std::mutex> g(
m);
433 for (
auto &task : taskListCopy)
438void AcceleratorServiceThread::Impl::addListener(
439 std::initializer_list<ReadChannelPort *> listenPorts,
441 std::lock_guard<std::mutex> g(m);
442 for (
auto port : listenPorts) {
443 if (listeners.count(port))
444 throw std::runtime_error(
"Port already has a listener");
445 listeners[port] = std::make_pair(callback, port->readAsync());
466 std::initializer_list<ReadChannelPort *> listenPorts,
469 impl->addListener(listenPorts, callback);
474 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.