Elffuss BraidHub

kikocis/ncnn public

d7a5f98c0f60 · 17.1 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2023 THL A29 Limited, a Tencent company. All rights reserved.
4//
5// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6// in compliance with the License. You may obtain a copy of the License at
7//
8// https://opensource.org/licenses/BSD-3-Clause
9//
10// Unless required by applicable law or agreed to in writing, software distributed
11// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12// CONDITIONS OF ANY KIND, either express or implied. See the License for the
13// specific language governing permissions and limitations under the License.
14
15#include "platform.h"
16
17#if NCNN_VULKAN
18#if NCNN_SIMPLEVK
19
20#include "simplevk.h"
21
22#include <stdio.h>
23#include <stdlib.h>
24#include <string.h>
25
26#if defined _WIN32
27#define WIN32_LEAN_AND_MEAN
28#include <windows.h>
29#else
30#include <dlfcn.h>
31#include <sys/types.h>
32#include <unistd.h>
33#if defined __ANDROID__
34#include <dirent.h>
35#include <fcntl.h>
36#include <sys/stat.h>
37#endif
38#endif
39
40#if __APPLE__
41
42// always use static vulkan linkage on apple platform
43extern "C" VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(VkInstance instance, const char* pName);
44
45#endif
46
47namespace ncnn {
48
49// vulkan loader entrypoint
50PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = 0;
51
52// vulkan global functions
53PFN_vkEnumerateInstanceExtensionProperties vkEnumerateInstanceExtensionProperties = 0;
54PFN_vkCreateInstance vkCreateInstance = 0;
55PFN_vkEnumerateInstanceLayerProperties vkEnumerateInstanceLayerProperties = 0;
56
57#if __APPLE__
58
59int load_vulkan_driver(const char* /*driver_path*/)
60{
61 unload_vulkan_driver();
62
63 vkGetInstanceProcAddr = ::vkGetInstanceProcAddr;
64 vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceExtensionProperties");
65 vkCreateInstance = (PFN_vkCreateInstance)vkGetInstanceProcAddr(NULL, "vkCreateInstance");
66 vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceLayerProperties");
67 return 0;
68}
69
70void unload_vulkan_driver()
71{
72 vkGetInstanceProcAddr = 0;
73 vkEnumerateInstanceExtensionProperties = 0;
74 vkCreateInstance = 0;
75 vkEnumerateInstanceLayerProperties = 0;
76}
77
78#else // __APPLE__
79
80#if defined _WIN32
81static HMODULE g_libvulkan = 0;
82#else
83static void* g_libvulkan = 0;
84#if defined __ANDROID__
85
86struct hw_module_t;
87struct hw_module_methods_t;
88struct hw_device_t;
89
90struct hw_module_methods_t
91{
92 /** Open a specific device */
93 int (*open)(const hw_module_t* mod, const char* id, hw_device_t** device);
94};
95
96struct hw_device_t
97{
98 /** tag must be initialized to HARDWARE_DEVICE_TAG */
99 uint32_t tag;
100 uint32_t version;
101 /** reference to the module this device belongs to */
102 hw_module_t* mod;
103 /** padding reserved for future use */
104#ifdef __LP64__
105 uint64_t reserved[12];
106#else
107 uint32_t reserved[12];
108#endif
109 /** Close this device */
110 int (*close)(hw_device_t* device);
111};
112
113struct hw_module_t
114{
115 /** tag must be initialized to HARDWARE_MODULE_TAG */
116 uint32_t tag;
117 uint16_t module_api_version;
118 uint16_t hal_api_version;
119 const char* id;
120 const char* name;
121 const char* author;
122 hw_module_methods_t* methods;
123 void* dso;
124#ifdef __LP64__
125 uint64_t reserved[32 - 7];
126#else
127 /** padding to 128 bytes, reserved for future use */
128 uint32_t reserved[32 - 7];
129#endif
130};
131
132struct hwvulkan_module_t : public hw_module_t
133{
134};
135
136struct hwvulkan_device_t : public hw_device_t
137{
138 PFN_vkEnumerateInstanceExtensionProperties EnumerateInstanceExtensionProperties;
139 PFN_vkCreateInstance CreateInstance;
140 PFN_vkGetInstanceProcAddr GetInstanceProcAddr;
141};
142
143// android hal vulkan loader
144static hwvulkan_device_t* g_hvkdi = 0;
145#endif
146#endif
147
148static std::string get_driver_path_from_icd(const char* icd_path)
149{
150 FILE* fp = fopen(icd_path, "rb");
151 if (!fp)
152 return std::string();
153
154 std::string driver_path;
155
156 char line[256];
157 while (!feof(fp))
158 {
159 char* s = fgets(line, 256, fp);
160 if (!s)
161 break;
162
163 // "library_path": "path to driver library",
164 char path[256];
165 int nscan = sscanf(line, " \"library_path\" : \"%255[^\"]\"", path);
166 if (nscan == 1)
167 {
168 if (path[0] == '.' || (path[0] != '/' && !strchr(path, ':') && (strchr(path, '/') || strchr(path, '\\'))))
169 {
170 // relative to the icd file path
171 std::string icd_dir = icd_path;
172 size_t dirpos = icd_dir.find_last_of("/\\");
173 if (dirpos != std::string::npos)
174 {
175 icd_dir = icd_dir.substr(0, dirpos + 1);
176 }
177 else
178 {
179 icd_dir = "./";
180 }
181
182 driver_path = icd_dir + path;
183 }
184 else
185 {
186 // filename or absolute path
187 driver_path = path;
188 }
189
190 break;
191 }
192 }
193
194 fclose(fp);
195
196 return driver_path;
197}
198
199static std::string get_driver_path_from_icd_env()
200{
201 const char* icd_path = getenv("VK_ICD_FILENAMES");
202 if (!icd_path)
203 return std::string();
204
205 return get_driver_path_from_icd(icd_path);
206}
207
208static std::string get_driver_path_from_ncnn_env()
209{
210 const char* driver_path = getenv("NCNN_VULKAN_DRIVER");
211 if (!driver_path)
212 return std::string();
213
214 return std::string(driver_path);
215}
216
217#if defined _WIN32
218static std::string search_file(const std::string& dirpath, const std::string& needle)
219{
220 WIN32_FIND_DATA file;
221 HANDLE handle = FindFirstFileA((dirpath + "\\*").c_str(), &file);
222 if (handle == INVALID_HANDLE_VALUE)
223 return std::string();
224
225 int found = 0;
226 std::vector<std::string> subdirs;
227
228 do
229 {
230 std::string name = file.cFileName;
231
232 if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
233 {
234 if (name != "." && name != "..")
235 subdirs.push_back(name);
236 }
237 else if (name == needle)
238 {
239 found = 1;
240 break;
241 }
242 } while (FindNextFileA(handle, &file));
243
244 FindClose(handle);
245
246 if (found)
247 return dirpath + "\\" + needle;
248
249 // recurse into subdirs
250 for (int i = 0; i < subdirs.size(); ++i)
251 {
252 std::string found_path = search_file(dirpath + "\\" + subdirs[i], needle);
253 if (!found_path.empty())
254 return found_path;
255 }
256
257 return std::string();
258}
259
260static int load_vulkan_windows(const char* driver_path)
261{
262 const char* libpath = driver_path ? driver_path : "vulkan-1.dll";
263
264 HMODULE libvulkan = LoadLibraryA(libpath);
265 if (!libvulkan)
266 {
267 NCNN_LOGE("LoadLibraryA %s failed %d", libpath, GetLastError());
268 return -1;
269 }
270
271 PFN_vkGetInstanceProcAddr GetInstanceProcAddr = 0;
272
273 GetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)GetProcAddress(libvulkan, "vk_icdGetInstanceProcAddr");
274 if (GetInstanceProcAddr)
275 {
276 // load icd driver
277 typedef VkResult(VKAPI_PTR * PFN_icdNegotiateLoaderICDInterfaceVersion)(uint32_t * pSupportedVersion);
278 PFN_icdNegotiateLoaderICDInterfaceVersion icdNegotiateLoaderICDInterfaceVersion = (PFN_icdNegotiateLoaderICDInterfaceVersion)GetProcAddress(libvulkan, "vk_icdNegotiateLoaderICDInterfaceVersion");
279 if (icdNegotiateLoaderICDInterfaceVersion)
280 {
281 uint32_t supported_version = 5;
282 VkResult ret = icdNegotiateLoaderICDInterfaceVersion(&supported_version);
283 if (ret != VK_SUCCESS)
284 {
285 NCNN_LOGE("icdNegotiateLoaderICDInterfaceVersion failed");
286 FreeLibrary(libvulkan);
287 return -1;
288 }
289 }
290 }
291 else
292 {
293 GetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)GetProcAddress(libvulkan, "vkGetInstanceProcAddr");
294 if (!GetInstanceProcAddr)
295 {
296 NCNN_LOGE("GetProcAddress failed %d", GetLastError());
297 FreeLibrary(libvulkan);
298 return -1;
299 }
300 }
301
302 g_libvulkan = libvulkan;
303 vkGetInstanceProcAddr = GetInstanceProcAddr;
304 vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceExtensionProperties");
305 vkCreateInstance = (PFN_vkCreateInstance)vkGetInstanceProcAddr(NULL, "vkCreateInstance");
306 vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceLayerProperties");
307 return 0;
308}
309#else
310static int load_vulkan_linux(const char* driver_path)
311{
312#if __APPLE__
313 const char* libpath = driver_path ? driver_path : "libvulkan.dylib";
314#else
315 const char* libpath = driver_path ? driver_path : "libvulkan.so";
316#endif
317
318 void* libvulkan = dlopen(libpath, RTLD_LOCAL | RTLD_NOW);
319#if !__APPLE__
320 if (!libvulkan)
321 {
322 libvulkan = dlopen("libvulkan.so.1", RTLD_LOCAL | RTLD_NOW);
323 }
324#endif
325 if (!libvulkan)
326 {
327 NCNN_LOGE("dlopen failed %s", dlerror());
328 return -1;
329 }
330
331 PFN_vkGetInstanceProcAddr GetInstanceProcAddr = 0;
332
333 GetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(libvulkan, "vk_icdGetInstanceProcAddr");
334 if (GetInstanceProcAddr)
335 {
336 // load icd driver
337 typedef VkResult(VKAPI_PTR * PFN_icdNegotiateLoaderICDInterfaceVersion)(uint32_t * pSupportedVersion);
338 PFN_icdNegotiateLoaderICDInterfaceVersion icdNegotiateLoaderICDInterfaceVersion = (PFN_icdNegotiateLoaderICDInterfaceVersion)dlsym(libvulkan, "vk_icdNegotiateLoaderICDInterfaceVersion");
339 if (icdNegotiateLoaderICDInterfaceVersion)
340 {
341 uint32_t supported_version = 5;
342 VkResult ret = icdNegotiateLoaderICDInterfaceVersion(&supported_version);
343 if (ret != VK_SUCCESS)
344 {
345 NCNN_LOGE("icdNegotiateLoaderICDInterfaceVersion failed");
346 dlclose(libvulkan);
347 return -1;
348 }
349 }
350 }
351 else
352 {
353 GetInstanceProcAddr = (PFN_vkGetInstanceProcAddr)dlsym(libvulkan, "vkGetInstanceProcAddr");
354 if (!GetInstanceProcAddr)
355 {
356 NCNN_LOGE("dlsym failed %s", dlerror());
357 dlclose(libvulkan);
358 return -1;
359 }
360 }
361
362 g_libvulkan = libvulkan;
363 vkGetInstanceProcAddr = GetInstanceProcAddr;
364 vkEnumerateInstanceExtensionProperties = (PFN_vkEnumerateInstanceExtensionProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceExtensionProperties");
365 vkCreateInstance = (PFN_vkCreateInstance)vkGetInstanceProcAddr(NULL, "vkCreateInstance");
366 vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceLayerProperties");
367 return 0;
368}
369
370#if defined __ANDROID__
371static int load_vulkan_android(const char* driver_path)
372{
373 char hal_driver_path[256];
374 if (!driver_path)
375 {
376 // https://source.android.com/docs/core/graphics/implement-vulkan#driver_emun
377
378 // /vendor/lib/hw/vulkan.<ro.hardware.vulkan>.so
379 // /vendor/lib/hw/vulkan.<ro.product.platform>.so
380 // /vendor/lib64/hw/vulkan.<ro.hardware.vulkan>.so
381 // /vendor/lib64/hw/vulkan.<ro.product.platform>.so
382
383#ifdef __LP64__
384 DIR* d = opendir("/vendor/lib64/hw");
385#else
386 DIR* d = opendir("/vendor/lib/hw");
387#endif
388 if (!d)
389 return -1;
390
391 int hal_driver_found = 0;
392 struct dirent* dir;
393 while ((dir = readdir(d)) != NULL)
394 {
395 char platform[256];
396 int nscan = sscanf(dir->d_name, "vulkan.%255s.so", platform);
397 if (nscan == 1)
398 {
399#ifdef __LP64__
400 snprintf(hal_driver_path, 256, "/vendor/lib64/hw/%s", dir->d_name);
401#else
402 snprintf(hal_driver_path, 256, "/vendor/lib/hw/%s", dir->d_name);
403#endif
404 hal_driver_found = 1;
405 break;
406 }
407 }
408 closedir(d);
409
410 if (!hal_driver_found)
411 {
412 NCNN_LOGE("no hal driver found");
413 return -1;
414 }
415
416 NCNN_LOGE("hal_driver_path = %s", hal_driver_path);
417 }
418
419 const char* libpath = driver_path ? driver_path : hal_driver_path;
420
421 void* libvulkan = dlopen(libpath, RTLD_LOCAL | RTLD_NOW);
422 if (!libvulkan)
423 {
424 NCNN_LOGE("dlopen failed %s", dlerror());
425 return -1;
426 }
427
428 // resolve entrypoint from android hal module
429 hw_module_t* hmi = 0;
430 hmi = (hw_module_t*)dlsym(libvulkan, "HMI");
431 if (!hmi)
432 {
433 NCNN_LOGE("dlsym failed %s", dlerror());
434 dlclose(libvulkan);
435 return -1;
436 }
437
438 if (strcmp(hmi->id, "vulkan") != 0)
439 {
440 NCNN_LOGE("hmi->id != vulkan");
441 dlclose(libvulkan);
442 return -1;
443 }
444
445 hwvulkan_module_t* hvkmi = (hwvulkan_module_t*)hmi;
446
447 // NCNN_LOGE("hvkmi name = %s", hvkmi->name);
448 // NCNN_LOGE("hvkmi author = %s", hvkmi->author);
449
450 hwvulkan_device_t* hvkdi = 0;
451 int result = hvkmi->methods->open(hvkmi, "vk0", (hw_device_t**)&hvkdi);
452 if (result != 0)
453 {
454 NCNN_LOGE("hmi->open failed %d", result);
455 dlclose(libvulkan);
456 return -1;
457 }
458
459 g_libvulkan = libvulkan;
460 g_hvkdi = hvkdi;
461 vkGetInstanceProcAddr = hvkdi->GetInstanceProcAddr;
462 vkEnumerateInstanceExtensionProperties = hvkdi->EnumerateInstanceExtensionProperties;
463 vkCreateInstance = hvkdi->CreateInstance;
464 vkEnumerateInstanceLayerProperties = (PFN_vkEnumerateInstanceLayerProperties)vkGetInstanceProcAddr(NULL, "vkEnumerateInstanceLayerProperties");
465 return 0;
466}
467#endif // __ANDROID__
468#endif // _WIN32
469
470int load_vulkan_driver(const char* driver_path)
471{
472 unload_vulkan_driver();
473
474 int ret = 0;
475
476 std::string driver_path_from_icd_env;
477 std::string driver_path_from_ncnn_env;
478 if (driver_path == 0)
479 {
480 driver_path_from_icd_env = get_driver_path_from_icd_env();
481 if (!driver_path_from_icd_env.empty())
482 {
483 driver_path = driver_path_from_icd_env.c_str();
484 }
485 else
486 {
487 driver_path_from_ncnn_env = get_driver_path_from_ncnn_env();
488 if (!driver_path_from_ncnn_env.empty())
489 {
490 driver_path = driver_path_from_ncnn_env.c_str();
491 }
492 }
493 }
494
495 // first try, load from driver_path
496#if defined _WIN32
497 ret = load_vulkan_windows(driver_path);
498#else
499 ret = load_vulkan_linux(driver_path);
500#if defined __ANDROID__
501 if (ret != 0)
502 {
503 // second try, load from android hal module
504 ret = load_vulkan_android(driver_path);
505 }
506#endif // __ANDROID__
507#endif // _WIN32
508 if (driver_path != 0 && ret != 0)
509 {
510 // third try, load from system vulkan
511#if defined _WIN32
512 ret = load_vulkan_windows(0);
513#else
514 ret = load_vulkan_linux(0);
515#if defined __ANDROID__
516 if (ret != 0)
517 {
518 // fourth try, load from any android hal module found
519 ret = load_vulkan_android(0);
520 }
521#endif // __ANDROID__
522#endif // _WIN32
523 }
524 if (ret != 0)
525 {
526 // fifth try, load from well-known path
527#if defined _WIN32
528 const char* well_known_path[] = {
529#if defined(__x86_64__) || defined(_M_X64)
530 "nvoglv64.dll",
531 "amdvlk64.dll",
532 "igvk64.dll"
533#else
534 "nvoglv32.dll",
535 "amdvlk32.dll",
536 "igvk32.dll"
537#endif
538 };
539#elif defined __ANDROID__
540 const char* well_known_path[] = {
541#ifdef __LP64__
542 "/vendor/lib64/hw/vulkan.adreno.so",
543 "/vendor/lib64/egl/libGLES_mali.so"
544#else
545 "/vendor/lib/hw/vulkan.adreno.so",
546 "/vendor/lib/egl/libGLES_mali.so"
547#endif
548 };
549#else
550 const char* well_known_path[] = {
551 "libGLX_nvidia.so.0",
552 "libvulkan_radeon.so",
553 "libvulkan_intel.so",
554 "libMaliVulkan.so.1",
555 "libVK_IMG.so"
556 };
557#endif
558
559 const int well_known_path_count = sizeof(well_known_path) / sizeof(const char*);
560 for (int i = 0; i < well_known_path_count; i++)
561 {
562#if defined _WIN32
563 // find driver dll in %SystemRoot%\System32\DriverStore\FileRepository (32bit and 64bit both and in here)
564 std::string dllpath = search_file("%SystemRoot%\\System32\\DriverStore\\FileRepository", well_known_path[i]);
565 if (dllpath.empty())
566 continue;
567
568 ret = load_vulkan_windows(well_known_path[i]);
569#elif defined __ANDROID__
570 ret = load_vulkan_android(well_known_path[i]);
571#else
572 ret = load_vulkan_linux(well_known_path[i]);
573#endif
574 if (ret == 0)
575 break;
576 }
577 }
578
579 return ret;
580}
581
582void unload_vulkan_driver()
583{
584 vkGetInstanceProcAddr = 0;
585 vkEnumerateInstanceExtensionProperties = 0;
586 vkCreateInstance = 0;
587 vkEnumerateInstanceLayerProperties = 0;
588
589#if defined _WIN32
590 if (g_libvulkan)
591 {
592 FreeLibrary(g_libvulkan);
593 g_libvulkan = 0;
594 }
595#else
596#if defined __ANDROID__
597 if (g_hvkdi)
598 {
599 if (g_hvkdi->close)
600 {
601 g_hvkdi->close(g_hvkdi);
602 }
603 g_hvkdi = 0;
604 }
605#endif // __ANDROID__
606
607 if (g_libvulkan)
608 {
609 dlclose(g_libvulkan);
610 g_libvulkan = 0;
611 }
612#endif // _WIN32
613}
614
615#endif // __APPLE__
616
617} // namespace ncnn
618
619#endif // NCNN_SIMPLEVK
620#endif // NCNN_VULKAN