mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-06 04:55:44 +00:00
Layer and bridges updated from Winlator-NeuralScale 71c140d9 (michaelisomer-cyber, GPL-3.0): - full FSR 4.1 on the NPU (S8 graph, U8 fallback), compiled on the device per HTP arch - ghosting fix: blank far depth when a game sends none, binding 11 bound with 62 - FSR 4.1.2 Lite S8/U8 zero-copy graphs - Snapdragon GSR 2 on the GPU (new engine sgsr2_gpu) - D3D11 DLSS through DXVK's interop (nvngx D3D11 entry points) Left out on purpose: upstream's root-only performance/thermal manager, GPU clock floor and bypass charging. Kept from DroidDeck: NPU detection by the app (DROIDDECK_UPSCALE_NPU, any HTP generation incl. the phone's own QNN libraries) instead of upstream's SoC list, DD env names and log tags, Intel XeSS 3 (runtime still fetched from a0ab6b0f, upstream dropped it in cb3ae04e). FSR 4.0 on the NPU is gone upstream; the engine id becomes fsr4_1_full_npu and saved fsr4_0_npu choices map to it. The full-FSR-4-on-Turnip guard is now opt-in (DROIDDECK_UPSCALE_FULL_OFF_ON_TURNIP=1), since upstream's binding-11 fix targets that black frame. Data files re-pinned to 71c140d9 (81 core + 8 NPU, sha256 checked).
2119 lines
87 KiB
C
2119 lines
87 KiB
C
// Clean-room Qualcomm QNN HTP runtime management (bundled v79/v81 files, or any arch on the device's own QNN runtime) and zero-copy AHardwareBuffer/dmabuf
|
|
// shared tensor binding for the DroidDeck upscaler layer (ported from Winlator-NeuralScale).
|
|
// Adapted from BananaNative's verified SM8850 (Adreno 840 / Hexagon HTP v81) runtime.
|
|
// DD_UPSCALE_NO_ANDROID builds (glibc) compile only the stubs at the end: every NPU init fails
|
|
// with "npu_unavailable" and the callers keep their GPU paths.
|
|
#define _GNU_SOURCE
|
|
#include "fsr4_qnn.h"
|
|
#include "dd_upscale_compat.h"
|
|
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
#define F4_TAG "DroidDeckUpscaleNPU"
|
|
#define F4_LOGI(...) dd_upscale_log(DD_LOG_INFO, F4_TAG, __VA_ARGS__)
|
|
#define F4_LOGW(...) dd_upscale_log(DD_LOG_WARN, F4_TAG, __VA_ARGS__)
|
|
#define F4_LOGE(...) dd_upscale_log(DD_LOG_ERROR, F4_TAG, __VA_ARGS__)
|
|
|
|
#ifndef DD_UPSCALE_NO_ANDROID
|
|
|
|
#include <android/dlext.h>
|
|
#include <android/hardware_buffer.h>
|
|
#include <ctype.h>
|
|
#include <dirent.h>
|
|
#include <dlfcn.h>
|
|
#include <errno.h>
|
|
#include <pthread.h>
|
|
#include <sched.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/mman.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/system_properties.h>
|
|
#include <time.h>
|
|
#include <unistd.h>
|
|
|
|
typedef struct {
|
|
int version;
|
|
int numFds;
|
|
int numInts;
|
|
int data[];
|
|
} fsr4_native_handle;
|
|
|
|
typedef int (*pfn_remote_handle_control)(uint32_t req, void *data, uint32_t len);
|
|
typedef void *(*pfn_rpcmem_alloc)(int heapid, uint32_t flags, int size);
|
|
typedef void (*pfn_rpcmem_free)(void *po);
|
|
typedef int (*pfn_rpcmem_to_fd)(void *po);
|
|
typedef Qnn_ErrorHandle_t (*pfn_qnn_get_providers)(const QnnInterface_t ***list, uint32_t *n);
|
|
typedef Qnn_ErrorHandle_t (*pfn_qnn_sys_get_providers)(const QnnSystemInterface_t ***list, uint32_t *n);
|
|
typedef const fsr4_native_handle *(*pfn_ahb_get_native_handle)(const AHardwareBuffer *buf);
|
|
|
|
typedef struct {
|
|
int refs;
|
|
char power_mode[32];
|
|
void *lib_cdsp, *lib_sys, *lib_htp, *lib_prep;
|
|
void *lib_stub[2];
|
|
const QnnSystemInterface_ImplV1_11_t *S;
|
|
const QnnInterface_ImplV2_36_t *Q;
|
|
Qnn_LogHandle_t logger;
|
|
Qnn_BackendHandle_t backend;
|
|
Qnn_DeviceHandle_t device;
|
|
const QnnHtpDevice_PerfInfrastructure_t *perf;
|
|
uint32_t power_id;
|
|
int has_power_id;
|
|
size_t dline;
|
|
double last_exec_ms;
|
|
} qnn_rt;
|
|
|
|
static pthread_mutex_t g_rt_mu = PTHREAD_MUTEX_INITIALIZER;
|
|
static qnn_rt g_rt;
|
|
static char g_qnn_last_err[64] = "none";
|
|
|
|
static void set_qnn_err(const char *fmt, ...) {
|
|
va_list ap;
|
|
va_start(ap, fmt);
|
|
vsnprintf(g_qnn_last_err, sizeof g_qnn_last_err, fmt, ap);
|
|
va_end(ap);
|
|
}
|
|
|
|
const char *wl_fsr4_qnn_last_error(void) {
|
|
return g_qnn_last_err;
|
|
}
|
|
|
|
typedef struct {
|
|
AHardwareBuffer *ahb;
|
|
void *lib_nativewin;
|
|
void *lib_rpc;
|
|
void *rpc_ptr;
|
|
pfn_rpcmem_free rpc_free;
|
|
int is_heap;
|
|
int dmabuf_fd;
|
|
uint8_t *mapped;
|
|
size_t bytes;
|
|
} qnn_ahb;
|
|
|
|
typedef struct {
|
|
int ready;
|
|
int nslots;
|
|
Qnn_ContextHandle_t ctx;
|
|
Qnn_GraphHandle_t graph;
|
|
Qnn_Tensor_t in_t[2], out_t[2];
|
|
Qnn_MemHandle_t in_mh[2], out_mh[2];
|
|
char *names[4];
|
|
uint32_t *dims[4];
|
|
uint8_t *dyns[4];
|
|
void *qextra[4];
|
|
} qnn_graph;
|
|
|
|
struct wl_fsr4_qnn {
|
|
char dir[512];
|
|
int has_rt;
|
|
size_t dline;
|
|
qnn_ahb buf;
|
|
qnn_graph presets[2];
|
|
};
|
|
|
|
static double mono_ms(void) {
|
|
struct timespec ts;
|
|
clock_gettime(CLOCK_MONOTONIC, &ts);
|
|
return (double)ts.tv_sec * 1e3 + (double)ts.tv_nsec * 1e-6;
|
|
}
|
|
|
|
static size_t query_dcache_line(void) {
|
|
#if defined(__aarch64__)
|
|
uint64_t ctr = 0;
|
|
__asm__ volatile("mrs %0, ctr_el0" : "=r"(ctr));
|
|
size_t sz = (size_t)4u << ((ctr >> 16) & 0xfu);
|
|
return sz >= 16u ? sz : 64u;
|
|
#else
|
|
return 64u;
|
|
#endif
|
|
}
|
|
|
|
static void civac_range(const void *ptr, size_t bytes, size_t line) {
|
|
#if defined(__aarch64__)
|
|
if (!ptr || !bytes) return;
|
|
uintptr_t p = (uintptr_t)ptr & ~(uintptr_t)(line - 1);
|
|
uintptr_t end = ((uintptr_t)ptr + bytes + line - 1) & ~(uintptr_t)(line - 1);
|
|
for (; p < end; p += line) __asm__ volatile("dc civac, %0" : : "r"(p) : "memory");
|
|
__asm__ volatile("dsb sy" : : : "memory");
|
|
#else
|
|
(void)ptr; (void)bytes; (void)line;
|
|
#endif
|
|
}
|
|
|
|
static int qnn_log_verbose(void) {
|
|
const char *e = dd_upscale_env("LOG");
|
|
return e && atoi(e) >= 2;
|
|
}
|
|
|
|
static void qnn_log_cb(const char *fmt, uint32_t level, uint64_t ts, va_list args) {
|
|
(void)ts;
|
|
if (!fmt) return;
|
|
if (level > QNN_LOG_LEVEL_WARN && !qnn_log_verbose()) return;
|
|
char msg[512];
|
|
vsnprintf(msg, sizeof msg, fmt, args);
|
|
size_t n = strlen(msg);
|
|
while (n > 0 && (msg[n - 1] == '\n' || msg[n - 1] == '\r')) msg[--n] = 0;
|
|
if (level <= QNN_LOG_LEVEL_ERROR) F4_LOGE("QNN: %s", msg);
|
|
else F4_LOGI("QNN: %s", msg);
|
|
}
|
|
|
|
// ---- Hexagon HTP arch of this SoC: names the folder that holds compiled context caches ----
|
|
// A context binary only loads on the arch it was finalized for, so caches live in <dir>/<arch>/.
|
|
static char g_htp_arch[8];
|
|
static pthread_mutex_t g_htp_arch_mu = PTHREAD_MUTEX_INITIALIZER;
|
|
static int g_htp_soc_checked;
|
|
static int g_htp_rt_up; // a QNN device exists, so libQnnHtp.so has mapped its stub
|
|
static int g_htp_stubs_preloaded_all; // both stubs mapped by us: /proc/self/maps says nothing
|
|
|
|
static int htp_arch_valid(const char *a) {
|
|
size_t n = a ? strlen(a) : 0;
|
|
if (n < 2 || n > 4 || a[0] != 'v') return 0;
|
|
for (size_t i = 1; i < n; i++) if (!isdigit((unsigned char)a[i])) return 0;
|
|
return 1;
|
|
}
|
|
|
|
static const char *htp_arch_from_soc(void) {
|
|
// SoCs whose HTP skel ships with the layer's data files (adsp/libQnnHtpV79Skel.so, V81Skel.so).
|
|
static const struct { const char *model_prefix, *platform, *arch; } k_socs[] = {
|
|
{"SM8750", "sun", "v79"}, // Snapdragon 8 Elite
|
|
{"SM8850", "canoe", "v81"}, // Snapdragon 8 Elite Gen 5
|
|
};
|
|
char v[PROP_VALUE_MAX];
|
|
static const char *const model_props[] = {"ro.soc.model", "ro.vendor.qti.soc_model"};
|
|
static const char *const platform_props[] = {"ro.vendor.qti.soc_name", "ro.board.platform"};
|
|
for (size_t p = 0; p < sizeof model_props / sizeof model_props[0]; p++) {
|
|
if (__system_property_get(model_props[p], v) <= 0) continue;
|
|
for (size_t i = 0; i < sizeof k_socs / sizeof k_socs[0]; i++)
|
|
if (!strncasecmp(v, k_socs[i].model_prefix, strlen(k_socs[i].model_prefix))) return k_socs[i].arch;
|
|
}
|
|
for (size_t p = 0; p < sizeof platform_props / sizeof platform_props[0]; p++) {
|
|
if (__system_property_get(platform_props[p], v) <= 0) continue;
|
|
for (size_t i = 0; i < sizeof k_socs / sizeof k_socs[0]; i++)
|
|
if (!strcasecmp(v, k_socs[i].platform)) return k_socs[i].arch;
|
|
}
|
|
return NULL;
|
|
}
|
|
|
|
// The phone's own QNN runtime names its arch by its stub (/vendor/lib64/libQnnHtpV<NN>Stub.so), for SoCs the
|
|
// table above does not list. Stubs of two arches: no answer here.
|
|
static int htp_arch_from_vendor(char *out, size_t out_sz) {
|
|
DIR *d = opendir("/vendor/lib64");
|
|
if (!d) return 0;
|
|
char found[8] = "";
|
|
int ambiguous = 0;
|
|
struct dirent *e;
|
|
while (!ambiguous && (e = readdir(d))) {
|
|
if (strncmp(e->d_name, "libQnnHtpV", 10) != 0) continue;
|
|
const char *dg = e->d_name + 10;
|
|
size_t n = 0;
|
|
while (n < 3 && isdigit((unsigned char)dg[n])) n++;
|
|
if (n < 2 || strcmp(dg + n, "Stub.so") != 0) continue;
|
|
char a[8];
|
|
snprintf(a, sizeof a, "v%.*s", (int)n, dg);
|
|
if (!found[0]) snprintf(found, sizeof found, "%s", a);
|
|
else if (strcmp(found, a) != 0) ambiguous = 1;
|
|
}
|
|
closedir(d);
|
|
if (!found[0] || ambiguous) return 0;
|
|
snprintf(out, out_sz, "%s", found);
|
|
return 1;
|
|
}
|
|
|
|
// libQnnHtp.so maps the arch stub (libQnnHtpVNNStub.so) once a device exists.
|
|
static int htp_arch_from_maps(char *out, size_t out_sz) {
|
|
FILE *f = fopen("/proc/self/maps", "r");
|
|
if (!f) return 0;
|
|
char line[1024];
|
|
int found = 0;
|
|
while (!found && fgets(line, sizeof line, f)) {
|
|
const char *m = strstr(line, "libQnnHtpV");
|
|
size_t skip = 10;
|
|
if (!m) { m = strstr(line, "libQairtHtpV"); skip = 12; }
|
|
if (!m) continue;
|
|
const char *d = m + skip;
|
|
size_t n = 0;
|
|
while (n < 3 && isdigit((unsigned char)d[n])) n++;
|
|
if (n >= 2 && !strncmp(d + n, "Stub.so", 7)) {
|
|
snprintf(out, out_sz, "v%.*s", (int)n, d);
|
|
found = 1;
|
|
}
|
|
}
|
|
fclose(f);
|
|
return found;
|
|
}
|
|
|
|
static const char *htp_arch_from_skels(const char *fsr4_dir) {
|
|
if (!fsr4_dir) return NULL;
|
|
char p79[640], p81[640];
|
|
snprintf(p79, sizeof p79, "%s/adsp/libQnnHtpV79Skel.so", fsr4_dir);
|
|
snprintf(p81, sizeof p81, "%s/adsp/libQnnHtpV81Skel.so", fsr4_dir);
|
|
int has79 = access(p79, R_OK) == 0, has81 = access(p81, R_OK) == 0;
|
|
if (has79 != has81) return has79 ? "v79" : "v81";
|
|
return NULL;
|
|
}
|
|
|
|
// Order: HTP_ARCH env, SoC properties, the vendor's own stub, mapped stub (once a QNN device exists), the only skel in
|
|
// <dir>/adsp, else "htp". A hit from the first three is kept for the process.
|
|
static const char *htp_arch_for_dir(const char *fsr4_dir) {
|
|
pthread_mutex_lock(&g_htp_arch_mu);
|
|
if (!g_htp_arch[0] && !g_htp_soc_checked) {
|
|
g_htp_soc_checked = 1;
|
|
const char *env = dd_upscale_env("HTP_ARCH");
|
|
const char *a = htp_arch_valid(env) ? env : htp_arch_from_soc();
|
|
if (a) snprintf(g_htp_arch, sizeof g_htp_arch, "%s", a);
|
|
else htp_arch_from_vendor(g_htp_arch, sizeof g_htp_arch);
|
|
}
|
|
if (!g_htp_arch[0] && g_htp_rt_up && !g_htp_stubs_preloaded_all) {
|
|
char mapped[8];
|
|
if (htp_arch_from_maps(mapped, sizeof mapped)) snprintf(g_htp_arch, sizeof g_htp_arch, "%s", mapped);
|
|
}
|
|
const char *out = g_htp_arch[0] ? g_htp_arch : NULL;
|
|
pthread_mutex_unlock(&g_htp_arch_mu);
|
|
if (out) return out;
|
|
const char *a = htp_arch_from_skels(fsr4_dir);
|
|
return a ? a : "htp";
|
|
}
|
|
|
|
int wl_fsr4_qnn_cache_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz) {
|
|
if (!fsr4_dir || !*fsr4_dir || !name || !out || !out_sz) return 0;
|
|
int n = snprintf(out, out_sz, "%s/%s/%s", fsr4_dir, htp_arch_for_dir(fsr4_dir), name);
|
|
return n > 0 && (size_t)n < out_sz;
|
|
}
|
|
|
|
static void cache_rel_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz) {
|
|
snprintf(out, out_sz, "%s/%s", htp_arch_for_dir(fsr4_dir), name);
|
|
}
|
|
|
|
static void ensure_adsp_path(const char *fsr4_dir) {
|
|
char adsp[600];
|
|
snprintf(adsp, sizeof adsp, "%s/adsp", fsr4_dir);
|
|
const char *cur = getenv("ADSP_LIBRARY_PATH");
|
|
if (cur && strstr(cur, adsp)) return;
|
|
char next[1536];
|
|
if (cur && *cur) snprintf(next, sizeof next, "%s;%s", adsp, cur);
|
|
else snprintf(next, sizeof next, "%s;/vendor/dsp/cdsp;/vendor/lib/rfsa/adsp;/system/lib/rfsa/adsp", adsp);
|
|
setenv("ADSP_LIBRARY_PATH", next, 1);
|
|
}
|
|
|
|
typedef struct android_namespace_t *(*pfn_get_exported_ns)(const char *name);
|
|
|
|
static struct android_namespace_t *get_sphal_ns(void) {
|
|
static int probed = 0;
|
|
static struct android_namespace_t *ns = NULL;
|
|
if (probed) return ns;
|
|
probed = 1;
|
|
pfn_get_exported_ns fn = (pfn_get_exported_ns)dlsym(RTLD_DEFAULT, "android_get_exported_namespace");
|
|
if (!fn) {
|
|
void *h = dlopen("libdl_android.so", RTLD_NOW | RTLD_LOCAL);
|
|
if (!h) h = dlopen("/system/lib64/libdl_android.so", RTLD_NOW | RTLD_LOCAL);
|
|
if (h) fn = (pfn_get_exported_ns)dlsym(h, "android_get_exported_namespace");
|
|
}
|
|
if (fn) {
|
|
ns = fn("sphal");
|
|
if (ns) F4_LOGI("Acquired Android 'sphal' linker namespace for Hexagon FastRPC/QNN");
|
|
}
|
|
return ns;
|
|
}
|
|
|
|
static void *dlopen_in_sphal(const char *path, int flags) {
|
|
struct android_namespace_t *ns = get_sphal_ns();
|
|
if (!ns) return NULL;
|
|
android_dlextinfo ext;
|
|
memset(&ext, 0, sizeof ext);
|
|
ext.flags = ANDROID_DLEXT_USE_NAMESPACE;
|
|
ext.library_namespace = ns;
|
|
return android_dlopen_ext(path, flags, &ext);
|
|
}
|
|
|
|
static int resolve_qnn_lib_path(const char *fsr4_dir, const char *soname, char *out, size_t out_sz) {
|
|
// 1. <fsr4_dir>/jni/arm64-v8a/<soname>
|
|
snprintf(out, out_sz, "%s/jni/arm64-v8a/%s", fsr4_dir, soname);
|
|
if (access(out, R_OK) == 0) return 1;
|
|
// 2. <fsr4_dir>/<soname>
|
|
snprintf(out, out_sz, "%s/%s", fsr4_dir, soname);
|
|
if (access(out, R_OK) == 0) return 1;
|
|
// 3. <DROIDDECK_UPSCALE_NATIVELIB_DIR>/<soname>
|
|
const char *nld = dd_upscale_env("NATIVELIB_DIR");
|
|
if (nld) {
|
|
snprintf(out, out_sz, "%s/%s", nld, soname);
|
|
if (access(out, R_OK) == 0) return 1;
|
|
}
|
|
// 4. Scan LD_LIBRARY_PATH entries
|
|
const char *ldp = getenv("LD_LIBRARY_PATH");
|
|
if (ldp && *ldp) {
|
|
const char *p = ldp;
|
|
while (*p) {
|
|
const char *colon = strchr(p, ':');
|
|
size_t len = colon ? (size_t)(colon - p) : strlen(p);
|
|
if (len > 0 && len < 512) {
|
|
snprintf(out, out_sz, "%.*s/%s", (int)len, p, soname);
|
|
if (access(out, R_OK) == 0) return 1;
|
|
}
|
|
if (!colon) break;
|
|
p = colon + 1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// The bundled QNN libraries (the pinned download in <dir>) serve only the arches whose skel came with them
|
|
// (<dir>/adsp/libQnnHtpV<NN>Skel.so). Any other arch runs on the phone's own QNN runtime, loaded by name
|
|
// (vendor libraries listed in public.libraries.txt). An arch not known yet keeps the bundled ones.
|
|
static int use_bundled_qnn(const char *fsr4_dir) {
|
|
char path[640];
|
|
if (!resolve_qnn_lib_path(fsr4_dir, "libQnnHtp.so", path, sizeof path)) return 0;
|
|
const char *arch = htp_arch_for_dir(fsr4_dir);
|
|
if (!htp_arch_valid(arch)) return 1;
|
|
snprintf(path, sizeof path, "%s/adsp/libQnnHtpV%sSkel.so", fsr4_dir, arch + 1);
|
|
return access(path, R_OK) == 0;
|
|
}
|
|
|
|
static void *dlopen_qnn_lib_flags(const char *fsr4_dir, const char *soname, int flags) {
|
|
char full[640];
|
|
if (use_bundled_qnn(fsr4_dir) && resolve_qnn_lib_path(fsr4_dir, soname, full, sizeof full)) {
|
|
// Prefer loading QNN libs in 'sphal' so libQnnHtpV81Stub.so resolves vendor libcdsprpc.so
|
|
void *h = dlopen_in_sphal(full, flags);
|
|
if (h) return h;
|
|
h = dlopen(full, flags);
|
|
if (h) return h;
|
|
}
|
|
void *h = dlopen_in_sphal(soname, flags);
|
|
if (h) return h;
|
|
return dlopen(soname, flags);
|
|
}
|
|
|
|
static void *dlopen_qnn_lib(const char *fsr4_dir, const char *soname) {
|
|
return dlopen_qnn_lib_flags(fsr4_dir, soname, RTLD_NOW | RTLD_LOCAL);
|
|
}
|
|
|
|
static void *dlopen_cdsprpc(void) {
|
|
void *h = dlopen_in_sphal("libcdsprpc.so", RTLD_NOW | RTLD_GLOBAL);
|
|
if (!h) h = dlopen_in_sphal("/vendor/lib64/libcdsprpc.so", RTLD_NOW | RTLD_GLOBAL);
|
|
if (!h) h = dlopen("/vendor/lib64/libcdsprpc.so", RTLD_NOW | RTLD_GLOBAL);
|
|
if (!h) h = dlopen("/system/vendor/lib64/libcdsprpc.so", RTLD_NOW | RTLD_GLOBAL);
|
|
if (!h) h = dlopen("libcdsprpc.so", RTLD_NOW | RTLD_GLOBAL);
|
|
return h;
|
|
}
|
|
|
|
// libQnnHtp.so dlopens libQnnHtpV<arch>Stub.so by name. Loading the stub first from the same
|
|
// search list (DIR/jni/arm64-v8a, DIR, NATIVELIB_DIR, LD_LIBRARY_PATH) lets that lookup find it
|
|
// without LD_LIBRARY_PATH. Unknown arch: every stub that is present gets loaded.
|
|
static void preload_htp_stubs(qnn_rt *rt, const char *fsr4_dir) {
|
|
if (!use_bundled_qnn(fsr4_dir)) return; // the phone's libQnnHtp.so finds its own stub
|
|
static const char *const k_arch[2] = {"v79", "v81"};
|
|
static const char *const k_stubs[2] = {"libQnnHtpV79Stub.so", "libQnnHtpV81Stub.so"};
|
|
const char *arch = htp_arch_for_dir(fsr4_dir);
|
|
int known = !strcmp(arch, k_arch[0]) || !strcmp(arch, k_arch[1]);
|
|
for (int i = 0; i < 2; i++) {
|
|
if (known && strcmp(arch, k_arch[i]) != 0) continue;
|
|
char full[640];
|
|
if (!resolve_qnn_lib_path(fsr4_dir, k_stubs[i], full, sizeof full)) continue;
|
|
rt->lib_stub[i] = dlopen_qnn_lib_flags(fsr4_dir, k_stubs[i], RTLD_NOW | RTLD_GLOBAL);
|
|
if (!rt->lib_stub[i]) F4_LOGW("preload %s failed: %s", full, dlerror());
|
|
}
|
|
if (!known && rt->lib_stub[0] && rt->lib_stub[1]) {
|
|
pthread_mutex_lock(&g_htp_arch_mu);
|
|
g_htp_stubs_preloaded_all = 1;
|
|
pthread_mutex_unlock(&g_htp_arch_mu);
|
|
}
|
|
}
|
|
|
|
static void request_unsigned_pd(qnn_rt *rt) {
|
|
rt->lib_cdsp = dlopen_cdsprpc();
|
|
if (!rt->lib_cdsp) return;
|
|
pfn_remote_handle_control ctl = (pfn_remote_handle_control)dlsym(rt->lib_cdsp, "remote_handle_control");
|
|
if (!ctl) return;
|
|
struct { uint32_t domain; uint32_t enable; } req = {3u, 1u};
|
|
int rc = ctl(4u, &req, (uint32_t)sizeof req);
|
|
if (rc != 0) F4_LOGW("remote_handle_control unsigned PD returned %d (continuing)", rc);
|
|
}
|
|
|
|
static int extract_ahb_dmabuf(qnn_ahb *b, uint64_t min_bytes) {
|
|
pfn_ahb_get_native_handle get_nh = (pfn_ahb_get_native_handle)dlsym(RTLD_DEFAULT, "AHardwareBuffer_getNativeHandle");
|
|
if (!get_nh) {
|
|
b->lib_nativewin = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
|
|
if (b->lib_nativewin) get_nh = (pfn_ahb_get_native_handle)dlsym(b->lib_nativewin, "AHardwareBuffer_getNativeHandle");
|
|
}
|
|
if (get_nh) {
|
|
const fsr4_native_handle *nh = get_nh(b->ahb);
|
|
if (nh && nh->numFds > 0 && nh->numFds <= 32) {
|
|
for (int i = 0; i < nh->numFds; i++) {
|
|
int f = nh->data[i];
|
|
if (f < 0) continue;
|
|
off_t sz = lseek(f, 0, SEEK_END);
|
|
if (sz >= 0) lseek(f, 0, SEEK_SET);
|
|
if (sz >= (off_t)min_bytes) {
|
|
int dupfd = dup(f);
|
|
if (dupfd >= 0) return dupfd;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
int sv[2] = {-1, -1};
|
|
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) return -1;
|
|
int s = AHardwareBuffer_sendHandleToUnixSocket(b->ahb, sv[0]);
|
|
if (s != 0) { close(sv[0]); close(sv[1]); return -1; }
|
|
char payload[256], cbuf[CMSG_SPACE(sizeof(int) * 16)];
|
|
struct iovec iov = {payload, sizeof payload};
|
|
struct msghdr msg;
|
|
memset(&msg, 0, sizeof msg);
|
|
msg.msg_iov = &iov;
|
|
msg.msg_iovlen = 1;
|
|
msg.msg_control = cbuf;
|
|
msg.msg_controllen = sizeof cbuf;
|
|
ssize_t nr = recvmsg(sv[1], &msg, MSG_CMSG_CLOEXEC);
|
|
close(sv[0]);
|
|
close(sv[1]);
|
|
if (nr < 0) return -1;
|
|
int out_fd = -1;
|
|
for (struct cmsghdr *cm = CMSG_FIRSTHDR(&msg); cm; cm = CMSG_NXTHDR(&msg, cm)) {
|
|
if (cm->cmsg_level == SOL_SOCKET && cm->cmsg_type == SCM_RIGHTS) {
|
|
int n = (int)((cm->cmsg_len - CMSG_LEN(0)) / sizeof(int));
|
|
int *fds = (int *)CMSG_DATA(cm);
|
|
for (int i = 0; i < n; i++) {
|
|
off_t sz = fds[i] >= 0 ? lseek(fds[i], 0, SEEK_END) : -1;
|
|
if (fds[i] >= 0 && sz >= 0) lseek(fds[i], 0, SEEK_SET);
|
|
if (out_fd < 0 && fds[i] >= 0 && sz >= (off_t)min_bytes) out_fd = fds[i];
|
|
else if (fds[i] >= 0) close(fds[i]);
|
|
}
|
|
}
|
|
}
|
|
return out_fd;
|
|
}
|
|
|
|
static void qnn_ahb_free(qnn_ahb *b) {
|
|
if (b->rpc_ptr) {
|
|
if (b->rpc_free) b->rpc_free(b->rpc_ptr);
|
|
b->rpc_ptr = NULL;
|
|
b->mapped = NULL;
|
|
b->dmabuf_fd = -1;
|
|
} else if (b->is_heap) {
|
|
free(b->mapped);
|
|
b->mapped = NULL;
|
|
b->is_heap = 0;
|
|
} else {
|
|
if (b->mapped) { munmap(b->mapped, b->bytes); b->mapped = NULL; }
|
|
if (b->dmabuf_fd >= 0) { close(b->dmabuf_fd); b->dmabuf_fd = -1; }
|
|
}
|
|
if (b->ahb) { AHardwareBuffer_release(b->ahb); b->ahb = NULL; }
|
|
if (b->lib_nativewin) { dlclose(b->lib_nativewin); b->lib_nativewin = NULL; }
|
|
if (b->lib_rpc) { dlclose(b->lib_rpc); b->lib_rpc = NULL; }
|
|
b->rpc_free = NULL;
|
|
b->bytes = 0;
|
|
}
|
|
|
|
static int qnn_ahb_alloc(qnn_ahb *b, size_t bytes, size_t dline) {
|
|
memset(b, 0, sizeof *b);
|
|
b->dmabuf_fd = -1;
|
|
b->bytes = bytes;
|
|
|
|
// Tier 1 & 2: AHardwareBuffer BLOB (zero-copy Adreno GPU + Hexagon HTP when supported)
|
|
AHardwareBuffer_Desc desc;
|
|
memset(&desc, 0, sizeof desc);
|
|
desc.width = (uint32_t)bytes;
|
|
desc.height = 1;
|
|
desc.layers = 1;
|
|
desc.format = AHARDWAREBUFFER_FORMAT_BLOB;
|
|
desc.usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN | (1ULL << 24);
|
|
if (AHardwareBuffer_allocate(&desc, &b->ahb) != 0 || !b->ahb) {
|
|
desc.usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;
|
|
if (AHardwareBuffer_allocate(&desc, &b->ahb) != 0) b->ahb = NULL;
|
|
}
|
|
if (b->ahb) {
|
|
b->dmabuf_fd = extract_ahb_dmabuf(b, (uint64_t)bytes);
|
|
if (b->dmabuf_fd >= 0) {
|
|
void *mp = mmap(NULL, bytes, PROT_READ | PROT_WRITE, MAP_SHARED, b->dmabuf_fd, 0);
|
|
if (mp != MAP_FAILED) {
|
|
b->mapped = (uint8_t *)mp;
|
|
memset(b->mapped, 0, bytes);
|
|
civac_range(b->mapped, bytes, dline);
|
|
return 1;
|
|
}
|
|
F4_LOGW("mmap AHB dmabuf(%zu B) failed errno=%d; trying rpcmem fallback", bytes, errno);
|
|
close(b->dmabuf_fd);
|
|
b->dmabuf_fd = -1;
|
|
} else {
|
|
F4_LOGW("extract_ahb_dmabuf(%zu B) failed; trying rpcmem fallback", bytes);
|
|
}
|
|
AHardwareBuffer_release(b->ahb);
|
|
b->ahb = NULL;
|
|
}
|
|
|
|
// Tier 3: FastRPC rpcmem ION buffer (works on all Qualcomm SoCs including non-AHB drivers)
|
|
b->lib_rpc = dlopen_cdsprpc();
|
|
if (b->lib_rpc) {
|
|
pfn_rpcmem_alloc p_alloc = (pfn_rpcmem_alloc)dlsym(b->lib_rpc, "rpcmem_alloc");
|
|
pfn_rpcmem_free p_free = (pfn_rpcmem_free)dlsym(b->lib_rpc, "rpcmem_free");
|
|
pfn_rpcmem_to_fd p_tofd = (pfn_rpcmem_to_fd)dlsym(b->lib_rpc, "rpcmem_to_fd");
|
|
if (p_alloc && p_free && p_tofd) {
|
|
void *p = p_alloc(25 /* RPCMEM_HEAP_ID_SYSTEM */, 1 /* RPCMEM_DEFAULT_FLAGS */, (int)bytes);
|
|
if (p) {
|
|
int fd = p_tofd(p);
|
|
if (fd >= 0) {
|
|
b->rpc_ptr = p;
|
|
b->rpc_free = p_free;
|
|
b->dmabuf_fd = fd;
|
|
b->mapped = (uint8_t *)p;
|
|
memset(b->mapped, 0, bytes);
|
|
civac_range(b->mapped, bytes, dline);
|
|
F4_LOGI("Allocated %zu B QNN tensor buffer via FastRPC rpcmem (fd=%d)", bytes, fd);
|
|
return 1;
|
|
}
|
|
p_free(p);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Tier 4: Plain heap buffer (paired with QNN_TENSORMEMTYPE_RAW fallback in graph_load_locked)
|
|
b->mapped = (uint8_t *)calloc(1, bytes);
|
|
if (!b->mapped) {
|
|
set_qnn_err("qnn_alloc_oom");
|
|
qnn_ahb_free(b);
|
|
return 0;
|
|
}
|
|
b->is_heap = 1;
|
|
F4_LOGW("Allocated %zu B QNN tensor buffer via heap fallback (QNN RAW memType)", bytes);
|
|
return 1;
|
|
}
|
|
|
|
static int apply_power_profile(qnn_rt *rt, const char *mode) {
|
|
const char *eff_mode = (mode && *mode) ? mode : "balanced";
|
|
if (!rt->has_power_id) {
|
|
const QnnHtpDevice_Infrastructure_t *infra = NULL;
|
|
if (!rt->Q || !rt->Q->deviceGetInfrastructure ||
|
|
rt->Q->deviceGetInfrastructure(&infra) != QNN_SUCCESS_CODE ||
|
|
!infra || infra->infraType != QNN_HTP_DEVICE_INFRA_TYPE_PERF)
|
|
return -1;
|
|
rt->perf = &infra->perfInfra;
|
|
if (!rt->perf->createPowerConfigId || !rt->perf->setPowerConfig) return -1;
|
|
if (rt->perf->createPowerConfigId(0, 0, &rt->power_id) != QNN_SUCCESS_CODE) return -1;
|
|
rt->has_power_id = 1;
|
|
} else {
|
|
if (!rt->perf || !rt->perf->setPowerConfig) return -1;
|
|
if (strcmp(rt->power_mode, eff_mode) == 0) return 0;
|
|
}
|
|
|
|
// Gaming-aware Hexagon HTP power profiles (with HMX_TIMEOUT_INTERVAL_US + runtime gear shifting):
|
|
// - idle : withdraws Bus/Core/HMX votes (DISABLE) during pause menus / loading (>500 ms idle)
|
|
// - async_eco : POWER_SAVER, 500 us sleepLat, 0 us RPC poll, SVS2->SVS->NOM, HMX SVS + 250 us timeout
|
|
// - async_mid : POWER_SAVER, 200 us sleepLat, 0 us RPC poll, SVS2->NOM->NOM, HMX NOM + 500 us timeout
|
|
// - low : POWER_SAVER, 200 us sleepLat, 0 us RPC poll, SVS2->SVS->NOM, HMX SVS + 250 us timeout
|
|
// - balanced : PERF, 100 us sleepLat, 150 us RPC poll, SVS2->NOM->TURBO, HMX NOM/TUR + 1000 us timeout
|
|
// - turbo : PERF, 100 us sleepLat, 1000 us RPC poll, SVS->TURBO->MAX, HMX TUR + 2000 us timeout
|
|
// - burst : pinned awake (sleepDisable=1), 9999 us poll, MAX pinned (benchmark mode)
|
|
uint32_t dcvs_mode = QNN_HTP_POWERMODE_PERF;
|
|
uint32_t sleep_disable = 0u;
|
|
uint32_t sleep_lat_us = 100u;
|
|
uint32_t rpc_poll_us = 150u;
|
|
uint32_t min_corner = QNN_HTP_VCORNER_SVS2;
|
|
uint32_t tgt_corner = QNN_HTP_VCORNER_NOM;
|
|
uint32_t max_corner = QNN_HTP_VCORNER_TURBO;
|
|
uint32_t hmx_min = QNN_HTP_EXP_VCORNER_LOW_SVS;
|
|
uint32_t hmx_tgt = QNN_HTP_EXP_VCORNER_NOM;
|
|
uint32_t hmx_max = QNN_HTP_EXP_VCORNER_TUR;
|
|
uint32_t hmx_perf = QNN_HTP_CLK_PERF_HIGH;
|
|
uint32_t hmx_timeout_us = 1000u;
|
|
int is_idle = 0;
|
|
|
|
if (!strcmp(eff_mode, "idle")) {
|
|
is_idle = 1;
|
|
dcvs_mode = QNN_HTP_POWERMODE_POWER_SAVER;
|
|
sleep_disable = 0u;
|
|
sleep_lat_us = 500u;
|
|
rpc_poll_us = 0u;
|
|
min_corner = QNN_HTP_VCORNER_DISABLE;
|
|
tgt_corner = QNN_HTP_VCORNER_DISABLE;
|
|
max_corner = QNN_HTP_VCORNER_DISABLE;
|
|
hmx_min = QNN_HTP_EXP_VCORNER_DISABLE;
|
|
hmx_tgt = QNN_HTP_EXP_VCORNER_DISABLE;
|
|
hmx_max = QNN_HTP_EXP_VCORNER_DISABLE;
|
|
hmx_perf = QNN_HTP_CLK_PERF_LOW;
|
|
hmx_timeout_us = 250u;
|
|
} else if (!strcmp(eff_mode, "async_eco")) {
|
|
dcvs_mode = QNN_HTP_POWERMODE_POWER_SAVER;
|
|
sleep_disable = 0u;
|
|
sleep_lat_us = 500u;
|
|
rpc_poll_us = 0u;
|
|
min_corner = QNN_HTP_VCORNER_SVS2;
|
|
tgt_corner = QNN_HTP_VCORNER_SVS;
|
|
max_corner = QNN_HTP_VCORNER_NOM;
|
|
hmx_min = QNN_HTP_EXP_VCORNER_LOW_SVS;
|
|
hmx_tgt = QNN_HTP_EXP_VCORNER_SVS;
|
|
hmx_max = QNN_HTP_EXP_VCORNER_SVS;
|
|
hmx_perf = QNN_HTP_CLK_PERF_LOW;
|
|
hmx_timeout_us = 250u;
|
|
} else if (!strcmp(eff_mode, "async_mid")) {
|
|
dcvs_mode = QNN_HTP_POWERMODE_POWER_SAVER;
|
|
sleep_disable = 0u;
|
|
sleep_lat_us = 200u;
|
|
rpc_poll_us = 0u;
|
|
min_corner = QNN_HTP_VCORNER_SVS2;
|
|
tgt_corner = QNN_HTP_VCORNER_NOM;
|
|
max_corner = QNN_HTP_VCORNER_NOM;
|
|
hmx_min = QNN_HTP_EXP_VCORNER_LOW_SVS;
|
|
hmx_tgt = QNN_HTP_EXP_VCORNER_NOM;
|
|
hmx_max = QNN_HTP_EXP_VCORNER_NOM;
|
|
hmx_perf = QNN_HTP_CLK_PERF_LOW;
|
|
hmx_timeout_us = 500u;
|
|
} else if (!strcmp(eff_mode, "burst")) {
|
|
dcvs_mode = QNN_HTP_POWERMODE_PERF;
|
|
sleep_disable = 1u;
|
|
sleep_lat_us = 100u;
|
|
rpc_poll_us = 9999u;
|
|
min_corner = QNN_HTP_VCORNER_MAX;
|
|
tgt_corner = QNN_HTP_VCORNER_MAX;
|
|
max_corner = QNN_HTP_VCORNER_MAX;
|
|
hmx_min = QNN_HTP_EXP_VCORNER_MAX;
|
|
hmx_tgt = QNN_HTP_EXP_VCORNER_MAX;
|
|
hmx_max = QNN_HTP_EXP_VCORNER_MAX;
|
|
hmx_timeout_us = 0u;
|
|
} else if (!strcmp(eff_mode, "turbo")) {
|
|
dcvs_mode = QNN_HTP_POWERMODE_PERF;
|
|
sleep_disable = 0u;
|
|
sleep_lat_us = 100u;
|
|
rpc_poll_us = 1000u;
|
|
min_corner = QNN_HTP_VCORNER_SVS;
|
|
tgt_corner = QNN_HTP_VCORNER_TURBO;
|
|
max_corner = QNN_HTP_VCORNER_MAX;
|
|
hmx_min = QNN_HTP_EXP_VCORNER_SVS;
|
|
hmx_tgt = QNN_HTP_EXP_VCORNER_TUR;
|
|
hmx_max = QNN_HTP_EXP_VCORNER_TUR;
|
|
hmx_timeout_us = 2000u;
|
|
} else if (!strcmp(eff_mode, "low")) {
|
|
dcvs_mode = QNN_HTP_POWERMODE_POWER_SAVER;
|
|
sleep_disable = 0u;
|
|
sleep_lat_us = 200u;
|
|
rpc_poll_us = 0u;
|
|
min_corner = QNN_HTP_VCORNER_SVS2;
|
|
tgt_corner = QNN_HTP_VCORNER_SVS;
|
|
max_corner = QNN_HTP_VCORNER_NOM;
|
|
hmx_min = QNN_HTP_EXP_VCORNER_LOW_SVS;
|
|
hmx_tgt = QNN_HTP_EXP_VCORNER_SVS;
|
|
hmx_max = QNN_HTP_EXP_VCORNER_SVS;
|
|
hmx_perf = QNN_HTP_CLK_PERF_LOW;
|
|
hmx_timeout_us = 250u;
|
|
}
|
|
|
|
QnnHtpPerfInfrastructure_PowerConfig_t dcvs, lat, poll, hmx, hmx_to;
|
|
memset(&dcvs, 0, sizeof dcvs);
|
|
dcvs.option = QNN_HTP_POWER_OPT_DCVS_V3;
|
|
dcvs.dcvsV3Config.contextId = rt->power_id;
|
|
dcvs.dcvsV3Config.setDcvsEnable = 1; dcvs.dcvsV3Config.dcvsEnable = is_idle ? 0u : 1u;
|
|
dcvs.dcvsV3Config.powerMode = dcvs_mode;
|
|
dcvs.dcvsV3Config.setSleepLatency = 1; dcvs.dcvsV3Config.sleepLatency = sleep_lat_us;
|
|
dcvs.dcvsV3Config.setSleepDisable = 1; dcvs.dcvsV3Config.sleepDisable = sleep_disable;
|
|
dcvs.dcvsV3Config.setBusParams = 1;
|
|
dcvs.dcvsV3Config.busVoltageCornerMin = min_corner;
|
|
dcvs.dcvsV3Config.busVoltageCornerTarget = tgt_corner;
|
|
dcvs.dcvsV3Config.busVoltageCornerMax = max_corner;
|
|
dcvs.dcvsV3Config.setCoreParams = 1;
|
|
dcvs.dcvsV3Config.coreVoltageCornerMin = min_corner;
|
|
dcvs.dcvsV3Config.coreVoltageCornerTarget = tgt_corner;
|
|
dcvs.dcvsV3Config.coreVoltageCornerMax = max_corner;
|
|
|
|
memset(&lat, 0, sizeof lat);
|
|
lat.option = QNN_HTP_POWER_OPT_RPC_CONTROL_LATENCY;
|
|
lat.rpcControlLatencyConfig = sleep_lat_us;
|
|
|
|
memset(&poll, 0, sizeof poll);
|
|
poll.option = QNN_HTP_POWER_OPT_RPC_POLLING_TIME;
|
|
poll.rpcPollingTimeConfig = rpc_poll_us;
|
|
|
|
memset(&hmx, 0, sizeof hmx);
|
|
hmx.option = QNN_HTP_POWER_OPT_HMX_V2;
|
|
hmx.hmxV2Config.hmxPickDefault = 0;
|
|
hmx.hmxV2Config.hmxVoltageCornerMin = hmx_min;
|
|
hmx.hmxV2Config.hmxVoltageCornerTarget = hmx_tgt;
|
|
hmx.hmxV2Config.hmxVoltageCornerMax = hmx_max;
|
|
hmx.hmxV2Config.hmxPerfMode = hmx_perf;
|
|
|
|
memset(&hmx_to, 0, sizeof hmx_to);
|
|
hmx_to.option = QNN_HTP_POWER_OPT_HMX_TIMEOUT_INTERVAL_US;
|
|
hmx_to.hmxTimeoutIntervalUsConfig = hmx_timeout_us;
|
|
|
|
int applied_hmx_to = 0;
|
|
Qnn_ErrorHandle_t rc = 1;
|
|
if (hmx_timeout_us > 0u) {
|
|
const QnnHtpPerfInfrastructure_PowerConfig_t *cfgs5[] = {&dcvs, &lat, &poll, &hmx, &hmx_to, NULL};
|
|
rc = rt->perf->setPowerConfig(rt->power_id, cfgs5);
|
|
if (rc == QNN_SUCCESS_CODE) applied_hmx_to = 1;
|
|
}
|
|
if (rc != QNN_SUCCESS_CODE) {
|
|
const QnnHtpPerfInfrastructure_PowerConfig_t *cfgs4[] = {&dcvs, &lat, &poll, &hmx, NULL};
|
|
rc = rt->perf->setPowerConfig(rt->power_id, cfgs4);
|
|
}
|
|
if (rc != QNN_SUCCESS_CODE) {
|
|
const QnnHtpPerfInfrastructure_PowerConfig_t *cfgs3[] = {&dcvs, &lat, &poll, NULL};
|
|
rc = rt->perf->setPowerConfig(rt->power_id, cfgs3);
|
|
}
|
|
if (rc != QNN_SUCCESS_CODE) return -1;
|
|
|
|
if (rt->power_mode != eff_mode) {
|
|
snprintf(rt->power_mode, sizeof rt->power_mode, "%s", eff_mode);
|
|
}
|
|
F4_LOGI("QNN HTP power profile='%s' sleepDisable=%u sleepLat=%uus rpcPoll=%uus hmxTo=%uus(%d) core=0x%x..0x%x..0x%x hmx=0x%x..0x%x..0x%x",
|
|
eff_mode, sleep_disable, sleep_lat_us, rpc_poll_us, hmx_timeout_us, applied_hmx_to,
|
|
min_corner, tgt_corner, max_corner, hmx_min, hmx_tgt, hmx_max);
|
|
return 0;
|
|
}
|
|
|
|
int wl_fsr4_qnn_set_power_mode(const char *power_mode) {
|
|
if (!power_mode || !*power_mode) return -1;
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
// Prevent a dormant worker thread (e.g. Full NPU after switching to Lite NPU, or vice versa)
|
|
// from wiping shared HTP voltage corners to "idle" while another NPU graph is actively running!
|
|
if (strcmp(power_mode, "idle") == 0 && g_rt.last_exec_ms > 0.0 &&
|
|
(mono_ms() - g_rt.last_exec_ms) < 450.0) {
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
return 0;
|
|
}
|
|
int rc = -1;
|
|
if (g_rt.refs > 0 && g_rt.has_power_id && g_rt.perf) {
|
|
rc = apply_power_profile(&g_rt, power_mode);
|
|
}
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
return rc;
|
|
}
|
|
|
|
const char *wl_fsr4_qnn_get_power_mode(void) {
|
|
return g_rt.power_mode[0] ? g_rt.power_mode : "balanced";
|
|
}
|
|
|
|
void wl_fsr4_pin_worker_non_prime(const char *worker_name) {
|
|
long ncpus_l = sysconf(_SC_NPROCESSORS_CONF);
|
|
int ncpus = (ncpus_l > 0 && ncpus_l <= 32) ? (int)ncpus_l : 8;
|
|
if (ncpus < 4) return;
|
|
|
|
long freqs[32];
|
|
long max_freq = 0;
|
|
int freq_count = 0;
|
|
for (int i = 0; i < ncpus; i++) {
|
|
freqs[i] = 0;
|
|
char path[96];
|
|
snprintf(path, sizeof path, "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq", i);
|
|
FILE *f = fopen(path, "r");
|
|
if (f) {
|
|
long khz = 0;
|
|
if (fscanf(f, "%ld", &khz) == 1 && khz > 0) {
|
|
freqs[i] = khz;
|
|
if (khz > max_freq) max_freq = khz;
|
|
freq_count++;
|
|
}
|
|
fclose(f);
|
|
}
|
|
}
|
|
|
|
cpu_set_t cpuset;
|
|
CPU_ZERO(&cpuset);
|
|
int pinned = 0;
|
|
uint32_t mask = 0u;
|
|
if (freq_count >= 4 && max_freq > 0) {
|
|
for (int i = 0; i < ncpus; i++) {
|
|
if (freqs[i] > 0 && freqs[i] < max_freq) {
|
|
CPU_SET(i, &cpuset);
|
|
mask |= (1u << i);
|
|
pinned++;
|
|
}
|
|
}
|
|
}
|
|
// Fallback if cpufreq sysfs is unreadable on non-root / strict SELinux: exclude top 2 Prime CPUs on 8-core SoCs
|
|
if (pinned < 2 && ncpus >= 8) {
|
|
CPU_ZERO(&cpuset);
|
|
pinned = 0;
|
|
mask = 0u;
|
|
int limit = ncpus - 2;
|
|
if (limit > 6) limit = 6;
|
|
for (int i = 0; i < limit; i++) {
|
|
CPU_SET(i, &cpuset);
|
|
mask |= (1u << i);
|
|
pinned++;
|
|
}
|
|
}
|
|
if (pinned >= 2) {
|
|
if (sched_setaffinity(0, sizeof cpuset, &cpuset) == 0) {
|
|
F4_LOGI("Pinned %s worker to %d non-Prime CPUs (mask=0x%x, max_prime=%ldkHz)",
|
|
worker_name ? worker_name : "npu", pinned, mask, max_freq);
|
|
}
|
|
}
|
|
}
|
|
|
|
static void rt_teardown_locked(void) {
|
|
qnn_rt *rt = &g_rt;
|
|
if (rt->has_power_id && rt->perf) {
|
|
QnnHtpPerfInfrastructure_PowerConfig_t dcvs, hmx;
|
|
memset(&dcvs, 0, sizeof dcvs);
|
|
dcvs.option = QNN_HTP_POWER_OPT_DCVS_V3;
|
|
dcvs.dcvsV3Config.contextId = rt->power_id;
|
|
dcvs.dcvsV3Config.setDcvsEnable = 1;
|
|
dcvs.dcvsV3Config.setSleepLatency = 1;
|
|
dcvs.dcvsV3Config.setSleepDisable = 1;
|
|
dcvs.dcvsV3Config.setBusParams = 1;
|
|
dcvs.dcvsV3Config.busVoltageCornerMin = QNN_HTP_VCORNER_DISABLE;
|
|
dcvs.dcvsV3Config.busVoltageCornerTarget = QNN_HTP_VCORNER_DISABLE;
|
|
dcvs.dcvsV3Config.busVoltageCornerMax = QNN_HTP_VCORNER_DISABLE;
|
|
dcvs.dcvsV3Config.setCoreParams = 1;
|
|
dcvs.dcvsV3Config.coreVoltageCornerMin = QNN_HTP_VCORNER_DISABLE;
|
|
dcvs.dcvsV3Config.coreVoltageCornerTarget = QNN_HTP_VCORNER_DISABLE;
|
|
dcvs.dcvsV3Config.coreVoltageCornerMax = QNN_HTP_VCORNER_DISABLE;
|
|
memset(&hmx, 0, sizeof hmx);
|
|
hmx.option = QNN_HTP_POWER_OPT_HMX_V2;
|
|
hmx.hmxV2Config.hmxVoltageCornerMin = QNN_HTP_EXP_VCORNER_DISABLE;
|
|
hmx.hmxV2Config.hmxVoltageCornerTarget = QNN_HTP_EXP_VCORNER_DISABLE;
|
|
hmx.hmxV2Config.hmxVoltageCornerMax = QNN_HTP_EXP_VCORNER_DISABLE;
|
|
const QnnHtpPerfInfrastructure_PowerConfig_t *cfgs[] = {&dcvs, &hmx, NULL};
|
|
if (rt->perf->setPowerConfig) rt->perf->setPowerConfig(rt->power_id, cfgs);
|
|
if (rt->perf->destroyPowerConfigId) rt->perf->destroyPowerConfigId(rt->power_id);
|
|
rt->has_power_id = 0;
|
|
}
|
|
if (rt->device && rt->Q && rt->Q->deviceFree) rt->Q->deviceFree(rt->device);
|
|
if (rt->backend && rt->Q && rt->Q->backendFree) rt->Q->backendFree(rt->backend);
|
|
if (rt->logger && rt->Q && rt->Q->logFree) rt->Q->logFree(rt->logger);
|
|
if (rt->lib_prep) dlclose(rt->lib_prep);
|
|
if (rt->lib_htp) dlclose(rt->lib_htp);
|
|
if (rt->lib_sys) dlclose(rt->lib_sys);
|
|
for (int i = 0; i < 2; i++) if (rt->lib_stub[i]) dlclose(rt->lib_stub[i]);
|
|
if (rt->lib_cdsp) dlclose(rt->lib_cdsp);
|
|
memset(rt, 0, sizeof *rt);
|
|
pthread_mutex_lock(&g_htp_arch_mu);
|
|
g_htp_rt_up = 0;
|
|
g_htp_stubs_preloaded_all = 0;
|
|
pthread_mutex_unlock(&g_htp_arch_mu);
|
|
}
|
|
|
|
static int rt_acquire_locked(const char *fsr4_dir, const char *power_mode) {
|
|
if (g_rt.refs > 0) {
|
|
g_rt.refs++;
|
|
return 1;
|
|
}
|
|
memset(&g_rt, 0, sizeof g_rt);
|
|
g_rt.dline = query_dcache_line();
|
|
snprintf(g_rt.power_mode, sizeof g_rt.power_mode, "%s", (power_mode && *power_mode) ? power_mode : "balanced");
|
|
|
|
ensure_adsp_path(fsr4_dir);
|
|
F4_LOGI("HTP %s: %s QNN libraries", htp_arch_for_dir(fsr4_dir), use_bundled_qnn(fsr4_dir) ? "bundled" : "this device's own");
|
|
request_unsigned_pd(&g_rt);
|
|
preload_htp_stubs(&g_rt, fsr4_dir);
|
|
|
|
g_rt.lib_sys = dlopen_qnn_lib(fsr4_dir, "libQnnSystem.so");
|
|
if (!g_rt.lib_sys) {
|
|
set_qnn_err("qnn_dlopen_sys");
|
|
F4_LOGE("dlopen libQnnSystem.so failed (dir=%s): %s", fsr4_dir, dlerror());
|
|
rt_teardown_locked();
|
|
return 0;
|
|
}
|
|
g_rt.lib_htp = dlopen_qnn_lib(fsr4_dir, "libQnnHtp.so");
|
|
if (!g_rt.lib_htp) {
|
|
set_qnn_err("qnn_dlopen_htp");
|
|
F4_LOGE("dlopen libQnnHtp.so failed (dir=%s): %s", fsr4_dir, dlerror());
|
|
rt_teardown_locked();
|
|
return 0;
|
|
}
|
|
|
|
pfn_qnn_sys_get_providers sys_gp = (pfn_qnn_sys_get_providers)dlsym(g_rt.lib_sys, "QnnSystemInterface_getProviders");
|
|
pfn_qnn_get_providers qnn_gp = (pfn_qnn_get_providers)dlsym(g_rt.lib_htp, "QnnInterface_getProviders");
|
|
const QnnSystemInterface_t **slist = NULL;
|
|
const QnnInterface_t **qlist = NULL;
|
|
uint32_t nsys = 0, nqnn = 0;
|
|
if (!sys_gp || !qnn_gp || sys_gp(&slist, &nsys) != QNN_SUCCESS_CODE || qnn_gp(&qlist, &nqnn) != QNN_SUCCESS_CODE) {
|
|
set_qnn_err("qnn_providers");
|
|
F4_LOGE("QNN provider discovery failed");
|
|
rt_teardown_locked();
|
|
return 0;
|
|
}
|
|
|
|
for (uint32_t i = 0; i < nsys; i++) {
|
|
if (slist[i] && slist[i]->systemApiVersion.major == 1) { g_rt.S = &slist[i]->v1_11; break; }
|
|
}
|
|
for (uint32_t i = 0; i < nqnn; i++) {
|
|
if (qlist[i] && qlist[i]->apiVersion.coreApiVersion.major == 2) { g_rt.Q = &qlist[i]->v2_36; break; }
|
|
}
|
|
if (!g_rt.S || !g_rt.Q || !g_rt.S->systemContextCreate || !g_rt.S->systemContextGetBinaryInfo || !g_rt.S->systemContextFree ||
|
|
!g_rt.Q->backendCreate || !g_rt.Q->deviceCreate || !g_rt.Q->contextCreateFromBinary ||
|
|
!g_rt.Q->graphRetrieve || !g_rt.Q->graphExecute || !g_rt.Q->memRegister) {
|
|
set_qnn_err("qnn_iface_fns");
|
|
F4_LOGE("missing required QNN interface functions");
|
|
rt_teardown_locked();
|
|
return 0;
|
|
}
|
|
|
|
if (g_rt.Q->logCreate) {
|
|
uint32_t qll = qnn_log_verbose() ? QNN_LOG_LEVEL_INFO : QNN_LOG_LEVEL_WARN;
|
|
g_rt.Q->logCreate(qnn_log_cb, qll, &g_rt.logger);
|
|
}
|
|
Qnn_ErrorHandle_t be = g_rt.Q->backendCreate(g_rt.logger, NULL, &g_rt.backend);
|
|
if (be != QNN_SUCCESS_CODE || !g_rt.backend) {
|
|
set_qnn_err("qnn_backend_0x%llx", (unsigned long long)be);
|
|
F4_LOGE("backendCreate failed rc=0x%llx", (unsigned long long)be);
|
|
rt_teardown_locked();
|
|
return 0;
|
|
}
|
|
|
|
QnnHtpDevice_CustomConfig_t pd_cfg;
|
|
memset(&pd_cfg, 0, sizeof pd_cfg);
|
|
pd_cfg.option = QNN_HTP_DEVICE_CONFIG_OPTION_SIGNEDPD;
|
|
pd_cfg.useSignedProcessDomain.deviceId = 0;
|
|
pd_cfg.useSignedProcessDomain.useSignedProcessDomain = false;
|
|
QnnDevice_Config_t dev_cfg;
|
|
memset(&dev_cfg, 0, sizeof dev_cfg);
|
|
dev_cfg.option = QNN_DEVICE_CONFIG_OPTION_CUSTOM;
|
|
dev_cfg.customConfig = &pd_cfg;
|
|
const QnnDevice_Config_t *dev_cfgs[] = {&dev_cfg, NULL};
|
|
Qnn_ErrorHandle_t de = g_rt.Q->deviceCreate(g_rt.logger, dev_cfgs, &g_rt.device);
|
|
if (de != QNN_SUCCESS_CODE || !g_rt.device) {
|
|
F4_LOGW("deviceCreate(unsignedPD) rc=0x%llx; retrying with default device config", (unsigned long long)de);
|
|
g_rt.device = NULL;
|
|
de = g_rt.Q->deviceCreate(g_rt.logger, NULL, &g_rt.device);
|
|
}
|
|
if (de != QNN_SUCCESS_CODE || !g_rt.device) {
|
|
set_qnn_err("qnn_dev_0x%llx", (unsigned long long)de);
|
|
F4_LOGE("deviceCreate failed rc=0x%llx", (unsigned long long)de);
|
|
rt_teardown_locked();
|
|
return 0;
|
|
}
|
|
|
|
if (apply_power_profile(&g_rt, g_rt.power_mode) == 0)
|
|
F4_LOGI("HTP %s runtime initialized (power=%s)", htp_arch_for_dir(fsr4_dir), g_rt.power_mode);
|
|
else
|
|
F4_LOGI("HTP %s runtime initialized without perf vote", htp_arch_for_dir(fsr4_dir));
|
|
|
|
g_rt.refs = 1;
|
|
pthread_mutex_lock(&g_htp_arch_mu);
|
|
g_htp_rt_up = 1;
|
|
pthread_mutex_unlock(&g_htp_arch_mu);
|
|
return 1;
|
|
}
|
|
|
|
static void rt_release_locked(void) {
|
|
if (g_rt.refs <= 0) return;
|
|
if (--g_rt.refs == 0) rt_teardown_locked();
|
|
}
|
|
|
|
static uint8_t *read_bin_file(const char *path, size_t *out_sz) {
|
|
FILE *f = fopen(path, "rb");
|
|
if (!f) return NULL;
|
|
if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return NULL; }
|
|
long len = ftell(f);
|
|
if (len <= 0 || len > 128L * 1024L * 1024L || fseek(f, 0, SEEK_SET) != 0) { fclose(f); return NULL; }
|
|
uint8_t *buf = (uint8_t *)malloc((size_t)len);
|
|
if (!buf) { fclose(f); return NULL; }
|
|
size_t got = fread(buf, 1, (size_t)len, f);
|
|
fclose(f);
|
|
if (got != (size_t)len) { free(buf); return NULL; }
|
|
*out_sz = (size_t)len;
|
|
return buf;
|
|
}
|
|
|
|
static void tensor_fields(const Qnn_Tensor_t *t, uint32_t *rank, uint32_t **dims, uint32_t *dtype, const char **name, uint8_t **dyn, Qnn_QuantizeParams_t **qp) {
|
|
if (t->version == QNN_TENSOR_VERSION_2) {
|
|
if (rank) *rank = t->v2.rank;
|
|
if (dims) *dims = t->v2.dimensions;
|
|
if (dtype) *dtype = t->v2.dataType;
|
|
if (name) *name = t->v2.name;
|
|
if (dyn) *dyn = t->v2.isDynamicDimensions;
|
|
if (qp) *qp = (Qnn_QuantizeParams_t *)&t->v2.quantizeParams;
|
|
} else {
|
|
if (rank) *rank = t->v1.rank;
|
|
if (dims) *dims = t->v1.dimensions;
|
|
if (dtype) *dtype = t->v1.dataType;
|
|
if (name) *name = t->v1.name;
|
|
if (dyn) *dyn = NULL;
|
|
if (qp) *qp = (Qnn_QuantizeParams_t *)&t->v1.quantizeParams;
|
|
}
|
|
}
|
|
|
|
static int clone_tensor(const Qnn_Tensor_t *src, Qnn_Tensor_t *dst, char **name_out, uint32_t **dims_out, uint8_t **dyn_out, void **qextra_out) {
|
|
*dst = *src;
|
|
uint32_t rank = 0, dtype = 0;
|
|
uint32_t *sdims = NULL;
|
|
uint8_t *sdyn = NULL;
|
|
const char *sname = NULL;
|
|
Qnn_QuantizeParams_t *sqp = NULL;
|
|
tensor_fields(src, &rank, &sdims, &dtype, &sname, &sdyn, &sqp);
|
|
(void)dtype;
|
|
if (rank > 8) return 0;
|
|
|
|
char *nc = sname ? strdup(sname) : strdup("");
|
|
uint32_t *dc = (rank && sdims) ? (uint32_t *)malloc(rank * sizeof(uint32_t)) : NULL;
|
|
uint8_t *dyc = (rank && sdyn) ? (uint8_t *)malloc(rank) : NULL;
|
|
if (!nc || (rank && sdims && !dc) || (rank && sdyn && !dyc)) {
|
|
free(nc); free(dc); free(dyc);
|
|
return 0;
|
|
}
|
|
if (dc) memcpy(dc, sdims, rank * sizeof(uint32_t));
|
|
if (dyc) memcpy(dyc, sdyn, rank);
|
|
|
|
void *qx = NULL;
|
|
Qnn_QuantizeParams_t qp = *sqp;
|
|
if (qp.encodingDefinition == QNN_DEFINITION_DEFINED && qp.quantizationEncoding == QNN_QUANT_ENC_AXIS_SCALE_OFFSET &&
|
|
qp.axisScaleOffsetEncoding.numScaleOffsets && qp.axisScaleOffsetEncoding.scaleOffset) {
|
|
size_t bytes = qp.axisScaleOffsetEncoding.numScaleOffsets * sizeof(Qnn_ScaleOffset_t);
|
|
qx = malloc(bytes);
|
|
if (!qx) { free(nc); free(dc); free(dyc); return 0; }
|
|
memcpy(qx, qp.axisScaleOffsetEncoding.scaleOffset, bytes);
|
|
qp.axisScaleOffsetEncoding.scaleOffset = (Qnn_ScaleOffset_t *)qx;
|
|
}
|
|
|
|
if (dst->version == QNN_TENSOR_VERSION_2) {
|
|
dst->v2.name = nc;
|
|
dst->v2.dimensions = dc;
|
|
dst->v2.isDynamicDimensions = dyc;
|
|
dst->v2.quantizeParams = qp;
|
|
} else {
|
|
dst->v1.name = nc;
|
|
dst->v1.dimensions = dc;
|
|
dst->v1.quantizeParams = qp;
|
|
}
|
|
*name_out = nc;
|
|
*dims_out = dc;
|
|
*dyn_out = dyc;
|
|
*qextra_out = qx;
|
|
return 1;
|
|
}
|
|
|
|
static void graph_unload_locked(qnn_graph *g) {
|
|
for (int s = 0; s < 2; s++) {
|
|
if (g->in_mh[s]) { if (g_rt.Q && g_rt.Q->memDeRegister) g_rt.Q->memDeRegister(&g->in_mh[s], 1); g->in_mh[s] = NULL; }
|
|
if (g->out_mh[s]) { if (g_rt.Q && g_rt.Q->memDeRegister) g_rt.Q->memDeRegister(&g->out_mh[s], 1); g->out_mh[s] = NULL; }
|
|
}
|
|
if (g->ctx) { if (g_rt.Q && g_rt.Q->contextFree) g_rt.Q->contextFree(g->ctx, NULL); g->ctx = NULL; }
|
|
for (int k = 0; k < 4; k++) {
|
|
free(g->names[k]); g->names[k] = NULL;
|
|
free(g->dims[k]); g->dims[k] = NULL;
|
|
free(g->dyns[k]); g->dyns[k] = NULL;
|
|
free(g->qextra[k]); g->qextra[k] = NULL;
|
|
}
|
|
g->graph = NULL;
|
|
g->nslots = 0;
|
|
g->ready = 0;
|
|
}
|
|
|
|
static int graph_load_locked(qnn_graph *g, const char *dir, const char *file, const qnn_ahb *buf,
|
|
int nslots, const uint64_t *in_offs, const uint64_t *out_offs) {
|
|
if (g->ready) return 1;
|
|
if (nslots < 1 || nslots > 2) return 0;
|
|
|
|
char path[600];
|
|
snprintf(path, sizeof path, "%s/%s", dir, file);
|
|
size_t bin_sz = 0;
|
|
uint8_t *bin = read_bin_file(path, &bin_sz);
|
|
if (!bin) {
|
|
F4_LOGE("cannot read graph binary %s", path);
|
|
return 0;
|
|
}
|
|
|
|
QnnSystemContext_Handle_t sys_ctx = NULL;
|
|
if (g_rt.S->systemContextCreate(&sys_ctx) != QNN_SUCCESS_CODE || !sys_ctx) {
|
|
set_qnn_err("qnn_sysctx");
|
|
free(bin);
|
|
return 0;
|
|
}
|
|
|
|
const QnnSystemContext_BinaryInfo_t *bi = NULL;
|
|
Qnn_ContextBinarySize_t bi_sz = 0;
|
|
Qnn_ErrorHandle_t bie = g_rt.S->systemContextGetBinaryInfo(sys_ctx, bin, (uint64_t)bin_sz, &bi, &bi_sz);
|
|
if (bie != QNN_SUCCESS_CODE || !bi) {
|
|
set_qnn_err("qnn_bininfo_0x%llx", (unsigned long long)bie);
|
|
g_rt.S->systemContextFree(sys_ctx);
|
|
free(bin);
|
|
return 0;
|
|
}
|
|
|
|
uint32_t ngraphs = 0;
|
|
QnnSystemContext_GraphInfo_t *graphs = NULL;
|
|
if (bi->version == 1) { ngraphs = bi->contextBinaryInfoV1.numGraphs; graphs = bi->contextBinaryInfoV1.graphs; }
|
|
else if (bi->version == 2) { ngraphs = bi->contextBinaryInfoV2.numGraphs; graphs = bi->contextBinaryInfoV2.graphs; }
|
|
else if (bi->version == 3) { ngraphs = bi->contextBinaryInfoV3.numGraphs; graphs = bi->contextBinaryInfoV3.graphs; }
|
|
if (!ngraphs || !graphs) {
|
|
set_qnn_err("qnn_nographs");
|
|
g_rt.S->systemContextFree(sys_ctx);
|
|
free(bin);
|
|
return 0;
|
|
}
|
|
|
|
const char *gname = NULL;
|
|
uint32_t nin = 0, nout = 0;
|
|
Qnn_Tensor_t *gin = NULL, *gout = NULL;
|
|
if (graphs[0].version == 1) {
|
|
gname = graphs[0].graphInfoV1.graphName;
|
|
nin = graphs[0].graphInfoV1.numGraphInputs; gin = graphs[0].graphInfoV1.graphInputs;
|
|
nout = graphs[0].graphInfoV1.numGraphOutputs; gout = graphs[0].graphInfoV1.graphOutputs;
|
|
} else if (graphs[0].version == 2) {
|
|
gname = graphs[0].graphInfoV2.graphName;
|
|
nin = graphs[0].graphInfoV2.numGraphInputs; gin = graphs[0].graphInfoV2.graphInputs;
|
|
nout = graphs[0].graphInfoV2.numGraphOutputs; gout = graphs[0].graphInfoV2.graphOutputs;
|
|
} else if (graphs[0].version == 3) {
|
|
gname = graphs[0].graphInfoV3.graphName;
|
|
nin = graphs[0].graphInfoV3.numGraphInputs; gin = graphs[0].graphInfoV3.graphInputs;
|
|
nout = graphs[0].graphInfoV3.numGraphOutputs; gout = graphs[0].graphInfoV3.graphOutputs;
|
|
}
|
|
if (!gname || nin < 1 || nout < 1 || !gin || !gout) {
|
|
set_qnn_err("qnn_ginfo");
|
|
g_rt.S->systemContextFree(sys_ctx);
|
|
free(bin);
|
|
return 0;
|
|
}
|
|
|
|
char gname_copy[256];
|
|
snprintf(gname_copy, sizeof gname_copy, "%s", gname);
|
|
|
|
for (int s = 0; s < nslots; s++) {
|
|
if (!clone_tensor(&gin[0], &g->in_t[s], &g->names[s], &g->dims[s], &g->dyns[s], &g->qextra[s]) ||
|
|
!clone_tensor(&gout[0], &g->out_t[s], &g->names[2 + s], &g->dims[2 + s], &g->dyns[2 + s], &g->qextra[2 + s])) {
|
|
set_qnn_err("qnn_clone");
|
|
g_rt.S->systemContextFree(sys_ctx);
|
|
free(bin);
|
|
graph_unload_locked(g);
|
|
return 0;
|
|
}
|
|
}
|
|
g_rt.S->systemContextFree(sys_ctx);
|
|
|
|
Qnn_ErrorHandle_t ce = g_rt.Q->contextCreateFromBinary(g_rt.backend, g_rt.device, NULL, bin, (uint64_t)bin_sz, &g->ctx, NULL);
|
|
free(bin);
|
|
if (ce != QNN_SUCCESS_CODE || !g->ctx) {
|
|
set_qnn_err("qnn_loadctx_0x%llx", (unsigned long long)ce);
|
|
F4_LOGE("contextCreateFromBinary(%s) failed rc=0x%llx", file, (unsigned long long)ce);
|
|
graph_unload_locked(g);
|
|
return 0;
|
|
}
|
|
Qnn_ErrorHandle_t re = g_rt.Q->graphRetrieve(g->ctx, gname_copy, &g->graph);
|
|
if (re != QNN_SUCCESS_CODE || !g->graph) {
|
|
set_qnn_err("qnn_retrieve_0x%llx", (unsigned long long)re);
|
|
F4_LOGE("graphRetrieve(%s) failed rc=0x%llx", gname_copy, (unsigned long long)re);
|
|
graph_unload_locked(g);
|
|
return 0;
|
|
}
|
|
|
|
int use_raw_fallback = (buf->dmabuf_fd < 0);
|
|
for (int s = 0; s < nslots; s++) {
|
|
Qnn_Tensor_t *ts[2] = {&g->in_t[s], &g->out_t[s]};
|
|
Qnn_MemHandle_t *mhs[2] = {&g->in_mh[s], &g->out_mh[s]};
|
|
uint64_t offs[2] = {in_offs[s], out_offs[s]};
|
|
|
|
for (int io = 0; io < 2; io++) {
|
|
uint32_t rank = 0, dtype = 0;
|
|
uint32_t *dims = NULL;
|
|
tensor_fields(ts[io], &rank, &dims, &dtype, NULL, NULL, NULL);
|
|
|
|
int reg_ok = 0;
|
|
if (!use_raw_fallback) {
|
|
QnnMemHtp_Descriptor_t hd;
|
|
memset(&hd, 0, sizeof hd);
|
|
hd.type = QNN_HTP_MEM_SHARED_BUFFER;
|
|
hd.size = (uint64_t)buf->bytes;
|
|
hd.sharedBufferConfig.fd = buf->dmabuf_fd;
|
|
hd.sharedBufferConfig.offset = offs[io];
|
|
|
|
Qnn_MemDescriptor_t md;
|
|
memset(&md, 0, sizeof md);
|
|
md.memShape.numDim = rank;
|
|
md.memShape.dimSize = dims;
|
|
md.dataType = dtype;
|
|
md.memType = QNN_MEM_TYPE_CUSTOM;
|
|
md.customInfo = &hd;
|
|
|
|
Qnn_ErrorHandle_t mr = g_rt.Q->memRegister(g->ctx, &md, 1, mhs[io]);
|
|
if (mr == QNN_SUCCESS_CODE && *mhs[io]) {
|
|
reg_ok = 1;
|
|
if (ts[io]->version == QNN_TENSOR_VERSION_2) {
|
|
ts[io]->v2.memType = QNN_TENSORMEMTYPE_MEMHANDLE;
|
|
ts[io]->v2.memHandle = *mhs[io];
|
|
} else {
|
|
ts[io]->v1.memType = QNN_TENSORMEMTYPE_MEMHANDLE;
|
|
ts[io]->v1.memHandle = *mhs[io];
|
|
}
|
|
} else {
|
|
F4_LOGW("memRegister(%s slot=%d io=%d) rc=0x%llx; falling back to QNN RAW clientBuf",
|
|
file, s, io, (unsigned long long)mr);
|
|
use_raw_fallback = 1;
|
|
}
|
|
}
|
|
if (!reg_ok) {
|
|
size_t elem_sz = 1u;
|
|
if (dtype == QNN_DATATYPE_FLOAT_16 || dtype == 0x0316 || dtype == 0x0416) elem_sz = 2u;
|
|
else if (dtype == QNN_DATATYPE_FLOAT_32 || dtype == QNN_DATATYPE_INT_32 ||
|
|
dtype == QNN_DATATYPE_UINT_32 || dtype == QNN_DATATYPE_SFIXED_POINT_32) elem_sz = 4u;
|
|
size_t nbytes = elem_sz;
|
|
for (uint32_t d = 0; d < rank && dims; d++) nbytes *= dims[d];
|
|
if (ts[io]->version == QNN_TENSOR_VERSION_2) {
|
|
ts[io]->v2.memType = QNN_TENSORMEMTYPE_RAW;
|
|
ts[io]->v2.clientBuf.data = buf->mapped + offs[io];
|
|
ts[io]->v2.clientBuf.dataSize = (uint32_t)nbytes;
|
|
} else {
|
|
ts[io]->v1.memType = QNN_TENSORMEMTYPE_RAW;
|
|
ts[io]->v1.clientBuf.data = buf->mapped + offs[io];
|
|
ts[io]->v1.clientBuf.dataSize = (uint32_t)nbytes;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
g->nslots = nslots;
|
|
g->ready = 1;
|
|
F4_LOGI("loaded HTP graph %s (%s)", file, gname_copy);
|
|
return 1;
|
|
}
|
|
|
|
static int load_sr_preset_locked(wl_fsr4_qnn *q, int preset) {
|
|
if (preset < 0 || preset > 1) return 0;
|
|
const char *file = (preset == WL_FSR4_PRESET_ULTRAPERF) ? "v81/nf4up_k1h.bin" : "v81/nf4_k1h.bin";
|
|
uint64_t in_offs[2] = {0u, (uint64_t)WL_FSR4_TENSOR_BYTES};
|
|
uint64_t out_offs[2] = {2u * (uint64_t)WL_FSR4_TENSOR_BYTES, 3u * (uint64_t)WL_FSR4_TENSOR_BYTES};
|
|
return graph_load_locked(&q->presets[preset], q->dir, file, &q->buf, 2, in_offs, out_offs);
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init(const char *fsr4_dir, int preset, const char *power_mode) {
|
|
if (!fsr4_dir || !*fsr4_dir) return NULL;
|
|
wl_fsr4_qnn *q = (wl_fsr4_qnn *)calloc(1, sizeof *q);
|
|
if (!q) return NULL;
|
|
q->buf.dmabuf_fd = -1;
|
|
q->dline = query_dcache_line();
|
|
snprintf(q->dir, sizeof q->dir, "%s", fsr4_dir);
|
|
|
|
if (!qnn_ahb_alloc(&q->buf, WL_FSR4_AHB_BYTES, q->dline)) {
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
if (!rt_acquire_locked(fsr4_dir, power_mode)) {
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
q->has_rt = 1;
|
|
int ok = load_sr_preset_locked(q, preset);
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
|
|
if (!ok) {
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
F4_LOGI("HTP v81 SR ready (ahb=%u B, dmabuf=%d)", WL_FSR4_AHB_BYTES, q->buf.dmabuf_fd);
|
|
return q;
|
|
}
|
|
|
|
int wl_fsr4_qnn_load_preset(wl_fsr4_qnn *q, int preset) {
|
|
if (!q) return 0;
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
int ok = load_sr_preset_locked(q, preset);
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
return ok;
|
|
}
|
|
|
|
void *wl_fsr4_qnn_ahb(const wl_fsr4_qnn *q) { return q ? q->buf.ahb : NULL; }
|
|
void *wl_fsr4_qnn_mapped(const wl_fsr4_qnn *q) { return q ? q->buf.mapped : NULL; }
|
|
int wl_fsr4_qnn_dmabuf_fd(const wl_fsr4_qnn *q) { return q ? q->buf.dmabuf_fd : -1; }
|
|
|
|
int wl_fsr4_qnn_exec(wl_fsr4_qnn *q, int preset, int slot, double *out_ms) {
|
|
if (!q || preset < 0 || preset > 1 || (slot != 0 && slot != 1)) return 0;
|
|
uint64_t off_in = (uint64_t)slot * WL_FSR4_TENSOR_BYTES;
|
|
uint64_t off_out = (uint64_t)(2 + slot) * WL_FSR4_TENSOR_BYTES;
|
|
civac_range(q->buf.mapped + off_in, WL_FSR4_TENSOR_BYTES, q->dline);
|
|
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
qnn_graph *p = &q->presets[preset];
|
|
if (!p->ready && !load_sr_preset_locked(q, preset)) {
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
return 0;
|
|
}
|
|
double t0 = mono_ms();
|
|
g_rt.last_exec_ms = t0;
|
|
Qnn_ErrorHandle_t qe = g_rt.Q->graphExecute(p->graph, &p->in_t[slot], 1, &p->out_t[slot], 1, NULL, NULL);
|
|
double t1 = mono_ms();
|
|
g_rt.last_exec_ms = t1;
|
|
double dt = t1 - t0;
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
|
|
civac_range(q->buf.mapped + off_out, WL_FSR4_TENSOR_BYTES, q->dline);
|
|
if (out_ms) *out_ms = dt;
|
|
if (qe != QNN_SUCCESS_CODE) {
|
|
F4_LOGE("QnnGraph_execute failed rc=0x%llx", (unsigned long long)qe);
|
|
return 0;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
// ============================================================================
|
|
// Built-in self-contained AMD FSR 4.0.2 INT8 on-device QNN HTP compiler
|
|
// ============================================================================
|
|
#define WPK_MAGIC 0x314B505734525346ULL /* "FSR4WPK1" */
|
|
|
|
enum {
|
|
WPK_TK_APP_WRITE = 0,
|
|
WPK_TK_APP_READ = 1,
|
|
WPK_TK_NATIVE = 2,
|
|
WPK_TK_STATIC_U8 = 3,
|
|
WPK_TK_STATIC_S32 = 4,
|
|
WPK_TK_APP_WRITE_S8 = 5,
|
|
WPK_TK_APP_READ_S8 = 6,
|
|
WPK_TK_NATIVE_S8 = 7,
|
|
WPK_TK_STATIC_S8 = 8,
|
|
|
|
WPK_OP_CONV2D = 1,
|
|
WPK_OP_RELU = 2,
|
|
WPK_OP_ADD = 3,
|
|
WPK_OP_CONCAT = 4,
|
|
WPK_OP_SLICE_CH = 5,
|
|
WPK_OP_DEPTH_TO_SPACE = 6,
|
|
WPK_OP_CONVERT = 7,
|
|
WPK_OP_SLICE_HW = 8,
|
|
WPK_OP_PAD_HW = 9,
|
|
};
|
|
|
|
typedef struct __attribute__((packed)) {
|
|
uint64_t magic;
|
|
uint32_t version;
|
|
uint32_t in_h, in_w, in_c;
|
|
uint32_t out_h, out_w, out_c;
|
|
uint32_t num_tensors, num_ops;
|
|
uint32_t in_tid;
|
|
float s_in, s_out;
|
|
uint32_t out_tid, payload_bytes;
|
|
} WlWpkHeader;
|
|
|
|
typedef struct __attribute__((packed)) {
|
|
uint32_t id, kind;
|
|
uint32_t dims[4];
|
|
uint32_t rank;
|
|
float scale;
|
|
int32_t offset;
|
|
uint32_t data_offset, data_size;
|
|
} WlWpkTensor;
|
|
|
|
typedef struct __attribute__((packed)) {
|
|
uint32_t op_type;
|
|
uint32_t in_ids[3];
|
|
uint32_t num_ins, out_id;
|
|
uint32_t p0, p1, p2, p3;
|
|
} WlWpkOp;
|
|
|
|
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
|
|
_Static_assert(sizeof(WlWpkHeader) == 64, "WlWpkHeader size");
|
|
_Static_assert(sizeof(WlWpkTensor) == 44, "WlWpkTensor size");
|
|
_Static_assert(sizeof(WlWpkOp) == 40, "WlWpkOp size");
|
|
#endif
|
|
|
|
static Qnn_Tensor_t make_param_tensor(const char *name, uint32_t dtype,
|
|
uint32_t rank, uint32_t *dims,
|
|
void *data, uint32_t data_size) {
|
|
Qnn_Tensor_t t;
|
|
memset(&t, 0, sizeof t);
|
|
t.version = QNN_TENSOR_VERSION_1;
|
|
t.v1.name = name;
|
|
t.v1.type = QNN_TENSOR_TYPE_STATIC;
|
|
t.v1.dataFormat = QNN_TENSOR_DATA_FORMAT_FLAT_BUFFER;
|
|
t.v1.dataType = dtype;
|
|
t.v1.quantizeParams.encodingDefinition = QNN_DEFINITION_UNDEFINED;
|
|
t.v1.quantizeParams.quantizationEncoding = QNN_QUANT_ENC_UNDEFINED;
|
|
t.v1.rank = rank;
|
|
t.v1.dimensions = dims;
|
|
t.v1.memType = QNN_TENSORMEMTYPE_RAW;
|
|
t.v1.clientBuf.data = data;
|
|
t.v1.clientBuf.dataSize = data_size;
|
|
return t;
|
|
}
|
|
|
|
static int compile_wpack_attempt_locked(const char *fsr4_dir, const uint8_t *wpk, size_t wpk_sz,
|
|
const char *cache_rel, const char *graph_name, int use_custom_cfg) {
|
|
if (!graph_name || !*graph_name) graph_name = "fsr4_v07_i8";
|
|
if (!g_rt.Q || !g_rt.Q->contextCreate || !g_rt.Q->graphCreate ||
|
|
!g_rt.Q->graphAddNode || !g_rt.Q->graphFinalize ||
|
|
!g_rt.Q->tensorCreateGraphTensor || !g_rt.Q->contextGetBinarySize ||
|
|
!g_rt.Q->contextGetBinary) {
|
|
set_qnn_err("qnn_no_compile_fns");
|
|
F4_LOGE("QNN interface missing graph-compile functions");
|
|
return 0;
|
|
}
|
|
|
|
// Ensure libQnnHtpPrepare.so is globally loaded for on-device HTP graph compilation
|
|
if (!g_rt.lib_prep) {
|
|
g_rt.lib_prep = dlopen_qnn_lib_flags(fsr4_dir, "libQnnHtpPrepare.so", RTLD_NOW | RTLD_GLOBAL);
|
|
if (!g_rt.lib_prep) {
|
|
F4_LOGW("libQnnHtpPrepare.so preload failed (%s); relying on HTP internal loader", dlerror());
|
|
}
|
|
}
|
|
|
|
WlWpkHeader hdr;
|
|
memcpy(&hdr, wpk, sizeof hdr);
|
|
size_t tensors_off = sizeof(WlWpkHeader) + WL_FSR4_PASS0_WB_BYTES;
|
|
size_t ops_off = tensors_off + (size_t)hdr.num_tensors * sizeof(WlWpkTensor);
|
|
size_t payload_off = ops_off + (size_t)hdr.num_ops * sizeof(WlWpkOp);
|
|
if (payload_off + hdr.payload_bytes > wpk_sz) {
|
|
set_qnn_err("qnn_wpk_trunc");
|
|
F4_LOGE("%s wpack truncated (%zu < %zu)", graph_name, wpk_sz, payload_off + hdr.payload_bytes);
|
|
return 0;
|
|
}
|
|
|
|
const WlWpkTensor *wt = (const WlWpkTensor *)(wpk + tensors_off);
|
|
const WlWpkOp *wo = (const WlWpkOp *)(wpk + ops_off);
|
|
uint8_t *payload = (uint8_t *)(wpk + payload_off);
|
|
|
|
Qnn_ContextHandle_t ctx = NULL;
|
|
Qnn_ErrorHandle_t rc = g_rt.Q->contextCreate(g_rt.backend, g_rt.device, NULL, &ctx);
|
|
if (rc != QNN_SUCCESS_CODE || !ctx) {
|
|
set_qnn_err("qnn_ctx_0x%llx", (unsigned long long)rc);
|
|
F4_LOGE("QnnContext_create failed rc=0x%llx", (unsigned long long)rc);
|
|
return 0;
|
|
}
|
|
|
|
QnnHtpGraph_CustomConfig_t htp_opt, htp_vtcm;
|
|
memset(&htp_opt, 0, sizeof htp_opt);
|
|
htp_opt.option = QNN_HTP_GRAPH_CONFIG_OPTION_OPTIMIZATION;
|
|
htp_opt.optimizationOption.type = QNN_HTP_GRAPH_OPT_FINALIZE_FLAG;
|
|
htp_opt.optimizationOption.floatValue = 3.0f;
|
|
|
|
memset(&htp_vtcm, 0, sizeof htp_vtcm);
|
|
htp_vtcm.option = QNN_HTP_GRAPH_CONFIG_OPTION_VTCM_SIZE;
|
|
htp_vtcm.vtcmSizeInMB = 8u;
|
|
|
|
QnnGraph_Config_t gc0 = { QNN_GRAPH_CONFIG_OPTION_CUSTOM, { .customConfig = &htp_opt } };
|
|
QnnGraph_Config_t gc1 = { QNN_GRAPH_CONFIG_OPTION_CUSTOM, { .customConfig = &htp_vtcm } };
|
|
const QnnGraph_Config_t *gcfg[3] = { &gc0, &gc1, NULL };
|
|
|
|
Qnn_GraphHandle_t graph = NULL;
|
|
if (use_custom_cfg) {
|
|
rc = g_rt.Q->graphCreate(ctx, graph_name, gcfg, &graph);
|
|
if (rc != QNN_SUCCESS_CODE || !graph) {
|
|
F4_LOGW("QnnGraph_create(%s O=3,vtcm=8) rc=0x%llx; retrying with default graph config", graph_name, (unsigned long long)rc);
|
|
rc = g_rt.Q->graphCreate(ctx, graph_name, NULL, &graph);
|
|
}
|
|
} else {
|
|
rc = g_rt.Q->graphCreate(ctx, graph_name, NULL, &graph);
|
|
}
|
|
if (rc != QNN_SUCCESS_CODE || !graph) {
|
|
set_qnn_err("qnn_gcreate_0x%llx", (unsigned long long)rc);
|
|
F4_LOGE("QnnGraph_create failed rc=0x%llx", (unsigned long long)rc);
|
|
g_rt.Q->contextFree(ctx, NULL);
|
|
return 0;
|
|
}
|
|
|
|
Qnn_Tensor_t *qt = (Qnn_Tensor_t *)calloc(hdr.num_tensors, sizeof(Qnn_Tensor_t));
|
|
uint32_t (*qdims)[4] = (uint32_t (*)[4])calloc(hdr.num_tensors, sizeof(uint32_t[4]));
|
|
char (*qnames)[32] = (char (*)[32])calloc(hdr.num_tensors, sizeof(char[32]));
|
|
if (!qt || !qdims || !qnames) {
|
|
set_qnn_err("qnn_oom");
|
|
free(qt); free(qdims); free(qnames);
|
|
g_rt.Q->contextFree(ctx, NULL);
|
|
return 0;
|
|
}
|
|
|
|
int ok = 1;
|
|
for (uint32_t i = 0; i < hdr.num_tensors; i++) {
|
|
WlWpkTensor td;
|
|
memcpy(&td, &wt[i], sizeof td);
|
|
snprintf(qnames[i], 32,
|
|
(td.kind == WPK_TK_APP_WRITE) ? "input_u8" :
|
|
(td.kind == WPK_TK_APP_READ) ? "output_u8" :
|
|
(td.kind == WPK_TK_APP_WRITE_S8) ? "input_s8" :
|
|
(td.kind == WPK_TK_APP_READ_S8) ? "output_s8" : "t_%u", i);
|
|
for (int k = 0; k < 4; k++) qdims[i][k] = td.dims[k];
|
|
|
|
Qnn_Tensor_t *t = &qt[i];
|
|
t->version = QNN_TENSOR_VERSION_1;
|
|
t->v1.name = qnames[i];
|
|
t->v1.dataFormat = QNN_TENSOR_DATA_FORMAT_FLAT_BUFFER;
|
|
t->v1.quantizeParams.encodingDefinition = QNN_DEFINITION_DEFINED;
|
|
t->v1.quantizeParams.quantizationEncoding = QNN_QUANT_ENC_SCALE_OFFSET;
|
|
t->v1.quantizeParams.scaleOffsetEncoding.scale = td.scale;
|
|
t->v1.quantizeParams.scaleOffsetEncoding.offset = td.offset;
|
|
t->v1.rank = td.rank;
|
|
t->v1.dimensions = qdims[i];
|
|
t->v1.memType = QNN_TENSORMEMTYPE_RAW;
|
|
|
|
if (td.kind == WPK_TK_APP_WRITE) {
|
|
t->v1.type = QNN_TENSOR_TYPE_APP_WRITE;
|
|
t->v1.dataType = QNN_DATATYPE_UFIXED_POINT_8;
|
|
} else if (td.kind == WPK_TK_APP_READ) {
|
|
t->v1.type = QNN_TENSOR_TYPE_APP_READ;
|
|
t->v1.dataType = QNN_DATATYPE_UFIXED_POINT_8;
|
|
} else if (td.kind == WPK_TK_NATIVE) {
|
|
t->v1.type = QNN_TENSOR_TYPE_NATIVE;
|
|
t->v1.dataType = QNN_DATATYPE_UFIXED_POINT_8;
|
|
} else if (td.kind == WPK_TK_APP_WRITE_S8) {
|
|
t->v1.type = QNN_TENSOR_TYPE_APP_WRITE;
|
|
t->v1.dataType = QNN_DATATYPE_SFIXED_POINT_8;
|
|
} else if (td.kind == WPK_TK_APP_READ_S8) {
|
|
t->v1.type = QNN_TENSOR_TYPE_APP_READ;
|
|
t->v1.dataType = QNN_DATATYPE_SFIXED_POINT_8;
|
|
} else if (td.kind == WPK_TK_NATIVE_S8) {
|
|
t->v1.type = QNN_TENSOR_TYPE_NATIVE;
|
|
t->v1.dataType = QNN_DATATYPE_SFIXED_POINT_8;
|
|
} else if (td.kind == WPK_TK_STATIC_U8) {
|
|
t->v1.type = QNN_TENSOR_TYPE_STATIC;
|
|
t->v1.dataType = QNN_DATATYPE_UFIXED_POINT_8;
|
|
t->v1.clientBuf.data = payload + td.data_offset;
|
|
t->v1.clientBuf.dataSize = td.data_size;
|
|
} else if (td.kind == WPK_TK_STATIC_S8) {
|
|
t->v1.type = QNN_TENSOR_TYPE_STATIC;
|
|
t->v1.dataType = QNN_DATATYPE_SFIXED_POINT_8;
|
|
t->v1.clientBuf.data = payload + td.data_offset;
|
|
t->v1.clientBuf.dataSize = td.data_size;
|
|
} else {
|
|
t->v1.type = QNN_TENSOR_TYPE_STATIC;
|
|
t->v1.dataType = QNN_DATATYPE_SFIXED_POINT_32;
|
|
t->v1.clientBuf.data = payload + td.data_offset;
|
|
t->v1.clientBuf.dataSize = td.data_size;
|
|
}
|
|
|
|
rc = g_rt.Q->tensorCreateGraphTensor(graph, t);
|
|
if (rc != QNN_SUCCESS_CODE) {
|
|
set_qnn_err("qnn_t%u_0x%llx", i, (unsigned long long)rc);
|
|
F4_LOGE("tensorCreateGraphTensor(%u kind=%u) failed rc=0x%llx", i, td.kind, (unsigned long long)rc);
|
|
ok = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
for (uint32_t i = 0; ok && i < hdr.num_ops; i++) {
|
|
WlWpkOp od;
|
|
memcpy(&od, &wo[i], sizeof od);
|
|
char op_name[32], p_name0[40], p_name1[40];
|
|
snprintf(op_name, sizeof op_name, "op_%u", i);
|
|
|
|
Qnn_Tensor_t ins[3];
|
|
for (uint32_t k = 0; k < od.num_ins && k < 3; k++) ins[k] = qt[od.in_ids[k]];
|
|
Qnn_Tensor_t out_t = qt[od.out_id];
|
|
|
|
Qnn_Param_t params[4];
|
|
memset(params, 0, sizeof params);
|
|
uint32_t nparams = 0;
|
|
|
|
uint32_t stride_d[2] = { od.p0, od.p0 }, stride_dim[1] = { 2 };
|
|
uint32_t pad_d[4] = { od.p1, od.p1, od.p1, od.p1 }, pad_dim[2] = { 2, 2 };
|
|
uint32_t pad4_d[8] = { 0u, 0u, od.p0, od.p1, od.p2, od.p3, 0u, 0u }, pad4_dim[2] = { 4, 2 };
|
|
uint32_t d2s_d[2] = { od.p0, od.p0 }, d2s_dim[1] = { 2 };
|
|
int32_t slice_d[12]; uint32_t slice_dim[2] = { 4, 3 };
|
|
|
|
const char *type_name = NULL;
|
|
if (od.op_type == WPK_OP_CONV2D) {
|
|
type_name = "Conv2d";
|
|
snprintf(p_name0, sizeof p_name0, "op_%u_stride", i);
|
|
snprintf(p_name1, sizeof p_name1, "op_%u_pad", i);
|
|
params[nparams].paramType = QNN_PARAMTYPE_TENSOR;
|
|
params[nparams].name = "stride";
|
|
params[nparams].tensorParam = make_param_tensor(p_name0, QNN_DATATYPE_UINT_32, 1, stride_dim, stride_d, sizeof stride_d);
|
|
nparams++;
|
|
params[nparams].paramType = QNN_PARAMTYPE_TENSOR;
|
|
params[nparams].name = "pad_amount";
|
|
params[nparams].tensorParam = make_param_tensor(p_name1, QNN_DATATYPE_UINT_32, 2, pad_dim, pad_d, sizeof pad_d);
|
|
nparams++;
|
|
params[nparams].paramType = QNN_PARAMTYPE_SCALAR;
|
|
params[nparams].name = "group";
|
|
params[nparams].scalarParam.dataType = QNN_DATATYPE_UINT_32;
|
|
params[nparams].scalarParam.uint32Value = od.p2 ? od.p2 : 1u;
|
|
nparams++;
|
|
} else if (od.op_type == WPK_OP_RELU) {
|
|
type_name = "Relu";
|
|
} else if (od.op_type == WPK_OP_ADD) {
|
|
type_name = "ElementWiseAdd";
|
|
} else if (od.op_type == WPK_OP_CONCAT) {
|
|
type_name = "Concat";
|
|
params[nparams].paramType = QNN_PARAMTYPE_SCALAR;
|
|
params[nparams].name = "axis";
|
|
params[nparams].scalarParam.dataType = QNN_DATATYPE_UINT_32;
|
|
params[nparams].scalarParam.uint32Value = od.p0;
|
|
nparams++;
|
|
} else if (od.op_type == WPK_OP_SLICE_CH) {
|
|
type_name = "StridedSlice";
|
|
uint32_t *idims = qdims[od.in_ids[0]];
|
|
slice_d[0] = 0; slice_d[1] = (int32_t)idims[0]; slice_d[2] = 1;
|
|
slice_d[3] = 0; slice_d[4] = (int32_t)idims[1]; slice_d[5] = 1;
|
|
slice_d[6] = 0; slice_d[7] = (int32_t)idims[2]; slice_d[8] = 1;
|
|
slice_d[9] = (int32_t)od.p0; slice_d[10] = (int32_t)od.p1; slice_d[11] = 1;
|
|
snprintf(p_name0, sizeof p_name0, "op_%u_ranges", i);
|
|
params[nparams].paramType = QNN_PARAMTYPE_TENSOR;
|
|
params[nparams].name = "ranges";
|
|
params[nparams].tensorParam = make_param_tensor(p_name0, QNN_DATATYPE_INT_32, 2, slice_dim, slice_d, sizeof slice_d);
|
|
nparams++;
|
|
} else if (od.op_type == WPK_OP_DEPTH_TO_SPACE) {
|
|
type_name = "DepthToSpace";
|
|
snprintf(p_name0, sizeof p_name0, "op_%u_bs", i);
|
|
params[nparams].paramType = QNN_PARAMTYPE_TENSOR;
|
|
params[nparams].name = "block_size";
|
|
params[nparams].tensorParam = make_param_tensor(p_name0, QNN_DATATYPE_UINT_32, 1, d2s_dim, d2s_d, sizeof d2s_d);
|
|
nparams++;
|
|
params[nparams].paramType = QNN_PARAMTYPE_SCALAR;
|
|
params[nparams].name = "mode";
|
|
params[nparams].scalarParam.dataType = QNN_DATATYPE_UINT_32;
|
|
params[nparams].scalarParam.uint32Value = od.p1; /* 0 = DCR */
|
|
nparams++;
|
|
} else if (od.op_type == WPK_OP_CONVERT) {
|
|
type_name = "Convert";
|
|
} else if (od.op_type == WPK_OP_SLICE_HW) {
|
|
type_name = "StridedSlice";
|
|
uint32_t *idims = qdims[od.in_ids[0]];
|
|
slice_d[0] = 0; slice_d[1] = (int32_t)idims[0]; slice_d[2] = 1;
|
|
slice_d[3] = (int32_t)od.p0; slice_d[4] = (int32_t)od.p1; slice_d[5] = 1;
|
|
slice_d[6] = (int32_t)od.p2; slice_d[7] = (int32_t)od.p3; slice_d[8] = 1;
|
|
slice_d[9] = 0; slice_d[10] = (int32_t)idims[3]; slice_d[11] = 1;
|
|
snprintf(p_name0, sizeof p_name0, "op_%u_ranges", i);
|
|
params[nparams].paramType = QNN_PARAMTYPE_TENSOR;
|
|
params[nparams].name = "ranges";
|
|
params[nparams].tensorParam = make_param_tensor(p_name0, QNN_DATATYPE_INT_32, 2, slice_dim, slice_d, sizeof slice_d);
|
|
nparams++;
|
|
} else if (od.op_type == WPK_OP_PAD_HW) {
|
|
type_name = "Pad";
|
|
snprintf(p_name0, sizeof p_name0, "op_%u_padamt", i);
|
|
params[nparams].paramType = QNN_PARAMTYPE_TENSOR;
|
|
params[nparams].name = "pad_amount";
|
|
params[nparams].tensorParam = make_param_tensor(p_name0, QNN_DATATYPE_UINT_32, 2, pad4_dim, pad4_d, sizeof pad4_d);
|
|
nparams++;
|
|
params[nparams].paramType = QNN_PARAMTYPE_SCALAR;
|
|
params[nparams].name = "scheme";
|
|
params[nparams].scalarParam.dataType = QNN_DATATYPE_UINT_32;
|
|
params[nparams].scalarParam.uint32Value = 0u; /* CONSTANT */
|
|
nparams++;
|
|
params[nparams].paramType = QNN_PARAMTYPE_SCALAR;
|
|
params[nparams].name = "pad_constant_value";
|
|
params[nparams].scalarParam.dataType = QNN_DATATYPE_FLOAT_32;
|
|
params[nparams].scalarParam.floatValue = 0.0f;
|
|
nparams++;
|
|
}
|
|
|
|
for (uint32_t p = 0; p < nparams; p++) {
|
|
if (params[p].paramType == QNN_PARAMTYPE_TENSOR) {
|
|
rc = g_rt.Q->tensorCreateGraphTensor(graph, ¶ms[p].tensorParam);
|
|
if (rc != QNN_SUCCESS_CODE) {
|
|
set_qnn_err("qnn_pt%u_%u_0x%llx", i, p, (unsigned long long)rc);
|
|
F4_LOGE("tensorCreateGraphTensor(op=%u param=%s) failed rc=0x%llx",
|
|
i, params[p].name ? params[p].name : "?", (unsigned long long)rc);
|
|
ok = 0;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
if (!ok) break;
|
|
|
|
Qnn_OpConfig_t cfg;
|
|
memset(&cfg, 0, sizeof cfg);
|
|
cfg.version = QNN_OPCONFIG_VERSION_1;
|
|
cfg.v1.name = op_name;
|
|
cfg.v1.packageName = "qti.aisw";
|
|
cfg.v1.typeName = type_name;
|
|
cfg.v1.numOfParams = nparams;
|
|
cfg.v1.params = nparams ? params : NULL;
|
|
cfg.v1.numOfInputs = od.num_ins;
|
|
cfg.v1.inputTensors = ins;
|
|
cfg.v1.numOfOutputs = 1;
|
|
cfg.v1.outputTensors = &out_t;
|
|
|
|
rc = g_rt.Q->graphAddNode(graph, cfg);
|
|
if (rc != QNN_SUCCESS_CODE) {
|
|
set_qnn_err("qnn_op%u_%s_0x%llx", i, type_name ? type_name : "?", (unsigned long long)rc);
|
|
F4_LOGE("QnnGraph_addNode(%u %s) failed rc=0x%llx", i, type_name ? type_name : "?", (unsigned long long)rc);
|
|
ok = 0;
|
|
break;
|
|
}
|
|
}
|
|
|
|
free(qt); free(qdims); free(qnames);
|
|
|
|
if (ok) {
|
|
double t0 = mono_ms();
|
|
F4_LOGI("Compiling %s INT8 (%u ops, custom_cfg=%d) for Hexagon HTP NPU...",
|
|
graph_name, hdr.num_ops, use_custom_cfg);
|
|
rc = g_rt.Q->graphFinalize(graph, NULL, NULL);
|
|
if (rc != QNN_SUCCESS_CODE) {
|
|
set_qnn_err("qnn_fin_0x%llx", (unsigned long long)rc);
|
|
F4_LOGE("QnnGraph_finalize failed rc=0x%llx", (unsigned long long)rc);
|
|
ok = 0;
|
|
} else {
|
|
F4_LOGI("QnnGraph_finalize succeeded in %.1f ms!", mono_ms() - t0);
|
|
Qnn_ContextBinarySize_t bsz = 0, written = 0;
|
|
rc = g_rt.Q->contextGetBinarySize(ctx, &bsz);
|
|
if (rc == QNN_SUCCESS_CODE && bsz > 0) {
|
|
void *bin_out = malloc((size_t)bsz);
|
|
if (bin_out) {
|
|
rc = g_rt.Q->contextGetBinary(ctx, bin_out, bsz, &written);
|
|
if (rc == QNN_SUCCESS_CODE && written > 0) {
|
|
char arch_dir[600], dst_path[640], tmp_path[660];
|
|
snprintf(dst_path, sizeof dst_path, "%s/%s", fsr4_dir, cache_rel);
|
|
snprintf(arch_dir, sizeof arch_dir, "%s", dst_path);
|
|
char *slash = strrchr(arch_dir, '/');
|
|
if (slash && slash > arch_dir + strlen(fsr4_dir)) {
|
|
*slash = '\0';
|
|
mkdir(arch_dir, 0755);
|
|
}
|
|
snprintf(tmp_path, sizeof tmp_path, "%s.tmp", dst_path);
|
|
FILE *f = fopen(tmp_path, "wb");
|
|
if (f && fwrite(bin_out, 1, (size_t)written, f) == (size_t)written) {
|
|
fclose(f);
|
|
rename(tmp_path, dst_path);
|
|
F4_LOGI("Saved compiled Hexagon HTP binary cache: %s (%llu B)",
|
|
dst_path, (unsigned long long)written);
|
|
} else {
|
|
if (f) fclose(f);
|
|
unlink(tmp_path);
|
|
set_qnn_err("qnn_save_cache");
|
|
ok = 0;
|
|
}
|
|
} else {
|
|
set_qnn_err("qnn_getbin_0x%llx", (unsigned long long)rc);
|
|
F4_LOGE("contextGetBinary failed rc=0x%llx", (unsigned long long)rc);
|
|
ok = 0;
|
|
}
|
|
free(bin_out);
|
|
} else {
|
|
set_qnn_err("qnn_bin_oom");
|
|
ok = 0;
|
|
}
|
|
} else {
|
|
set_qnn_err("qnn_binsz_0x%llx", (unsigned long long)rc);
|
|
F4_LOGE("contextGetBinarySize failed rc=0x%llx", (unsigned long long)rc);
|
|
ok = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
g_rt.Q->contextFree(ctx, NULL);
|
|
return ok;
|
|
}
|
|
|
|
static int compile_wpack_to_cache_locked(const char *fsr4_dir, const uint8_t *wpk, size_t wpk_sz,
|
|
const char *cache_rel, const char *graph_name) {
|
|
if (compile_wpack_attempt_locked(fsr4_dir, wpk, wpk_sz, cache_rel, graph_name, 1)) return 1;
|
|
F4_LOGW("HTP compile(%s) with custom O=3/VTCM=8 config failed (%s); retrying with default graph config",
|
|
graph_name ? graph_name : "?", g_qnn_last_err);
|
|
return compile_wpack_attempt_locked(fsr4_dir, wpk, wpk_sz, cache_rel, graph_name, 0);
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack_layout(const char *fsr4_dir, const char *wpack_rel,
|
|
const char *cache_rel, const char *graph_name,
|
|
const char *power_mode,
|
|
size_t total_ahb_bytes,
|
|
const uint64_t in_offs[2], const uint64_t out_offs[2]) {
|
|
set_qnn_err("none");
|
|
if (!fsr4_dir || !*fsr4_dir || !wpack_rel || !cache_rel || !in_offs || !out_offs || total_ahb_bytes == 0u) {
|
|
set_qnn_err("qnn_nodir");
|
|
return NULL;
|
|
}
|
|
char wpk_path[640];
|
|
snprintf(wpk_path, sizeof wpk_path, "%s/%s", fsr4_dir, wpack_rel);
|
|
size_t wpk_sz = 0;
|
|
uint8_t *wpk = read_bin_file(wpk_path, &wpk_sz);
|
|
if (!wpk || wpk_sz < sizeof(WlWpkHeader) + WL_FSR4_PASS0_WB_BYTES) {
|
|
set_qnn_err("qnn_wpack_open");
|
|
free(wpk);
|
|
return NULL;
|
|
}
|
|
WlWpkHeader hdr;
|
|
memcpy(&hdr, wpk, sizeof hdr);
|
|
if (hdr.magic != WPK_MAGIC || hdr.version != 1u) {
|
|
set_qnn_err("qnn_wpack_hdr");
|
|
free(wpk);
|
|
return NULL;
|
|
}
|
|
|
|
wl_fsr4_qnn *q = (wl_fsr4_qnn *)calloc(1, sizeof *q);
|
|
if (!q) { free(wpk); return NULL; }
|
|
q->buf.dmabuf_fd = -1;
|
|
q->dline = query_dcache_line();
|
|
snprintf(q->dir, sizeof q->dir, "%s", fsr4_dir);
|
|
|
|
if (!qnn_ahb_alloc(&q->buf, total_ahb_bytes, q->dline)) {
|
|
free(wpk);
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
if (!rt_acquire_locked(fsr4_dir, power_mode)) {
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
free(wpk);
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
q->has_rt = 1;
|
|
|
|
// Callers name the cache "<arch>/<file>" (upstream writes v81/); the compiled context only loads on the
|
|
// HTP arch it was finalized for, so it is kept under this device's arch folder whatever the caller wrote.
|
|
const char *cache_file = strrchr(cache_rel, '/');
|
|
cache_file = cache_file ? cache_file + 1 : cache_rel;
|
|
char arch_rel[96];
|
|
cache_rel_path(q->dir, cache_file, arch_rel, sizeof arch_rel);
|
|
int ok = graph_load_locked(&q->presets[0], q->dir, arch_rel, &q->buf, 2, in_offs, out_offs);
|
|
if (!ok) {
|
|
if (compile_wpack_to_cache_locked(q->dir, wpk, wpk_sz, arch_rel, graph_name)) {
|
|
ok = graph_load_locked(&q->presets[0], q->dir, arch_rel, &q->buf, 2, in_offs, out_offs);
|
|
}
|
|
}
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
free(wpk);
|
|
|
|
if (!ok) {
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
F4_LOGI("On-device QNN HTP graph '%s' ready (ahb=%zu B, dmabuf=%d, in=[%llu,%llu], out=[%llu,%llu])",
|
|
graph_name ? graph_name : arch_rel, total_ahb_bytes, q->buf.dmabuf_fd,
|
|
(unsigned long long)in_offs[0], (unsigned long long)in_offs[1],
|
|
(unsigned long long)out_offs[0], (unsigned long long)out_offs[1]);
|
|
return q;
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel,
|
|
const char *cache_rel, const char *graph_name,
|
|
const char *power_mode,
|
|
uint32_t in_bytes, uint32_t out_bytes) {
|
|
size_t ahb_bytes = 2u * (size_t)in_bytes + 2u * (size_t)out_bytes;
|
|
uint64_t in_offs[2] = { 0u, (uint64_t)in_bytes };
|
|
uint64_t out_offs[2] = { 2u * (uint64_t)in_bytes, 2u * (uint64_t)in_bytes + (uint64_t)out_bytes };
|
|
return wl_fsr4_qnn_init_wpack_layout(fsr4_dir, wpack_rel, cache_rel, graph_name, power_mode,
|
|
ahb_bytes, in_offs, out_offs);
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_offsets_zc(wl_fsr4_qnn *q, int slot,
|
|
uint64_t in_off, uint32_t in_bytes,
|
|
uint64_t out_off, uint32_t out_bytes,
|
|
int zero_copy, double *out_ms) {
|
|
if (!q || (slot != 0 && slot != 1)) return 0;
|
|
// Only clean/invalidate CPU cache when CPU actually touched the buffer (staging memcpy mode).
|
|
// In true GPU<->AHB<->Hexagon zero-copy mode, CPU never reads/writes mapped memory after init,
|
|
// so skipping 16.7 MB of dc civac saves ~0.3-0.6 ms off Sync GPU wait + CPU cycles!
|
|
if (!zero_copy) {
|
|
civac_range(q->buf.mapped + in_off, in_bytes, q->dline);
|
|
}
|
|
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
qnn_graph *p = &q->presets[0];
|
|
if (!p->ready) {
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
return 0;
|
|
}
|
|
double t0 = mono_ms();
|
|
g_rt.last_exec_ms = t0;
|
|
Qnn_ErrorHandle_t qe = g_rt.Q->graphExecute(p->graph, &p->in_t[slot], 1, &p->out_t[slot], 1, NULL, NULL);
|
|
double t1 = mono_ms();
|
|
g_rt.last_exec_ms = t1;
|
|
double dt = t1 - t0;
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
|
|
if (!zero_copy) {
|
|
civac_range(q->buf.mapped + out_off, out_bytes, q->dline);
|
|
}
|
|
if (out_ms) *out_ms = dt;
|
|
if (qe != QNN_SUCCESS_CODE) {
|
|
F4_LOGE("QnnGraph_execute(offsets) failed rc=0x%llx", (unsigned long long)qe);
|
|
return 0;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_offsets(wl_fsr4_qnn *q, int slot,
|
|
uint64_t in_off, uint32_t in_bytes,
|
|
uint64_t out_off, uint32_t out_bytes,
|
|
double *out_ms) {
|
|
return wl_fsr4_qnn_exec_offsets_zc(q, slot, in_off, in_bytes, out_off, out_bytes, 0, out_ms);
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_custom(wl_fsr4_qnn *q, int slot, uint32_t in_bytes, uint32_t out_bytes, double *out_ms) {
|
|
uint64_t off_in = (uint64_t)slot * (uint64_t)in_bytes;
|
|
uint64_t off_out = 2u * (uint64_t)in_bytes + (uint64_t)slot * (uint64_t)out_bytes;
|
|
return wl_fsr4_qnn_exec_offsets(q, slot, off_in, in_bytes, off_out, out_bytes, out_ms);
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init_builtin(const char *fsr4_dir, const char *power_mode,
|
|
uint8_t out_pass0_wb[WL_FSR4_PASS0_WB_BYTES]) {
|
|
set_qnn_err("none");
|
|
if (!fsr4_dir || !*fsr4_dir) { set_qnn_err("qnn_nodir"); return NULL; }
|
|
char wpk_path[640];
|
|
snprintf(wpk_path, sizeof wpk_path, "%s/fsr4_v07_i8.wpack", fsr4_dir);
|
|
size_t wpk_sz = 0;
|
|
uint8_t *wpk = read_bin_file(wpk_path, &wpk_sz);
|
|
if (!wpk || wpk_sz < sizeof(WlWpkHeader) + WL_FSR4_PASS0_WB_BYTES) {
|
|
set_qnn_err("qnn_wpack_open");
|
|
free(wpk);
|
|
return NULL;
|
|
}
|
|
WlWpkHeader hdr;
|
|
memcpy(&hdr, wpk, sizeof hdr);
|
|
if (hdr.magic != WPK_MAGIC || hdr.version != 1u) {
|
|
set_qnn_err("qnn_wpack_hdr");
|
|
F4_LOGE("invalid fsr4_v07_i8.wpack header");
|
|
free(wpk);
|
|
return NULL;
|
|
}
|
|
if (out_pass0_wb) {
|
|
memcpy(out_pass0_wb, wpk + sizeof(WlWpkHeader), WL_FSR4_PASS0_WB_BYTES);
|
|
}
|
|
|
|
wl_fsr4_qnn *q = (wl_fsr4_qnn *)calloc(1, sizeof *q);
|
|
if (!q) { free(wpk); return NULL; }
|
|
q->buf.dmabuf_fd = -1;
|
|
q->dline = query_dcache_line();
|
|
snprintf(q->dir, sizeof q->dir, "%s", fsr4_dir);
|
|
|
|
if (!qnn_ahb_alloc(&q->buf, WL_FSR4_BUILTIN_AHB_BYTES, q->dline)) {
|
|
free(wpk);
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
|
|
uint64_t in_offs[2] = { 0u, (uint64_t)WL_FSR4_BUILTIN_IN_BYTES };
|
|
uint64_t out_offs[2] = { 2u * (uint64_t)WL_FSR4_BUILTIN_IN_BYTES,
|
|
2u * (uint64_t)WL_FSR4_BUILTIN_IN_BYTES + (uint64_t)WL_FSR4_BUILTIN_OUT_BYTES };
|
|
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
if (!rt_acquire_locked(fsr4_dir, power_mode)) {
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
free(wpk);
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
q->has_rt = 1;
|
|
|
|
char cache_rel[96];
|
|
cache_rel_path(q->dir, "fsr4_v07_i8_cache.bin", cache_rel, sizeof cache_rel);
|
|
int ok = graph_load_locked(&q->presets[0], q->dir, cache_rel, &q->buf, 2, in_offs, out_offs);
|
|
if (!ok) {
|
|
// Compile on-device via libQnnHtpPrepare.so and cache to disk
|
|
if (compile_wpack_to_cache_locked(q->dir, wpk, wpk_sz, cache_rel, "fsr4_v07_i8")) {
|
|
ok = graph_load_locked(&q->presets[0], q->dir, cache_rel, &q->buf, 2, in_offs, out_offs);
|
|
}
|
|
}
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
free(wpk);
|
|
|
|
if (!ok) {
|
|
wl_fsr4_qnn_free(q);
|
|
return NULL;
|
|
}
|
|
F4_LOGI("Built-in AMD FSR 4.0.2 INT8 Hexagon HTP NPU ready (ahb=%u B, dmabuf=%d)",
|
|
WL_FSR4_BUILTIN_AHB_BYTES, q->buf.dmabuf_fd);
|
|
return q;
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_builtin(wl_fsr4_qnn *q, int slot, double *out_ms) {
|
|
if (!q || (slot != 0 && slot != 1)) return 0;
|
|
uint64_t off_in = (uint64_t)slot * WL_FSR4_BUILTIN_IN_BYTES;
|
|
uint64_t off_out = 2u * (uint64_t)WL_FSR4_BUILTIN_IN_BYTES + (uint64_t)slot * WL_FSR4_BUILTIN_OUT_BYTES;
|
|
civac_range(q->buf.mapped + off_in, WL_FSR4_BUILTIN_IN_BYTES, q->dline);
|
|
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
qnn_graph *p = &q->presets[0];
|
|
if (!p->ready) {
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
return 0;
|
|
}
|
|
double t0 = mono_ms();
|
|
g_rt.last_exec_ms = t0;
|
|
Qnn_ErrorHandle_t qe = g_rt.Q->graphExecute(p->graph, &p->in_t[slot], 1, &p->out_t[slot], 1, NULL, NULL);
|
|
double t1 = mono_ms();
|
|
g_rt.last_exec_ms = t1;
|
|
double dt = t1 - t0;
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
|
|
civac_range(q->buf.mapped + off_out, WL_FSR4_BUILTIN_OUT_BYTES, q->dline);
|
|
if (out_ms) *out_ms = dt;
|
|
if (qe != QNN_SUCCESS_CODE) {
|
|
F4_LOGE("QnnGraph_execute(builtin) failed rc=0x%llx", (unsigned long long)qe);
|
|
return 0;
|
|
}
|
|
return 1;
|
|
}
|
|
|
|
void wl_fsr4_qnn_free(wl_fsr4_qnn *q) {
|
|
if (!q) return;
|
|
pthread_mutex_lock(&g_rt_mu);
|
|
for (int i = 0; i < 2; i++) {
|
|
if (q->presets[i].ready || q->presets[i].ctx) graph_unload_locked(&q->presets[i]);
|
|
}
|
|
if (q->has_rt) {
|
|
rt_release_locked();
|
|
q->has_rt = 0;
|
|
}
|
|
pthread_mutex_unlock(&g_rt_mu);
|
|
qnn_ahb_free(&q->buf);
|
|
free(q);
|
|
}
|
|
|
|
#else /* DD_UPSCALE_NO_ANDROID: no FastRPC, AHardwareBuffer or QNN on glibc */
|
|
|
|
static const char *const k_no_npu = "npu_unavailable";
|
|
|
|
const char *wl_fsr4_qnn_last_error(void) { return k_no_npu; }
|
|
|
|
int wl_fsr4_qnn_cache_path(const char *fsr4_dir, const char *name, char *out, size_t out_sz) {
|
|
if (!fsr4_dir || !*fsr4_dir || !name || !out || !out_sz) return 0;
|
|
int n = snprintf(out, out_sz, "%s/htp/%s", fsr4_dir, name);
|
|
return n > 0 && (size_t)n < out_sz;
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init(const char *fsr4_dir, int preset, const char *power_mode) {
|
|
(void)fsr4_dir; (void)preset; (void)power_mode;
|
|
return NULL;
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init_builtin(const char *fsr4_dir, const char *power_mode,
|
|
uint8_t out_pass0_wb[WL_FSR4_PASS0_WB_BYTES]) {
|
|
(void)fsr4_dir; (void)power_mode; (void)out_pass0_wb;
|
|
return NULL;
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack(const char *fsr4_dir, const char *wpack_rel,
|
|
const char *cache_name, const char *graph_name,
|
|
const char *power_mode,
|
|
uint32_t in_bytes, uint32_t out_bytes) {
|
|
(void)fsr4_dir; (void)wpack_rel; (void)cache_name; (void)graph_name;
|
|
(void)power_mode; (void)in_bytes; (void)out_bytes;
|
|
return NULL;
|
|
}
|
|
|
|
wl_fsr4_qnn *wl_fsr4_qnn_init_wpack_layout(const char *fsr4_dir, const char *wpack_rel,
|
|
const char *cache_rel, const char *graph_name,
|
|
const char *power_mode,
|
|
size_t total_ahb_bytes,
|
|
const uint64_t in_offs[2], const uint64_t out_offs[2]) {
|
|
(void)fsr4_dir; (void)wpack_rel; (void)cache_rel; (void)graph_name;
|
|
(void)power_mode; (void)total_ahb_bytes; (void)in_offs; (void)out_offs;
|
|
return NULL;
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_offsets_zc(wl_fsr4_qnn *q, int slot, uint64_t in_off, uint32_t in_bytes,
|
|
uint64_t out_off, uint32_t out_bytes, int zero_copy, double *out_ms) {
|
|
(void)q; (void)slot; (void)in_off; (void)in_bytes; (void)out_off; (void)out_bytes; (void)zero_copy;
|
|
if (out_ms) *out_ms = 0.0;
|
|
return 0;
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_offsets(wl_fsr4_qnn *q, int slot, uint64_t in_off, uint32_t in_bytes,
|
|
uint64_t out_off, uint32_t out_bytes, double *out_ms) {
|
|
return wl_fsr4_qnn_exec_offsets_zc(q, slot, in_off, in_bytes, out_off, out_bytes, 0, out_ms);
|
|
}
|
|
|
|
int wl_fsr4_qnn_set_power_mode(const char *power_mode) { (void)power_mode; return 0; }
|
|
void wl_fsr4_pin_worker_non_prime(const char *worker_name) { (void)worker_name; }
|
|
const char *wl_fsr4_qnn_get_power_mode(void) { return "n/a"; }
|
|
|
|
int wl_fsr4_qnn_load_preset(wl_fsr4_qnn *q, int preset) { (void)q; (void)preset; return 0; }
|
|
void *wl_fsr4_qnn_ahb(const wl_fsr4_qnn *q) { (void)q; return NULL; }
|
|
void *wl_fsr4_qnn_mapped(const wl_fsr4_qnn *q) { (void)q; return NULL; }
|
|
int wl_fsr4_qnn_dmabuf_fd(const wl_fsr4_qnn *q) { (void)q; return -1; }
|
|
|
|
int wl_fsr4_qnn_exec(wl_fsr4_qnn *q, int preset, int slot, double *out_ms) {
|
|
(void)q; (void)preset; (void)slot;
|
|
if (out_ms) *out_ms = 0.0;
|
|
return 0;
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_builtin(wl_fsr4_qnn *q, int slot, double *out_ms) {
|
|
(void)q; (void)slot;
|
|
if (out_ms) *out_ms = 0.0;
|
|
return 0;
|
|
}
|
|
|
|
int wl_fsr4_qnn_exec_custom(wl_fsr4_qnn *q, int slot, uint32_t in_bytes, uint32_t out_bytes, double *out_ms) {
|
|
(void)q; (void)slot; (void)in_bytes; (void)out_bytes;
|
|
if (out_ms) *out_ms = 0.0;
|
|
return 0;
|
|
}
|
|
|
|
void wl_fsr4_qnn_free(wl_fsr4_qnn *q) { (void)q; }
|
|
|
|
#endif /* DD_UPSCALE_NO_ANDROID */
|