Clone of mesa.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

anv_device.c 72KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081
  1. /*
  2. * Copyright © 2015 Intel Corporation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice (including the next
  12. * paragraph) shall be included in all copies or substantial portions of the
  13. * Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. * IN THE SOFTWARE.
  22. */
  23. #include <assert.h>
  24. #include <stdbool.h>
  25. #include <string.h>
  26. #include <sys/mman.h>
  27. #include <sys/sysinfo.h>
  28. #include <unistd.h>
  29. #include <fcntl.h>
  30. #include <xf86drm.h>
  31. #include "anv_private.h"
  32. #include "util/strtod.h"
  33. #include "util/debug.h"
  34. #include "util/build_id.h"
  35. #include "util/mesa-sha1.h"
  36. #include "vk_util.h"
  37. #include "genxml/gen7_pack.h"
  38. static void
  39. compiler_debug_log(void *data, const char *fmt, ...)
  40. { }
  41. static void
  42. compiler_perf_log(void *data, const char *fmt, ...)
  43. {
  44. va_list args;
  45. va_start(args, fmt);
  46. if (unlikely(INTEL_DEBUG & DEBUG_PERF))
  47. vfprintf(stderr, fmt, args);
  48. va_end(args);
  49. }
  50. static VkResult
  51. anv_compute_heap_size(int fd, uint64_t *heap_size)
  52. {
  53. uint64_t gtt_size;
  54. if (anv_gem_get_context_param(fd, 0, I915_CONTEXT_PARAM_GTT_SIZE,
  55. &gtt_size) == -1) {
  56. /* If, for whatever reason, we can't actually get the GTT size from the
  57. * kernel (too old?) fall back to the aperture size.
  58. */
  59. anv_perf_warn("Failed to get I915_CONTEXT_PARAM_GTT_SIZE: %m");
  60. if (anv_gem_get_aperture(fd, &gtt_size) == -1) {
  61. return vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
  62. "failed to get aperture size: %m");
  63. }
  64. }
  65. /* Query the total ram from the system */
  66. struct sysinfo info;
  67. sysinfo(&info);
  68. uint64_t total_ram = (uint64_t)info.totalram * (uint64_t)info.mem_unit;
  69. /* We don't want to burn too much ram with the GPU. If the user has 4GiB
  70. * or less, we use at most half. If they have more than 4GiB, we use 3/4.
  71. */
  72. uint64_t available_ram;
  73. if (total_ram <= 4ull * 1024ull * 1024ull * 1024ull)
  74. available_ram = total_ram / 2;
  75. else
  76. available_ram = total_ram * 3 / 4;
  77. /* We also want to leave some padding for things we allocate in the driver,
  78. * so don't go over 3/4 of the GTT either.
  79. */
  80. uint64_t available_gtt = gtt_size * 3 / 4;
  81. *heap_size = MIN2(available_ram, available_gtt);
  82. return VK_SUCCESS;
  83. }
  84. static VkResult
  85. anv_physical_device_init_heaps(struct anv_physical_device *device, int fd)
  86. {
  87. /* The kernel query only tells us whether or not the kernel supports the
  88. * EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and not whether or not the
  89. * hardware has actual 48bit address support.
  90. */
  91. device->supports_48bit_addresses =
  92. (device->info.gen >= 8) && anv_gem_supports_48b_addresses(fd);
  93. uint64_t heap_size;
  94. VkResult result = anv_compute_heap_size(fd, &heap_size);
  95. if (result != VK_SUCCESS)
  96. return result;
  97. if (heap_size <= 3ull * (1ull << 30)) {
  98. /* In this case, everything fits nicely into the 32-bit address space,
  99. * so there's no need for supporting 48bit addresses on client-allocated
  100. * memory objects.
  101. */
  102. device->memory.heap_count = 1;
  103. device->memory.heaps[0] = (struct anv_memory_heap) {
  104. .size = heap_size,
  105. .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
  106. .supports_48bit_addresses = false,
  107. };
  108. } else {
  109. /* Not everything will fit nicely into a 32-bit address space. In this
  110. * case we need a 64-bit heap. Advertise a small 32-bit heap and a
  111. * larger 48-bit heap. If we're in this case, then we have a total heap
  112. * size larger than 3GiB which most likely means they have 8 GiB of
  113. * video memory and so carving off 1 GiB for the 32-bit heap should be
  114. * reasonable.
  115. */
  116. const uint64_t heap_size_32bit = 1ull << 30;
  117. const uint64_t heap_size_48bit = heap_size - heap_size_32bit;
  118. assert(device->supports_48bit_addresses);
  119. device->memory.heap_count = 2;
  120. device->memory.heaps[0] = (struct anv_memory_heap) {
  121. .size = heap_size_48bit,
  122. .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
  123. .supports_48bit_addresses = true,
  124. };
  125. device->memory.heaps[1] = (struct anv_memory_heap) {
  126. .size = heap_size_32bit,
  127. .flags = VK_MEMORY_HEAP_DEVICE_LOCAL_BIT,
  128. .supports_48bit_addresses = false,
  129. };
  130. }
  131. uint32_t type_count = 0;
  132. for (uint32_t heap = 0; heap < device->memory.heap_count; heap++) {
  133. uint32_t valid_buffer_usage = ~0;
  134. /* There appears to be a hardware issue in the VF cache where it only
  135. * considers the bottom 32 bits of memory addresses. If you happen to
  136. * have two vertex buffers which get placed exactly 4 GiB apart and use
  137. * them in back-to-back draw calls, you can get collisions. In order to
  138. * solve this problem, we require vertex and index buffers be bound to
  139. * memory allocated out of the 32-bit heap.
  140. */
  141. if (device->memory.heaps[heap].supports_48bit_addresses) {
  142. valid_buffer_usage &= ~(VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
  143. VK_BUFFER_USAGE_VERTEX_BUFFER_BIT);
  144. }
  145. if (device->info.has_llc) {
  146. /* Big core GPUs share LLC with the CPU and thus one memory type can be
  147. * both cached and coherent at the same time.
  148. */
  149. device->memory.types[type_count++] = (struct anv_memory_type) {
  150. .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
  151. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
  152. VK_MEMORY_PROPERTY_HOST_COHERENT_BIT |
  153. VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
  154. .heapIndex = heap,
  155. .valid_buffer_usage = valid_buffer_usage,
  156. };
  157. } else {
  158. /* The spec requires that we expose a host-visible, coherent memory
  159. * type, but Atom GPUs don't share LLC. Thus we offer two memory types
  160. * to give the application a choice between cached, but not coherent and
  161. * coherent but uncached (WC though).
  162. */
  163. device->memory.types[type_count++] = (struct anv_memory_type) {
  164. .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
  165. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
  166. VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
  167. .heapIndex = heap,
  168. .valid_buffer_usage = valid_buffer_usage,
  169. };
  170. device->memory.types[type_count++] = (struct anv_memory_type) {
  171. .propertyFlags = VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT |
  172. VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT |
  173. VK_MEMORY_PROPERTY_HOST_CACHED_BIT,
  174. .heapIndex = heap,
  175. .valid_buffer_usage = valid_buffer_usage,
  176. };
  177. }
  178. }
  179. device->memory.type_count = type_count;
  180. return VK_SUCCESS;
  181. }
  182. static VkResult
  183. anv_physical_device_init_uuids(struct anv_physical_device *device)
  184. {
  185. const struct build_id_note *note = build_id_find_nhdr("libvulkan_intel.so");
  186. if (!note) {
  187. return vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
  188. "Failed to find build-id");
  189. }
  190. unsigned build_id_len = build_id_length(note);
  191. if (build_id_len < 20) {
  192. return vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
  193. "build-id too short. It needs to be a SHA");
  194. }
  195. struct mesa_sha1 sha1_ctx;
  196. uint8_t sha1[20];
  197. STATIC_ASSERT(VK_UUID_SIZE <= sizeof(sha1));
  198. /* The pipeline cache UUID is used for determining when a pipeline cache is
  199. * invalid. It needs both a driver build and the PCI ID of the device.
  200. */
  201. _mesa_sha1_init(&sha1_ctx);
  202. _mesa_sha1_update(&sha1_ctx, build_id_data(note), build_id_len);
  203. _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
  204. sizeof(device->chipset_id));
  205. _mesa_sha1_final(&sha1_ctx, sha1);
  206. memcpy(device->pipeline_cache_uuid, sha1, VK_UUID_SIZE);
  207. /* The driver UUID is used for determining sharability of images and memory
  208. * between two Vulkan instances in separate processes. People who want to
  209. * share memory need to also check the device UUID (below) so all this
  210. * needs to be is the build-id.
  211. */
  212. memcpy(device->driver_uuid, build_id_data(note), VK_UUID_SIZE);
  213. /* The device UUID uniquely identifies the given device within the machine.
  214. * Since we never have more than one device, this doesn't need to be a real
  215. * UUID. However, on the off-chance that someone tries to use this to
  216. * cache pre-tiled images or something of the like, we use the PCI ID and
  217. * some bits of ISL info to ensure that this is safe.
  218. */
  219. _mesa_sha1_init(&sha1_ctx);
  220. _mesa_sha1_update(&sha1_ctx, &device->chipset_id,
  221. sizeof(device->chipset_id));
  222. _mesa_sha1_update(&sha1_ctx, &device->isl_dev.has_bit6_swizzling,
  223. sizeof(device->isl_dev.has_bit6_swizzling));
  224. _mesa_sha1_final(&sha1_ctx, sha1);
  225. memcpy(device->device_uuid, sha1, VK_UUID_SIZE);
  226. return VK_SUCCESS;
  227. }
  228. static VkResult
  229. anv_physical_device_init(struct anv_physical_device *device,
  230. struct anv_instance *instance,
  231. const char *path)
  232. {
  233. VkResult result;
  234. int fd;
  235. fd = open(path, O_RDWR | O_CLOEXEC);
  236. if (fd < 0)
  237. return vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
  238. device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
  239. device->instance = instance;
  240. assert(strlen(path) < ARRAY_SIZE(device->path));
  241. strncpy(device->path, path, ARRAY_SIZE(device->path));
  242. device->chipset_id = anv_gem_get_param(fd, I915_PARAM_CHIPSET_ID);
  243. if (!device->chipset_id) {
  244. result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
  245. goto fail;
  246. }
  247. device->name = gen_get_device_name(device->chipset_id);
  248. if (!gen_get_device_info(device->chipset_id, &device->info)) {
  249. result = vk_error(VK_ERROR_INCOMPATIBLE_DRIVER);
  250. goto fail;
  251. }
  252. if (device->info.is_haswell) {
  253. fprintf(stderr, "WARNING: Haswell Vulkan support is incomplete\n");
  254. } else if (device->info.gen == 7 && !device->info.is_baytrail) {
  255. fprintf(stderr, "WARNING: Ivy Bridge Vulkan support is incomplete\n");
  256. } else if (device->info.gen == 7 && device->info.is_baytrail) {
  257. fprintf(stderr, "WARNING: Bay Trail Vulkan support is incomplete\n");
  258. } else if (device->info.gen >= 8 && device->info.gen <= 9) {
  259. /* Broadwell, Cherryview, Skylake, Broxton, Kabylake is as fully
  260. * supported as anything */
  261. } else {
  262. result = vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
  263. "Vulkan not yet supported on %s", device->name);
  264. goto fail;
  265. }
  266. device->cmd_parser_version = -1;
  267. if (device->info.gen == 7) {
  268. device->cmd_parser_version =
  269. anv_gem_get_param(fd, I915_PARAM_CMD_PARSER_VERSION);
  270. if (device->cmd_parser_version == -1) {
  271. result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
  272. "failed to get command parser version");
  273. goto fail;
  274. }
  275. }
  276. if (!anv_gem_get_param(fd, I915_PARAM_HAS_WAIT_TIMEOUT)) {
  277. result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
  278. "kernel missing gem wait");
  279. goto fail;
  280. }
  281. if (!anv_gem_get_param(fd, I915_PARAM_HAS_EXECBUF2)) {
  282. result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
  283. "kernel missing execbuf2");
  284. goto fail;
  285. }
  286. if (!device->info.has_llc &&
  287. anv_gem_get_param(fd, I915_PARAM_MMAP_VERSION) < 1) {
  288. result = vk_errorf(VK_ERROR_INITIALIZATION_FAILED,
  289. "kernel missing wc mmap");
  290. goto fail;
  291. }
  292. result = anv_physical_device_init_heaps(device, fd);
  293. if (result != VK_SUCCESS)
  294. goto fail;
  295. device->has_exec_async = anv_gem_get_param(fd, I915_PARAM_HAS_EXEC_ASYNC);
  296. bool swizzled = anv_gem_get_bit6_swizzle(fd, I915_TILING_X);
  297. /* GENs prior to 8 do not support EU/Subslice info */
  298. if (device->info.gen >= 8) {
  299. device->subslice_total = anv_gem_get_param(fd, I915_PARAM_SUBSLICE_TOTAL);
  300. device->eu_total = anv_gem_get_param(fd, I915_PARAM_EU_TOTAL);
  301. /* Without this information, we cannot get the right Braswell
  302. * brandstrings, and we have to use conservative numbers for GPGPU on
  303. * many platforms, but otherwise, things will just work.
  304. */
  305. if (device->subslice_total < 1 || device->eu_total < 1) {
  306. fprintf(stderr, "WARNING: Kernel 4.1 required to properly"
  307. " query GPU properties.\n");
  308. }
  309. } else if (device->info.gen == 7) {
  310. device->subslice_total = 1 << (device->info.gt - 1);
  311. }
  312. if (device->info.is_cherryview &&
  313. device->subslice_total > 0 && device->eu_total > 0) {
  314. /* Logical CS threads = EUs per subslice * num threads per EU */
  315. uint32_t max_cs_threads =
  316. device->eu_total / device->subslice_total * device->info.num_thread_per_eu;
  317. /* Fuse configurations may give more threads than expected, never less. */
  318. if (max_cs_threads > device->info.max_cs_threads)
  319. device->info.max_cs_threads = max_cs_threads;
  320. }
  321. brw_process_intel_debug_variable();
  322. device->compiler = brw_compiler_create(NULL, &device->info);
  323. if (device->compiler == NULL) {
  324. result = vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  325. goto fail;
  326. }
  327. device->compiler->shader_debug_log = compiler_debug_log;
  328. device->compiler->shader_perf_log = compiler_perf_log;
  329. isl_device_init(&device->isl_dev, &device->info, swizzled);
  330. result = anv_physical_device_init_uuids(device);
  331. if (result != VK_SUCCESS)
  332. goto fail;
  333. result = anv_init_wsi(device);
  334. if (result != VK_SUCCESS) {
  335. ralloc_free(device->compiler);
  336. goto fail;
  337. }
  338. device->local_fd = fd;
  339. return VK_SUCCESS;
  340. fail:
  341. close(fd);
  342. return result;
  343. }
  344. static void
  345. anv_physical_device_finish(struct anv_physical_device *device)
  346. {
  347. anv_finish_wsi(device);
  348. ralloc_free(device->compiler);
  349. close(device->local_fd);
  350. }
  351. static void *
  352. default_alloc_func(void *pUserData, size_t size, size_t align,
  353. VkSystemAllocationScope allocationScope)
  354. {
  355. return malloc(size);
  356. }
  357. static void *
  358. default_realloc_func(void *pUserData, void *pOriginal, size_t size,
  359. size_t align, VkSystemAllocationScope allocationScope)
  360. {
  361. return realloc(pOriginal, size);
  362. }
  363. static void
  364. default_free_func(void *pUserData, void *pMemory)
  365. {
  366. free(pMemory);
  367. }
  368. static const VkAllocationCallbacks default_alloc = {
  369. .pUserData = NULL,
  370. .pfnAllocation = default_alloc_func,
  371. .pfnReallocation = default_realloc_func,
  372. .pfnFree = default_free_func,
  373. };
  374. VkResult anv_CreateInstance(
  375. const VkInstanceCreateInfo* pCreateInfo,
  376. const VkAllocationCallbacks* pAllocator,
  377. VkInstance* pInstance)
  378. {
  379. struct anv_instance *instance;
  380. assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO);
  381. uint32_t client_version;
  382. if (pCreateInfo->pApplicationInfo &&
  383. pCreateInfo->pApplicationInfo->apiVersion != 0) {
  384. client_version = pCreateInfo->pApplicationInfo->apiVersion;
  385. } else {
  386. client_version = VK_MAKE_VERSION(1, 0, 0);
  387. }
  388. if (VK_MAKE_VERSION(1, 0, 0) > client_version ||
  389. client_version > VK_MAKE_VERSION(1, 0, 0xfff)) {
  390. return vk_errorf(VK_ERROR_INCOMPATIBLE_DRIVER,
  391. "Client requested version %d.%d.%d",
  392. VK_VERSION_MAJOR(client_version),
  393. VK_VERSION_MINOR(client_version),
  394. VK_VERSION_PATCH(client_version));
  395. }
  396. for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
  397. const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
  398. if (!anv_instance_extension_supported(ext_name))
  399. return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
  400. }
  401. instance = vk_alloc2(&default_alloc, pAllocator, sizeof(*instance), 8,
  402. VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
  403. if (!instance)
  404. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  405. instance->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
  406. if (pAllocator)
  407. instance->alloc = *pAllocator;
  408. else
  409. instance->alloc = default_alloc;
  410. instance->apiVersion = client_version;
  411. instance->physicalDeviceCount = -1;
  412. _mesa_locale_init();
  413. VG(VALGRIND_CREATE_MEMPOOL(instance, 0, false));
  414. *pInstance = anv_instance_to_handle(instance);
  415. return VK_SUCCESS;
  416. }
  417. void anv_DestroyInstance(
  418. VkInstance _instance,
  419. const VkAllocationCallbacks* pAllocator)
  420. {
  421. ANV_FROM_HANDLE(anv_instance, instance, _instance);
  422. if (!instance)
  423. return;
  424. if (instance->physicalDeviceCount > 0) {
  425. /* We support at most one physical device. */
  426. assert(instance->physicalDeviceCount == 1);
  427. anv_physical_device_finish(&instance->physicalDevice);
  428. }
  429. VG(VALGRIND_DESTROY_MEMPOOL(instance));
  430. _mesa_locale_fini();
  431. vk_free(&instance->alloc, instance);
  432. }
  433. static VkResult
  434. anv_enumerate_devices(struct anv_instance *instance)
  435. {
  436. /* TODO: Check for more devices ? */
  437. drmDevicePtr devices[8];
  438. VkResult result = VK_ERROR_INCOMPATIBLE_DRIVER;
  439. int max_devices;
  440. instance->physicalDeviceCount = 0;
  441. max_devices = drmGetDevices2(0, devices, ARRAY_SIZE(devices));
  442. if (max_devices < 1)
  443. return VK_ERROR_INCOMPATIBLE_DRIVER;
  444. for (unsigned i = 0; i < (unsigned)max_devices; i++) {
  445. if (devices[i]->available_nodes & 1 << DRM_NODE_RENDER &&
  446. devices[i]->bustype == DRM_BUS_PCI &&
  447. devices[i]->deviceinfo.pci->vendor_id == 0x8086) {
  448. result = anv_physical_device_init(&instance->physicalDevice,
  449. instance,
  450. devices[i]->nodes[DRM_NODE_RENDER]);
  451. if (result != VK_ERROR_INCOMPATIBLE_DRIVER)
  452. break;
  453. }
  454. }
  455. drmFreeDevices(devices, max_devices);
  456. if (result == VK_SUCCESS)
  457. instance->physicalDeviceCount = 1;
  458. return result;
  459. }
  460. VkResult anv_EnumeratePhysicalDevices(
  461. VkInstance _instance,
  462. uint32_t* pPhysicalDeviceCount,
  463. VkPhysicalDevice* pPhysicalDevices)
  464. {
  465. ANV_FROM_HANDLE(anv_instance, instance, _instance);
  466. VK_OUTARRAY_MAKE(out, pPhysicalDevices, pPhysicalDeviceCount);
  467. VkResult result;
  468. if (instance->physicalDeviceCount < 0) {
  469. result = anv_enumerate_devices(instance);
  470. if (result != VK_SUCCESS &&
  471. result != VK_ERROR_INCOMPATIBLE_DRIVER)
  472. return result;
  473. }
  474. if (instance->physicalDeviceCount > 0) {
  475. assert(instance->physicalDeviceCount == 1);
  476. vk_outarray_append(&out, i) {
  477. *i = anv_physical_device_to_handle(&instance->physicalDevice);
  478. }
  479. }
  480. return vk_outarray_status(&out);
  481. }
  482. void anv_GetPhysicalDeviceFeatures(
  483. VkPhysicalDevice physicalDevice,
  484. VkPhysicalDeviceFeatures* pFeatures)
  485. {
  486. ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
  487. *pFeatures = (VkPhysicalDeviceFeatures) {
  488. .robustBufferAccess = true,
  489. .fullDrawIndexUint32 = true,
  490. .imageCubeArray = true,
  491. .independentBlend = true,
  492. .geometryShader = true,
  493. .tessellationShader = true,
  494. .sampleRateShading = true,
  495. .dualSrcBlend = true,
  496. .logicOp = true,
  497. .multiDrawIndirect = true,
  498. .drawIndirectFirstInstance = true,
  499. .depthClamp = true,
  500. .depthBiasClamp = true,
  501. .fillModeNonSolid = true,
  502. .depthBounds = false,
  503. .wideLines = true,
  504. .largePoints = true,
  505. .alphaToOne = true,
  506. .multiViewport = true,
  507. .samplerAnisotropy = true,
  508. .textureCompressionETC2 = pdevice->info.gen >= 8 ||
  509. pdevice->info.is_baytrail,
  510. .textureCompressionASTC_LDR = pdevice->info.gen >= 9, /* FINISHME CHV */
  511. .textureCompressionBC = true,
  512. .occlusionQueryPrecise = true,
  513. .pipelineStatisticsQuery = true,
  514. .fragmentStoresAndAtomics = true,
  515. .shaderTessellationAndGeometryPointSize = true,
  516. .shaderImageGatherExtended = true,
  517. .shaderStorageImageExtendedFormats = true,
  518. .shaderStorageImageMultisample = false,
  519. .shaderStorageImageReadWithoutFormat = false,
  520. .shaderStorageImageWriteWithoutFormat = true,
  521. .shaderUniformBufferArrayDynamicIndexing = true,
  522. .shaderSampledImageArrayDynamicIndexing = true,
  523. .shaderStorageBufferArrayDynamicIndexing = true,
  524. .shaderStorageImageArrayDynamicIndexing = true,
  525. .shaderClipDistance = true,
  526. .shaderCullDistance = true,
  527. .shaderFloat64 = pdevice->info.gen >= 8,
  528. .shaderInt64 = pdevice->info.gen >= 8,
  529. .shaderInt16 = false,
  530. .shaderResourceMinLod = false,
  531. .variableMultisampleRate = false,
  532. .inheritedQueries = true,
  533. };
  534. /* We can't do image stores in vec4 shaders */
  535. pFeatures->vertexPipelineStoresAndAtomics =
  536. pdevice->compiler->scalar_stage[MESA_SHADER_VERTEX] &&
  537. pdevice->compiler->scalar_stage[MESA_SHADER_GEOMETRY];
  538. }
  539. void anv_GetPhysicalDeviceFeatures2KHR(
  540. VkPhysicalDevice physicalDevice,
  541. VkPhysicalDeviceFeatures2KHR* pFeatures)
  542. {
  543. anv_GetPhysicalDeviceFeatures(physicalDevice, &pFeatures->features);
  544. vk_foreach_struct(ext, pFeatures->pNext) {
  545. switch (ext->sType) {
  546. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHX: {
  547. VkPhysicalDeviceMultiviewFeaturesKHX *features =
  548. (VkPhysicalDeviceMultiviewFeaturesKHX *)ext;
  549. features->multiview = true;
  550. features->multiviewGeometryShader = true;
  551. features->multiviewTessellationShader = true;
  552. break;
  553. }
  554. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR: {
  555. VkPhysicalDeviceVariablePointerFeaturesKHR *features = (void *)ext;
  556. features->variablePointersStorageBuffer = true;
  557. features->variablePointers = false;
  558. break;
  559. }
  560. default:
  561. anv_debug_ignored_stype(ext->sType);
  562. break;
  563. }
  564. }
  565. }
  566. void anv_GetPhysicalDeviceProperties(
  567. VkPhysicalDevice physicalDevice,
  568. VkPhysicalDeviceProperties* pProperties)
  569. {
  570. ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
  571. const struct gen_device_info *devinfo = &pdevice->info;
  572. /* See assertions made when programming the buffer surface state. */
  573. const uint32_t max_raw_buffer_sz = devinfo->gen >= 7 ?
  574. (1ul << 30) : (1ul << 27);
  575. const uint32_t max_samplers = (devinfo->gen >= 8 || devinfo->is_haswell) ?
  576. 128 : 16;
  577. VkSampleCountFlags sample_counts =
  578. isl_device_get_sample_counts(&pdevice->isl_dev);
  579. VkPhysicalDeviceLimits limits = {
  580. .maxImageDimension1D = (1 << 14),
  581. .maxImageDimension2D = (1 << 14),
  582. .maxImageDimension3D = (1 << 11),
  583. .maxImageDimensionCube = (1 << 14),
  584. .maxImageArrayLayers = (1 << 11),
  585. .maxTexelBufferElements = 128 * 1024 * 1024,
  586. .maxUniformBufferRange = (1ul << 27),
  587. .maxStorageBufferRange = max_raw_buffer_sz,
  588. .maxPushConstantsSize = MAX_PUSH_CONSTANTS_SIZE,
  589. .maxMemoryAllocationCount = UINT32_MAX,
  590. .maxSamplerAllocationCount = 64 * 1024,
  591. .bufferImageGranularity = 64, /* A cache line */
  592. .sparseAddressSpaceSize = 0,
  593. .maxBoundDescriptorSets = MAX_SETS,
  594. .maxPerStageDescriptorSamplers = max_samplers,
  595. .maxPerStageDescriptorUniformBuffers = 64,
  596. .maxPerStageDescriptorStorageBuffers = 64,
  597. .maxPerStageDescriptorSampledImages = max_samplers,
  598. .maxPerStageDescriptorStorageImages = 64,
  599. .maxPerStageDescriptorInputAttachments = 64,
  600. .maxPerStageResources = 250,
  601. .maxDescriptorSetSamplers = 256,
  602. .maxDescriptorSetUniformBuffers = 256,
  603. .maxDescriptorSetUniformBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
  604. .maxDescriptorSetStorageBuffers = 256,
  605. .maxDescriptorSetStorageBuffersDynamic = MAX_DYNAMIC_BUFFERS / 2,
  606. .maxDescriptorSetSampledImages = 256,
  607. .maxDescriptorSetStorageImages = 256,
  608. .maxDescriptorSetInputAttachments = 256,
  609. .maxVertexInputAttributes = MAX_VBS,
  610. .maxVertexInputBindings = MAX_VBS,
  611. .maxVertexInputAttributeOffset = 2047,
  612. .maxVertexInputBindingStride = 2048,
  613. .maxVertexOutputComponents = 128,
  614. .maxTessellationGenerationLevel = 64,
  615. .maxTessellationPatchSize = 32,
  616. .maxTessellationControlPerVertexInputComponents = 128,
  617. .maxTessellationControlPerVertexOutputComponents = 128,
  618. .maxTessellationControlPerPatchOutputComponents = 128,
  619. .maxTessellationControlTotalOutputComponents = 2048,
  620. .maxTessellationEvaluationInputComponents = 128,
  621. .maxTessellationEvaluationOutputComponents = 128,
  622. .maxGeometryShaderInvocations = 32,
  623. .maxGeometryInputComponents = 64,
  624. .maxGeometryOutputComponents = 128,
  625. .maxGeometryOutputVertices = 256,
  626. .maxGeometryTotalOutputComponents = 1024,
  627. .maxFragmentInputComponents = 128,
  628. .maxFragmentOutputAttachments = 8,
  629. .maxFragmentDualSrcAttachments = 1,
  630. .maxFragmentCombinedOutputResources = 8,
  631. .maxComputeSharedMemorySize = 32768,
  632. .maxComputeWorkGroupCount = { 65535, 65535, 65535 },
  633. .maxComputeWorkGroupInvocations = 16 * devinfo->max_cs_threads,
  634. .maxComputeWorkGroupSize = {
  635. 16 * devinfo->max_cs_threads,
  636. 16 * devinfo->max_cs_threads,
  637. 16 * devinfo->max_cs_threads,
  638. },
  639. .subPixelPrecisionBits = 4 /* FIXME */,
  640. .subTexelPrecisionBits = 4 /* FIXME */,
  641. .mipmapPrecisionBits = 4 /* FIXME */,
  642. .maxDrawIndexedIndexValue = UINT32_MAX,
  643. .maxDrawIndirectCount = UINT32_MAX,
  644. .maxSamplerLodBias = 16,
  645. .maxSamplerAnisotropy = 16,
  646. .maxViewports = MAX_VIEWPORTS,
  647. .maxViewportDimensions = { (1 << 14), (1 << 14) },
  648. .viewportBoundsRange = { INT16_MIN, INT16_MAX },
  649. .viewportSubPixelBits = 13, /* We take a float? */
  650. .minMemoryMapAlignment = 4096, /* A page */
  651. .minTexelBufferOffsetAlignment = 1,
  652. .minUniformBufferOffsetAlignment = 16,
  653. .minStorageBufferOffsetAlignment = 4,
  654. .minTexelOffset = -8,
  655. .maxTexelOffset = 7,
  656. .minTexelGatherOffset = -32,
  657. .maxTexelGatherOffset = 31,
  658. .minInterpolationOffset = -0.5,
  659. .maxInterpolationOffset = 0.4375,
  660. .subPixelInterpolationOffsetBits = 4,
  661. .maxFramebufferWidth = (1 << 14),
  662. .maxFramebufferHeight = (1 << 14),
  663. .maxFramebufferLayers = (1 << 11),
  664. .framebufferColorSampleCounts = sample_counts,
  665. .framebufferDepthSampleCounts = sample_counts,
  666. .framebufferStencilSampleCounts = sample_counts,
  667. .framebufferNoAttachmentsSampleCounts = sample_counts,
  668. .maxColorAttachments = MAX_RTS,
  669. .sampledImageColorSampleCounts = sample_counts,
  670. .sampledImageIntegerSampleCounts = VK_SAMPLE_COUNT_1_BIT,
  671. .sampledImageDepthSampleCounts = sample_counts,
  672. .sampledImageStencilSampleCounts = sample_counts,
  673. .storageImageSampleCounts = VK_SAMPLE_COUNT_1_BIT,
  674. .maxSampleMaskWords = 1,
  675. .timestampComputeAndGraphics = false,
  676. .timestampPeriod = 1000000000.0 / devinfo->timestamp_frequency,
  677. .maxClipDistances = 8,
  678. .maxCullDistances = 8,
  679. .maxCombinedClipAndCullDistances = 8,
  680. .discreteQueuePriorities = 1,
  681. .pointSizeRange = { 0.125, 255.875 },
  682. .lineWidthRange = { 0.0, 7.9921875 },
  683. .pointSizeGranularity = (1.0 / 8.0),
  684. .lineWidthGranularity = (1.0 / 128.0),
  685. .strictLines = false, /* FINISHME */
  686. .standardSampleLocations = true,
  687. .optimalBufferCopyOffsetAlignment = 128,
  688. .optimalBufferCopyRowPitchAlignment = 128,
  689. .nonCoherentAtomSize = 64,
  690. };
  691. *pProperties = (VkPhysicalDeviceProperties) {
  692. .apiVersion = anv_physical_device_api_version(pdevice),
  693. .driverVersion = vk_get_driver_version(),
  694. .vendorID = 0x8086,
  695. .deviceID = pdevice->chipset_id,
  696. .deviceType = VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU,
  697. .limits = limits,
  698. .sparseProperties = {0}, /* Broadwell doesn't do sparse. */
  699. };
  700. snprintf(pProperties->deviceName, sizeof(pProperties->deviceName),
  701. "%s", pdevice->name);
  702. memcpy(pProperties->pipelineCacheUUID,
  703. pdevice->pipeline_cache_uuid, VK_UUID_SIZE);
  704. }
  705. void anv_GetPhysicalDeviceProperties2KHR(
  706. VkPhysicalDevice physicalDevice,
  707. VkPhysicalDeviceProperties2KHR* pProperties)
  708. {
  709. ANV_FROM_HANDLE(anv_physical_device, pdevice, physicalDevice);
  710. anv_GetPhysicalDeviceProperties(physicalDevice, &pProperties->properties);
  711. vk_foreach_struct(ext, pProperties->pNext) {
  712. switch (ext->sType) {
  713. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR: {
  714. VkPhysicalDevicePushDescriptorPropertiesKHR *properties =
  715. (VkPhysicalDevicePushDescriptorPropertiesKHR *) ext;
  716. properties->maxPushDescriptors = MAX_PUSH_DESCRIPTORS;
  717. break;
  718. }
  719. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR: {
  720. VkPhysicalDeviceIDPropertiesKHR *id_props =
  721. (VkPhysicalDeviceIDPropertiesKHR *)ext;
  722. memcpy(id_props->deviceUUID, pdevice->device_uuid, VK_UUID_SIZE);
  723. memcpy(id_props->driverUUID, pdevice->driver_uuid, VK_UUID_SIZE);
  724. /* The LUID is for Windows. */
  725. id_props->deviceLUIDValid = false;
  726. break;
  727. }
  728. case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHX: {
  729. VkPhysicalDeviceMultiviewPropertiesKHX *properties =
  730. (VkPhysicalDeviceMultiviewPropertiesKHX *)ext;
  731. properties->maxMultiviewViewCount = 16;
  732. properties->maxMultiviewInstanceIndex = UINT32_MAX / 16;
  733. break;
  734. }
  735. default:
  736. anv_debug_ignored_stype(ext->sType);
  737. break;
  738. }
  739. }
  740. }
  741. /* We support exactly one queue family. */
  742. static const VkQueueFamilyProperties
  743. anv_queue_family_properties = {
  744. .queueFlags = VK_QUEUE_GRAPHICS_BIT |
  745. VK_QUEUE_COMPUTE_BIT |
  746. VK_QUEUE_TRANSFER_BIT,
  747. .queueCount = 1,
  748. .timestampValidBits = 36, /* XXX: Real value here */
  749. .minImageTransferGranularity = { 1, 1, 1 },
  750. };
  751. void anv_GetPhysicalDeviceQueueFamilyProperties(
  752. VkPhysicalDevice physicalDevice,
  753. uint32_t* pCount,
  754. VkQueueFamilyProperties* pQueueFamilyProperties)
  755. {
  756. VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pCount);
  757. vk_outarray_append(&out, p) {
  758. *p = anv_queue_family_properties;
  759. }
  760. }
  761. void anv_GetPhysicalDeviceQueueFamilyProperties2KHR(
  762. VkPhysicalDevice physicalDevice,
  763. uint32_t* pQueueFamilyPropertyCount,
  764. VkQueueFamilyProperties2KHR* pQueueFamilyProperties)
  765. {
  766. VK_OUTARRAY_MAKE(out, pQueueFamilyProperties, pQueueFamilyPropertyCount);
  767. vk_outarray_append(&out, p) {
  768. p->queueFamilyProperties = anv_queue_family_properties;
  769. vk_foreach_struct(s, p->pNext) {
  770. anv_debug_ignored_stype(s->sType);
  771. }
  772. }
  773. }
  774. void anv_GetPhysicalDeviceMemoryProperties(
  775. VkPhysicalDevice physicalDevice,
  776. VkPhysicalDeviceMemoryProperties* pMemoryProperties)
  777. {
  778. ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
  779. pMemoryProperties->memoryTypeCount = physical_device->memory.type_count;
  780. for (uint32_t i = 0; i < physical_device->memory.type_count; i++) {
  781. pMemoryProperties->memoryTypes[i] = (VkMemoryType) {
  782. .propertyFlags = physical_device->memory.types[i].propertyFlags,
  783. .heapIndex = physical_device->memory.types[i].heapIndex,
  784. };
  785. }
  786. pMemoryProperties->memoryHeapCount = physical_device->memory.heap_count;
  787. for (uint32_t i = 0; i < physical_device->memory.heap_count; i++) {
  788. pMemoryProperties->memoryHeaps[i] = (VkMemoryHeap) {
  789. .size = physical_device->memory.heaps[i].size,
  790. .flags = physical_device->memory.heaps[i].flags,
  791. };
  792. }
  793. }
  794. void anv_GetPhysicalDeviceMemoryProperties2KHR(
  795. VkPhysicalDevice physicalDevice,
  796. VkPhysicalDeviceMemoryProperties2KHR* pMemoryProperties)
  797. {
  798. anv_GetPhysicalDeviceMemoryProperties(physicalDevice,
  799. &pMemoryProperties->memoryProperties);
  800. vk_foreach_struct(ext, pMemoryProperties->pNext) {
  801. switch (ext->sType) {
  802. default:
  803. anv_debug_ignored_stype(ext->sType);
  804. break;
  805. }
  806. }
  807. }
  808. PFN_vkVoidFunction anv_GetInstanceProcAddr(
  809. VkInstance instance,
  810. const char* pName)
  811. {
  812. return anv_lookup_entrypoint(NULL, pName);
  813. }
  814. /* With version 1+ of the loader interface the ICD should expose
  815. * vk_icdGetInstanceProcAddr to work around certain LD_PRELOAD issues seen in apps.
  816. */
  817. PUBLIC
  818. VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
  819. VkInstance instance,
  820. const char* pName);
  821. PUBLIC
  822. VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vk_icdGetInstanceProcAddr(
  823. VkInstance instance,
  824. const char* pName)
  825. {
  826. return anv_GetInstanceProcAddr(instance, pName);
  827. }
  828. PFN_vkVoidFunction anv_GetDeviceProcAddr(
  829. VkDevice _device,
  830. const char* pName)
  831. {
  832. ANV_FROM_HANDLE(anv_device, device, _device);
  833. return anv_lookup_entrypoint(&device->info, pName);
  834. }
  835. static void
  836. anv_queue_init(struct anv_device *device, struct anv_queue *queue)
  837. {
  838. queue->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
  839. queue->device = device;
  840. queue->pool = &device->surface_state_pool;
  841. }
  842. static void
  843. anv_queue_finish(struct anv_queue *queue)
  844. {
  845. }
  846. static struct anv_state
  847. anv_state_pool_emit_data(struct anv_state_pool *pool, size_t size, size_t align, const void *p)
  848. {
  849. struct anv_state state;
  850. state = anv_state_pool_alloc(pool, size, align);
  851. memcpy(state.map, p, size);
  852. anv_state_flush(pool->block_pool.device, state);
  853. return state;
  854. }
  855. struct gen8_border_color {
  856. union {
  857. float float32[4];
  858. uint32_t uint32[4];
  859. };
  860. /* Pad out to 64 bytes */
  861. uint32_t _pad[12];
  862. };
  863. static void
  864. anv_device_init_border_colors(struct anv_device *device)
  865. {
  866. static const struct gen8_border_color border_colors[] = {
  867. [VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 0.0 } },
  868. [VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK] = { .float32 = { 0.0, 0.0, 0.0, 1.0 } },
  869. [VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE] = { .float32 = { 1.0, 1.0, 1.0, 1.0 } },
  870. [VK_BORDER_COLOR_INT_TRANSPARENT_BLACK] = { .uint32 = { 0, 0, 0, 0 } },
  871. [VK_BORDER_COLOR_INT_OPAQUE_BLACK] = { .uint32 = { 0, 0, 0, 1 } },
  872. [VK_BORDER_COLOR_INT_OPAQUE_WHITE] = { .uint32 = { 1, 1, 1, 1 } },
  873. };
  874. device->border_colors = anv_state_pool_emit_data(&device->dynamic_state_pool,
  875. sizeof(border_colors), 64,
  876. border_colors);
  877. }
  878. VkResult anv_CreateDevice(
  879. VkPhysicalDevice physicalDevice,
  880. const VkDeviceCreateInfo* pCreateInfo,
  881. const VkAllocationCallbacks* pAllocator,
  882. VkDevice* pDevice)
  883. {
  884. ANV_FROM_HANDLE(anv_physical_device, physical_device, physicalDevice);
  885. VkResult result;
  886. struct anv_device *device;
  887. assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO);
  888. for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; i++) {
  889. const char *ext_name = pCreateInfo->ppEnabledExtensionNames[i];
  890. if (!anv_physical_device_extension_supported(physical_device, ext_name))
  891. return vk_error(VK_ERROR_EXTENSION_NOT_PRESENT);
  892. }
  893. /* Check enabled features */
  894. if (pCreateInfo->pEnabledFeatures) {
  895. VkPhysicalDeviceFeatures supported_features;
  896. anv_GetPhysicalDeviceFeatures(physicalDevice, &supported_features);
  897. VkBool32 *supported_feature = (VkBool32 *)&supported_features;
  898. VkBool32 *enabled_feature = (VkBool32 *)pCreateInfo->pEnabledFeatures;
  899. unsigned num_features = sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
  900. for (uint32_t i = 0; i < num_features; i++) {
  901. if (enabled_feature[i] && !supported_feature[i])
  902. return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
  903. }
  904. }
  905. device = vk_alloc2(&physical_device->instance->alloc, pAllocator,
  906. sizeof(*device), 8,
  907. VK_SYSTEM_ALLOCATION_SCOPE_DEVICE);
  908. if (!device)
  909. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  910. device->_loader_data.loaderMagic = ICD_LOADER_MAGIC;
  911. device->instance = physical_device->instance;
  912. device->chipset_id = physical_device->chipset_id;
  913. device->lost = false;
  914. if (pAllocator)
  915. device->alloc = *pAllocator;
  916. else
  917. device->alloc = physical_device->instance->alloc;
  918. /* XXX(chadv): Can we dup() physicalDevice->fd here? */
  919. device->fd = open(physical_device->path, O_RDWR | O_CLOEXEC);
  920. if (device->fd == -1) {
  921. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  922. goto fail_device;
  923. }
  924. device->context_id = anv_gem_create_context(device);
  925. if (device->context_id == -1) {
  926. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  927. goto fail_fd;
  928. }
  929. device->info = physical_device->info;
  930. device->isl_dev = physical_device->isl_dev;
  931. /* On Broadwell and later, we can use batch chaining to more efficiently
  932. * implement growing command buffers. Prior to Haswell, the kernel
  933. * command parser gets in the way and we have to fall back to growing
  934. * the batch.
  935. */
  936. device->can_chain_batches = device->info.gen >= 8;
  937. device->robust_buffer_access = pCreateInfo->pEnabledFeatures &&
  938. pCreateInfo->pEnabledFeatures->robustBufferAccess;
  939. if (pthread_mutex_init(&device->mutex, NULL) != 0) {
  940. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  941. goto fail_context_id;
  942. }
  943. pthread_condattr_t condattr;
  944. if (pthread_condattr_init(&condattr) != 0) {
  945. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  946. goto fail_mutex;
  947. }
  948. if (pthread_condattr_setclock(&condattr, CLOCK_MONOTONIC) != 0) {
  949. pthread_condattr_destroy(&condattr);
  950. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  951. goto fail_mutex;
  952. }
  953. if (pthread_cond_init(&device->queue_submit, NULL) != 0) {
  954. pthread_condattr_destroy(&condattr);
  955. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  956. goto fail_mutex;
  957. }
  958. pthread_condattr_destroy(&condattr);
  959. anv_bo_pool_init(&device->batch_bo_pool, device);
  960. result = anv_bo_cache_init(&device->bo_cache);
  961. if (result != VK_SUCCESS)
  962. goto fail_batch_bo_pool;
  963. result = anv_state_pool_init(&device->dynamic_state_pool, device, 16384);
  964. if (result != VK_SUCCESS)
  965. goto fail_bo_cache;
  966. result = anv_state_pool_init(&device->instruction_state_pool, device, 16384);
  967. if (result != VK_SUCCESS)
  968. goto fail_dynamic_state_pool;
  969. result = anv_state_pool_init(&device->surface_state_pool, device, 4096);
  970. if (result != VK_SUCCESS)
  971. goto fail_instruction_state_pool;
  972. result = anv_bo_init_new(&device->workaround_bo, device, 1024);
  973. if (result != VK_SUCCESS)
  974. goto fail_surface_state_pool;
  975. anv_scratch_pool_init(device, &device->scratch_pool);
  976. anv_queue_init(device, &device->queue);
  977. switch (device->info.gen) {
  978. case 7:
  979. if (!device->info.is_haswell)
  980. result = gen7_init_device_state(device);
  981. else
  982. result = gen75_init_device_state(device);
  983. break;
  984. case 8:
  985. result = gen8_init_device_state(device);
  986. break;
  987. case 9:
  988. result = gen9_init_device_state(device);
  989. break;
  990. case 10:
  991. result = gen10_init_device_state(device);
  992. break;
  993. default:
  994. /* Shouldn't get here as we don't create physical devices for any other
  995. * gens. */
  996. unreachable("unhandled gen");
  997. }
  998. if (result != VK_SUCCESS)
  999. goto fail_workaround_bo;
  1000. anv_device_init_blorp(device);
  1001. anv_device_init_border_colors(device);
  1002. *pDevice = anv_device_to_handle(device);
  1003. return VK_SUCCESS;
  1004. fail_workaround_bo:
  1005. anv_queue_finish(&device->queue);
  1006. anv_scratch_pool_finish(device, &device->scratch_pool);
  1007. anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
  1008. anv_gem_close(device, device->workaround_bo.gem_handle);
  1009. fail_surface_state_pool:
  1010. anv_state_pool_finish(&device->surface_state_pool);
  1011. fail_instruction_state_pool:
  1012. anv_state_pool_finish(&device->instruction_state_pool);
  1013. fail_dynamic_state_pool:
  1014. anv_state_pool_finish(&device->dynamic_state_pool);
  1015. fail_bo_cache:
  1016. anv_bo_cache_finish(&device->bo_cache);
  1017. fail_batch_bo_pool:
  1018. anv_bo_pool_finish(&device->batch_bo_pool);
  1019. pthread_cond_destroy(&device->queue_submit);
  1020. fail_mutex:
  1021. pthread_mutex_destroy(&device->mutex);
  1022. fail_context_id:
  1023. anv_gem_destroy_context(device, device->context_id);
  1024. fail_fd:
  1025. close(device->fd);
  1026. fail_device:
  1027. vk_free(&device->alloc, device);
  1028. return result;
  1029. }
  1030. void anv_DestroyDevice(
  1031. VkDevice _device,
  1032. const VkAllocationCallbacks* pAllocator)
  1033. {
  1034. ANV_FROM_HANDLE(anv_device, device, _device);
  1035. if (!device)
  1036. return;
  1037. anv_device_finish_blorp(device);
  1038. anv_queue_finish(&device->queue);
  1039. #ifdef HAVE_VALGRIND
  1040. /* We only need to free these to prevent valgrind errors. The backing
  1041. * BO will go away in a couple of lines so we don't actually leak.
  1042. */
  1043. anv_state_pool_free(&device->dynamic_state_pool, device->border_colors);
  1044. #endif
  1045. anv_scratch_pool_finish(device, &device->scratch_pool);
  1046. anv_gem_munmap(device->workaround_bo.map, device->workaround_bo.size);
  1047. anv_gem_close(device, device->workaround_bo.gem_handle);
  1048. anv_state_pool_finish(&device->surface_state_pool);
  1049. anv_state_pool_finish(&device->instruction_state_pool);
  1050. anv_state_pool_finish(&device->dynamic_state_pool);
  1051. anv_bo_cache_finish(&device->bo_cache);
  1052. anv_bo_pool_finish(&device->batch_bo_pool);
  1053. pthread_cond_destroy(&device->queue_submit);
  1054. pthread_mutex_destroy(&device->mutex);
  1055. anv_gem_destroy_context(device, device->context_id);
  1056. close(device->fd);
  1057. vk_free(&device->alloc, device);
  1058. }
  1059. VkResult anv_EnumerateInstanceLayerProperties(
  1060. uint32_t* pPropertyCount,
  1061. VkLayerProperties* pProperties)
  1062. {
  1063. if (pProperties == NULL) {
  1064. *pPropertyCount = 0;
  1065. return VK_SUCCESS;
  1066. }
  1067. /* None supported at this time */
  1068. return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
  1069. }
  1070. VkResult anv_EnumerateDeviceLayerProperties(
  1071. VkPhysicalDevice physicalDevice,
  1072. uint32_t* pPropertyCount,
  1073. VkLayerProperties* pProperties)
  1074. {
  1075. if (pProperties == NULL) {
  1076. *pPropertyCount = 0;
  1077. return VK_SUCCESS;
  1078. }
  1079. /* None supported at this time */
  1080. return vk_error(VK_ERROR_LAYER_NOT_PRESENT);
  1081. }
  1082. void anv_GetDeviceQueue(
  1083. VkDevice _device,
  1084. uint32_t queueNodeIndex,
  1085. uint32_t queueIndex,
  1086. VkQueue* pQueue)
  1087. {
  1088. ANV_FROM_HANDLE(anv_device, device, _device);
  1089. assert(queueIndex == 0);
  1090. *pQueue = anv_queue_to_handle(&device->queue);
  1091. }
  1092. VkResult
  1093. anv_device_query_status(struct anv_device *device)
  1094. {
  1095. /* This isn't likely as most of the callers of this function already check
  1096. * for it. However, it doesn't hurt to check and it potentially lets us
  1097. * avoid an ioctl.
  1098. */
  1099. if (unlikely(device->lost))
  1100. return VK_ERROR_DEVICE_LOST;
  1101. uint32_t active, pending;
  1102. int ret = anv_gem_gpu_get_reset_stats(device, &active, &pending);
  1103. if (ret == -1) {
  1104. /* We don't know the real error. */
  1105. device->lost = true;
  1106. return vk_errorf(VK_ERROR_DEVICE_LOST, "get_reset_stats failed: %m");
  1107. }
  1108. if (active) {
  1109. device->lost = true;
  1110. return vk_errorf(VK_ERROR_DEVICE_LOST,
  1111. "GPU hung on one of our command buffers");
  1112. } else if (pending) {
  1113. device->lost = true;
  1114. return vk_errorf(VK_ERROR_DEVICE_LOST,
  1115. "GPU hung with commands in-flight");
  1116. }
  1117. return VK_SUCCESS;
  1118. }
  1119. VkResult
  1120. anv_device_bo_busy(struct anv_device *device, struct anv_bo *bo)
  1121. {
  1122. /* Note: This only returns whether or not the BO is in use by an i915 GPU.
  1123. * Other usages of the BO (such as on different hardware) will not be
  1124. * flagged as "busy" by this ioctl. Use with care.
  1125. */
  1126. int ret = anv_gem_busy(device, bo->gem_handle);
  1127. if (ret == 1) {
  1128. return VK_NOT_READY;
  1129. } else if (ret == -1) {
  1130. /* We don't know the real error. */
  1131. device->lost = true;
  1132. return vk_errorf(VK_ERROR_DEVICE_LOST, "gem wait failed: %m");
  1133. }
  1134. /* Query for device status after the busy call. If the BO we're checking
  1135. * got caught in a GPU hang we don't want to return VK_SUCCESS to the
  1136. * client because it clearly doesn't have valid data. Yes, this most
  1137. * likely means an ioctl, but we just did an ioctl to query the busy status
  1138. * so it's no great loss.
  1139. */
  1140. return anv_device_query_status(device);
  1141. }
  1142. VkResult
  1143. anv_device_wait(struct anv_device *device, struct anv_bo *bo,
  1144. int64_t timeout)
  1145. {
  1146. int ret = anv_gem_wait(device, bo->gem_handle, &timeout);
  1147. if (ret == -1 && errno == ETIME) {
  1148. return VK_TIMEOUT;
  1149. } else if (ret == -1) {
  1150. /* We don't know the real error. */
  1151. device->lost = true;
  1152. return vk_errorf(VK_ERROR_DEVICE_LOST, "gem wait failed: %m");
  1153. }
  1154. /* Query for device status after the wait. If the BO we're waiting on got
  1155. * caught in a GPU hang we don't want to return VK_SUCCESS to the client
  1156. * because it clearly doesn't have valid data. Yes, this most likely means
  1157. * an ioctl, but we just did an ioctl to wait so it's no great loss.
  1158. */
  1159. return anv_device_query_status(device);
  1160. }
  1161. VkResult anv_DeviceWaitIdle(
  1162. VkDevice _device)
  1163. {
  1164. ANV_FROM_HANDLE(anv_device, device, _device);
  1165. if (unlikely(device->lost))
  1166. return VK_ERROR_DEVICE_LOST;
  1167. struct anv_batch batch;
  1168. uint32_t cmds[8];
  1169. batch.start = batch.next = cmds;
  1170. batch.end = (void *) cmds + sizeof(cmds);
  1171. anv_batch_emit(&batch, GEN7_MI_BATCH_BUFFER_END, bbe);
  1172. anv_batch_emit(&batch, GEN7_MI_NOOP, noop);
  1173. return anv_device_submit_simple_batch(device, &batch);
  1174. }
  1175. VkResult
  1176. anv_bo_init_new(struct anv_bo *bo, struct anv_device *device, uint64_t size)
  1177. {
  1178. uint32_t gem_handle = anv_gem_create(device, size);
  1179. if (!gem_handle)
  1180. return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
  1181. anv_bo_init(bo, gem_handle, size);
  1182. return VK_SUCCESS;
  1183. }
  1184. VkResult anv_AllocateMemory(
  1185. VkDevice _device,
  1186. const VkMemoryAllocateInfo* pAllocateInfo,
  1187. const VkAllocationCallbacks* pAllocator,
  1188. VkDeviceMemory* pMem)
  1189. {
  1190. ANV_FROM_HANDLE(anv_device, device, _device);
  1191. struct anv_physical_device *pdevice = &device->instance->physicalDevice;
  1192. struct anv_device_memory *mem;
  1193. VkResult result = VK_SUCCESS;
  1194. assert(pAllocateInfo->sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO);
  1195. /* The Vulkan 1.0.33 spec says "allocationSize must be greater than 0". */
  1196. assert(pAllocateInfo->allocationSize > 0);
  1197. /* The kernel relocation API has a limitation of a 32-bit delta value
  1198. * applied to the address before it is written which, in spite of it being
  1199. * unsigned, is treated as signed . Because of the way that this maps to
  1200. * the Vulkan API, we cannot handle an offset into a buffer that does not
  1201. * fit into a signed 32 bits. The only mechanism we have for dealing with
  1202. * this at the moment is to limit all VkDeviceMemory objects to a maximum
  1203. * of 2GB each. The Vulkan spec allows us to do this:
  1204. *
  1205. * "Some platforms may have a limit on the maximum size of a single
  1206. * allocation. For example, certain systems may fail to create
  1207. * allocations with a size greater than or equal to 4GB. Such a limit is
  1208. * implementation-dependent, and if such a failure occurs then the error
  1209. * VK_ERROR_OUT_OF_DEVICE_MEMORY should be returned."
  1210. *
  1211. * We don't use vk_error here because it's not an error so much as an
  1212. * indication to the application that the allocation is too large.
  1213. */
  1214. if (pAllocateInfo->allocationSize > (1ull << 31))
  1215. return VK_ERROR_OUT_OF_DEVICE_MEMORY;
  1216. /* FINISHME: Fail if allocation request exceeds heap size. */
  1217. mem = vk_alloc2(&device->alloc, pAllocator, sizeof(*mem), 8,
  1218. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  1219. if (mem == NULL)
  1220. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  1221. assert(pAllocateInfo->memoryTypeIndex < pdevice->memory.type_count);
  1222. mem->type = &pdevice->memory.types[pAllocateInfo->memoryTypeIndex];
  1223. mem->map = NULL;
  1224. mem->map_size = 0;
  1225. const VkImportMemoryFdInfoKHR *fd_info =
  1226. vk_find_struct_const(pAllocateInfo->pNext, IMPORT_MEMORY_FD_INFO_KHR);
  1227. /* The Vulkan spec permits handleType to be 0, in which case the struct is
  1228. * ignored.
  1229. */
  1230. if (fd_info && fd_info->handleType) {
  1231. /* At the moment, we only support the OPAQUE_FD memory type which is
  1232. * just a GEM buffer.
  1233. */
  1234. assert(fd_info->handleType ==
  1235. VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR);
  1236. result = anv_bo_cache_import(device, &device->bo_cache,
  1237. fd_info->fd, pAllocateInfo->allocationSize,
  1238. &mem->bo);
  1239. if (result != VK_SUCCESS)
  1240. goto fail;
  1241. } else {
  1242. result = anv_bo_cache_alloc(device, &device->bo_cache,
  1243. pAllocateInfo->allocationSize,
  1244. &mem->bo);
  1245. if (result != VK_SUCCESS)
  1246. goto fail;
  1247. }
  1248. assert(mem->type->heapIndex < pdevice->memory.heap_count);
  1249. if (pdevice->memory.heaps[mem->type->heapIndex].supports_48bit_addresses)
  1250. mem->bo->flags |= EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
  1251. if (pdevice->has_exec_async)
  1252. mem->bo->flags |= EXEC_OBJECT_ASYNC;
  1253. *pMem = anv_device_memory_to_handle(mem);
  1254. return VK_SUCCESS;
  1255. fail:
  1256. vk_free2(&device->alloc, pAllocator, mem);
  1257. return result;
  1258. }
  1259. VkResult anv_GetMemoryFdKHR(
  1260. VkDevice device_h,
  1261. const VkMemoryGetFdInfoKHR* pGetFdInfo,
  1262. int* pFd)
  1263. {
  1264. ANV_FROM_HANDLE(anv_device, dev, device_h);
  1265. ANV_FROM_HANDLE(anv_device_memory, mem, pGetFdInfo->memory);
  1266. assert(pGetFdInfo->sType == VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR);
  1267. /* We support only one handle type. */
  1268. assert(pGetFdInfo->handleType ==
  1269. VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT_KHR);
  1270. return anv_bo_cache_export(dev, &dev->bo_cache, mem->bo, pFd);
  1271. }
  1272. VkResult anv_GetMemoryFdPropertiesKHR(
  1273. VkDevice device_h,
  1274. VkExternalMemoryHandleTypeFlagBitsKHR handleType,
  1275. int fd,
  1276. VkMemoryFdPropertiesKHR* pMemoryFdProperties)
  1277. {
  1278. /* The valid usage section for this function says:
  1279. *
  1280. * "handleType must not be one of the handle types defined as opaque."
  1281. *
  1282. * Since we only handle opaque handles for now, there are no FD properties.
  1283. */
  1284. return VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR;
  1285. }
  1286. void anv_FreeMemory(
  1287. VkDevice _device,
  1288. VkDeviceMemory _mem,
  1289. const VkAllocationCallbacks* pAllocator)
  1290. {
  1291. ANV_FROM_HANDLE(anv_device, device, _device);
  1292. ANV_FROM_HANDLE(anv_device_memory, mem, _mem);
  1293. if (mem == NULL)
  1294. return;
  1295. if (mem->map)
  1296. anv_UnmapMemory(_device, _mem);
  1297. anv_bo_cache_release(device, &device->bo_cache, mem->bo);
  1298. vk_free2(&device->alloc, pAllocator, mem);
  1299. }
  1300. VkResult anv_MapMemory(
  1301. VkDevice _device,
  1302. VkDeviceMemory _memory,
  1303. VkDeviceSize offset,
  1304. VkDeviceSize size,
  1305. VkMemoryMapFlags flags,
  1306. void** ppData)
  1307. {
  1308. ANV_FROM_HANDLE(anv_device, device, _device);
  1309. ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
  1310. if (mem == NULL) {
  1311. *ppData = NULL;
  1312. return VK_SUCCESS;
  1313. }
  1314. if (size == VK_WHOLE_SIZE)
  1315. size = mem->bo->size - offset;
  1316. /* From the Vulkan spec version 1.0.32 docs for MapMemory:
  1317. *
  1318. * * If size is not equal to VK_WHOLE_SIZE, size must be greater than 0
  1319. * assert(size != 0);
  1320. * * If size is not equal to VK_WHOLE_SIZE, size must be less than or
  1321. * equal to the size of the memory minus offset
  1322. */
  1323. assert(size > 0);
  1324. assert(offset + size <= mem->bo->size);
  1325. /* FIXME: Is this supposed to be thread safe? Since vkUnmapMemory() only
  1326. * takes a VkDeviceMemory pointer, it seems like only one map of the memory
  1327. * at a time is valid. We could just mmap up front and return an offset
  1328. * pointer here, but that may exhaust virtual memory on 32 bit
  1329. * userspace. */
  1330. uint32_t gem_flags = 0;
  1331. if (!device->info.has_llc &&
  1332. (mem->type->propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
  1333. gem_flags |= I915_MMAP_WC;
  1334. /* GEM will fail to map if the offset isn't 4k-aligned. Round down. */
  1335. uint64_t map_offset = offset & ~4095ull;
  1336. assert(offset >= map_offset);
  1337. uint64_t map_size = (offset + size) - map_offset;
  1338. /* Let's map whole pages */
  1339. map_size = align_u64(map_size, 4096);
  1340. void *map = anv_gem_mmap(device, mem->bo->gem_handle,
  1341. map_offset, map_size, gem_flags);
  1342. if (map == MAP_FAILED)
  1343. return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
  1344. mem->map = map;
  1345. mem->map_size = map_size;
  1346. *ppData = mem->map + (offset - map_offset);
  1347. return VK_SUCCESS;
  1348. }
  1349. void anv_UnmapMemory(
  1350. VkDevice _device,
  1351. VkDeviceMemory _memory)
  1352. {
  1353. ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
  1354. if (mem == NULL)
  1355. return;
  1356. anv_gem_munmap(mem->map, mem->map_size);
  1357. mem->map = NULL;
  1358. mem->map_size = 0;
  1359. }
  1360. static void
  1361. clflush_mapped_ranges(struct anv_device *device,
  1362. uint32_t count,
  1363. const VkMappedMemoryRange *ranges)
  1364. {
  1365. for (uint32_t i = 0; i < count; i++) {
  1366. ANV_FROM_HANDLE(anv_device_memory, mem, ranges[i].memory);
  1367. if (ranges[i].offset >= mem->map_size)
  1368. continue;
  1369. gen_clflush_range(mem->map + ranges[i].offset,
  1370. MIN2(ranges[i].size, mem->map_size - ranges[i].offset));
  1371. }
  1372. }
  1373. VkResult anv_FlushMappedMemoryRanges(
  1374. VkDevice _device,
  1375. uint32_t memoryRangeCount,
  1376. const VkMappedMemoryRange* pMemoryRanges)
  1377. {
  1378. ANV_FROM_HANDLE(anv_device, device, _device);
  1379. if (device->info.has_llc)
  1380. return VK_SUCCESS;
  1381. /* Make sure the writes we're flushing have landed. */
  1382. __builtin_ia32_mfence();
  1383. clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
  1384. return VK_SUCCESS;
  1385. }
  1386. VkResult anv_InvalidateMappedMemoryRanges(
  1387. VkDevice _device,
  1388. uint32_t memoryRangeCount,
  1389. const VkMappedMemoryRange* pMemoryRanges)
  1390. {
  1391. ANV_FROM_HANDLE(anv_device, device, _device);
  1392. if (device->info.has_llc)
  1393. return VK_SUCCESS;
  1394. clflush_mapped_ranges(device, memoryRangeCount, pMemoryRanges);
  1395. /* Make sure no reads get moved up above the invalidate. */
  1396. __builtin_ia32_mfence();
  1397. return VK_SUCCESS;
  1398. }
  1399. void anv_GetBufferMemoryRequirements(
  1400. VkDevice _device,
  1401. VkBuffer _buffer,
  1402. VkMemoryRequirements* pMemoryRequirements)
  1403. {
  1404. ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
  1405. ANV_FROM_HANDLE(anv_device, device, _device);
  1406. struct anv_physical_device *pdevice = &device->instance->physicalDevice;
  1407. /* The Vulkan spec (git aaed022) says:
  1408. *
  1409. * memoryTypeBits is a bitfield and contains one bit set for every
  1410. * supported memory type for the resource. The bit `1<<i` is set if and
  1411. * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
  1412. * structure for the physical device is supported.
  1413. */
  1414. uint32_t memory_types = 0;
  1415. for (uint32_t i = 0; i < pdevice->memory.type_count; i++) {
  1416. uint32_t valid_usage = pdevice->memory.types[i].valid_buffer_usage;
  1417. if ((valid_usage & buffer->usage) == buffer->usage)
  1418. memory_types |= (1u << i);
  1419. }
  1420. pMemoryRequirements->size = buffer->size;
  1421. pMemoryRequirements->alignment = 16;
  1422. pMemoryRequirements->memoryTypeBits = memory_types;
  1423. }
  1424. void anv_GetBufferMemoryRequirements2KHR(
  1425. VkDevice _device,
  1426. const VkBufferMemoryRequirementsInfo2KHR* pInfo,
  1427. VkMemoryRequirements2KHR* pMemoryRequirements)
  1428. {
  1429. anv_GetBufferMemoryRequirements(_device, pInfo->buffer,
  1430. &pMemoryRequirements->memoryRequirements);
  1431. vk_foreach_struct(ext, pMemoryRequirements->pNext) {
  1432. switch (ext->sType) {
  1433. case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
  1434. VkMemoryDedicatedRequirementsKHR *requirements = (void *)ext;
  1435. requirements->prefersDedicatedAllocation = VK_FALSE;
  1436. requirements->requiresDedicatedAllocation = VK_FALSE;
  1437. break;
  1438. }
  1439. default:
  1440. anv_debug_ignored_stype(ext->sType);
  1441. break;
  1442. }
  1443. }
  1444. }
  1445. void anv_GetImageMemoryRequirements(
  1446. VkDevice _device,
  1447. VkImage _image,
  1448. VkMemoryRequirements* pMemoryRequirements)
  1449. {
  1450. ANV_FROM_HANDLE(anv_image, image, _image);
  1451. ANV_FROM_HANDLE(anv_device, device, _device);
  1452. struct anv_physical_device *pdevice = &device->instance->physicalDevice;
  1453. /* The Vulkan spec (git aaed022) says:
  1454. *
  1455. * memoryTypeBits is a bitfield and contains one bit set for every
  1456. * supported memory type for the resource. The bit `1<<i` is set if and
  1457. * only if the memory type `i` in the VkPhysicalDeviceMemoryProperties
  1458. * structure for the physical device is supported.
  1459. *
  1460. * All types are currently supported for images.
  1461. */
  1462. uint32_t memory_types = (1ull << pdevice->memory.type_count) - 1;
  1463. pMemoryRequirements->size = image->size;
  1464. pMemoryRequirements->alignment = image->alignment;
  1465. pMemoryRequirements->memoryTypeBits = memory_types;
  1466. }
  1467. void anv_GetImageMemoryRequirements2KHR(
  1468. VkDevice _device,
  1469. const VkImageMemoryRequirementsInfo2KHR* pInfo,
  1470. VkMemoryRequirements2KHR* pMemoryRequirements)
  1471. {
  1472. anv_GetImageMemoryRequirements(_device, pInfo->image,
  1473. &pMemoryRequirements->memoryRequirements);
  1474. vk_foreach_struct(ext, pMemoryRequirements->pNext) {
  1475. switch (ext->sType) {
  1476. case VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR: {
  1477. VkMemoryDedicatedRequirementsKHR *requirements = (void *)ext;
  1478. requirements->prefersDedicatedAllocation = VK_FALSE;
  1479. requirements->requiresDedicatedAllocation = VK_FALSE;
  1480. break;
  1481. }
  1482. default:
  1483. anv_debug_ignored_stype(ext->sType);
  1484. break;
  1485. }
  1486. }
  1487. }
  1488. void anv_GetImageSparseMemoryRequirements(
  1489. VkDevice device,
  1490. VkImage image,
  1491. uint32_t* pSparseMemoryRequirementCount,
  1492. VkSparseImageMemoryRequirements* pSparseMemoryRequirements)
  1493. {
  1494. *pSparseMemoryRequirementCount = 0;
  1495. }
  1496. void anv_GetImageSparseMemoryRequirements2KHR(
  1497. VkDevice device,
  1498. const VkImageSparseMemoryRequirementsInfo2KHR* pInfo,
  1499. uint32_t* pSparseMemoryRequirementCount,
  1500. VkSparseImageMemoryRequirements2KHR* pSparseMemoryRequirements)
  1501. {
  1502. *pSparseMemoryRequirementCount = 0;
  1503. }
  1504. void anv_GetDeviceMemoryCommitment(
  1505. VkDevice device,
  1506. VkDeviceMemory memory,
  1507. VkDeviceSize* pCommittedMemoryInBytes)
  1508. {
  1509. *pCommittedMemoryInBytes = 0;
  1510. }
  1511. VkResult anv_BindBufferMemory(
  1512. VkDevice device,
  1513. VkBuffer _buffer,
  1514. VkDeviceMemory _memory,
  1515. VkDeviceSize memoryOffset)
  1516. {
  1517. ANV_FROM_HANDLE(anv_device_memory, mem, _memory);
  1518. ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
  1519. if (mem) {
  1520. assert((buffer->usage & mem->type->valid_buffer_usage) == buffer->usage);
  1521. buffer->bo = mem->bo;
  1522. buffer->offset = memoryOffset;
  1523. } else {
  1524. buffer->bo = NULL;
  1525. buffer->offset = 0;
  1526. }
  1527. return VK_SUCCESS;
  1528. }
  1529. VkResult anv_QueueBindSparse(
  1530. VkQueue _queue,
  1531. uint32_t bindInfoCount,
  1532. const VkBindSparseInfo* pBindInfo,
  1533. VkFence fence)
  1534. {
  1535. ANV_FROM_HANDLE(anv_queue, queue, _queue);
  1536. if (unlikely(queue->device->lost))
  1537. return VK_ERROR_DEVICE_LOST;
  1538. return vk_error(VK_ERROR_FEATURE_NOT_PRESENT);
  1539. }
  1540. // Event functions
  1541. VkResult anv_CreateEvent(
  1542. VkDevice _device,
  1543. const VkEventCreateInfo* pCreateInfo,
  1544. const VkAllocationCallbacks* pAllocator,
  1545. VkEvent* pEvent)
  1546. {
  1547. ANV_FROM_HANDLE(anv_device, device, _device);
  1548. struct anv_state state;
  1549. struct anv_event *event;
  1550. assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO);
  1551. state = anv_state_pool_alloc(&device->dynamic_state_pool,
  1552. sizeof(*event), 8);
  1553. event = state.map;
  1554. event->state = state;
  1555. event->semaphore = VK_EVENT_RESET;
  1556. if (!device->info.has_llc) {
  1557. /* Make sure the writes we're flushing have landed. */
  1558. __builtin_ia32_mfence();
  1559. __builtin_ia32_clflush(event);
  1560. }
  1561. *pEvent = anv_event_to_handle(event);
  1562. return VK_SUCCESS;
  1563. }
  1564. void anv_DestroyEvent(
  1565. VkDevice _device,
  1566. VkEvent _event,
  1567. const VkAllocationCallbacks* pAllocator)
  1568. {
  1569. ANV_FROM_HANDLE(anv_device, device, _device);
  1570. ANV_FROM_HANDLE(anv_event, event, _event);
  1571. if (!event)
  1572. return;
  1573. anv_state_pool_free(&device->dynamic_state_pool, event->state);
  1574. }
  1575. VkResult anv_GetEventStatus(
  1576. VkDevice _device,
  1577. VkEvent _event)
  1578. {
  1579. ANV_FROM_HANDLE(anv_device, device, _device);
  1580. ANV_FROM_HANDLE(anv_event, event, _event);
  1581. if (unlikely(device->lost))
  1582. return VK_ERROR_DEVICE_LOST;
  1583. if (!device->info.has_llc) {
  1584. /* Invalidate read cache before reading event written by GPU. */
  1585. __builtin_ia32_clflush(event);
  1586. __builtin_ia32_mfence();
  1587. }
  1588. return event->semaphore;
  1589. }
  1590. VkResult anv_SetEvent(
  1591. VkDevice _device,
  1592. VkEvent _event)
  1593. {
  1594. ANV_FROM_HANDLE(anv_device, device, _device);
  1595. ANV_FROM_HANDLE(anv_event, event, _event);
  1596. event->semaphore = VK_EVENT_SET;
  1597. if (!device->info.has_llc) {
  1598. /* Make sure the writes we're flushing have landed. */
  1599. __builtin_ia32_mfence();
  1600. __builtin_ia32_clflush(event);
  1601. }
  1602. return VK_SUCCESS;
  1603. }
  1604. VkResult anv_ResetEvent(
  1605. VkDevice _device,
  1606. VkEvent _event)
  1607. {
  1608. ANV_FROM_HANDLE(anv_device, device, _device);
  1609. ANV_FROM_HANDLE(anv_event, event, _event);
  1610. event->semaphore = VK_EVENT_RESET;
  1611. if (!device->info.has_llc) {
  1612. /* Make sure the writes we're flushing have landed. */
  1613. __builtin_ia32_mfence();
  1614. __builtin_ia32_clflush(event);
  1615. }
  1616. return VK_SUCCESS;
  1617. }
  1618. // Buffer functions
  1619. VkResult anv_CreateBuffer(
  1620. VkDevice _device,
  1621. const VkBufferCreateInfo* pCreateInfo,
  1622. const VkAllocationCallbacks* pAllocator,
  1623. VkBuffer* pBuffer)
  1624. {
  1625. ANV_FROM_HANDLE(anv_device, device, _device);
  1626. struct anv_buffer *buffer;
  1627. assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO);
  1628. buffer = vk_alloc2(&device->alloc, pAllocator, sizeof(*buffer), 8,
  1629. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  1630. if (buffer == NULL)
  1631. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  1632. buffer->size = pCreateInfo->size;
  1633. buffer->usage = pCreateInfo->usage;
  1634. buffer->bo = NULL;
  1635. buffer->offset = 0;
  1636. *pBuffer = anv_buffer_to_handle(buffer);
  1637. return VK_SUCCESS;
  1638. }
  1639. void anv_DestroyBuffer(
  1640. VkDevice _device,
  1641. VkBuffer _buffer,
  1642. const VkAllocationCallbacks* pAllocator)
  1643. {
  1644. ANV_FROM_HANDLE(anv_device, device, _device);
  1645. ANV_FROM_HANDLE(anv_buffer, buffer, _buffer);
  1646. if (!buffer)
  1647. return;
  1648. vk_free2(&device->alloc, pAllocator, buffer);
  1649. }
  1650. void
  1651. anv_fill_buffer_surface_state(struct anv_device *device, struct anv_state state,
  1652. enum isl_format format,
  1653. uint32_t offset, uint32_t range, uint32_t stride)
  1654. {
  1655. isl_buffer_fill_state(&device->isl_dev, state.map,
  1656. .address = offset,
  1657. .mocs = device->default_mocs,
  1658. .size = range,
  1659. .format = format,
  1660. .stride = stride);
  1661. anv_state_flush(device, state);
  1662. }
  1663. void anv_DestroySampler(
  1664. VkDevice _device,
  1665. VkSampler _sampler,
  1666. const VkAllocationCallbacks* pAllocator)
  1667. {
  1668. ANV_FROM_HANDLE(anv_device, device, _device);
  1669. ANV_FROM_HANDLE(anv_sampler, sampler, _sampler);
  1670. if (!sampler)
  1671. return;
  1672. vk_free2(&device->alloc, pAllocator, sampler);
  1673. }
  1674. VkResult anv_CreateFramebuffer(
  1675. VkDevice _device,
  1676. const VkFramebufferCreateInfo* pCreateInfo,
  1677. const VkAllocationCallbacks* pAllocator,
  1678. VkFramebuffer* pFramebuffer)
  1679. {
  1680. ANV_FROM_HANDLE(anv_device, device, _device);
  1681. struct anv_framebuffer *framebuffer;
  1682. assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO);
  1683. size_t size = sizeof(*framebuffer) +
  1684. sizeof(struct anv_image_view *) * pCreateInfo->attachmentCount;
  1685. framebuffer = vk_alloc2(&device->alloc, pAllocator, size, 8,
  1686. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  1687. if (framebuffer == NULL)
  1688. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  1689. framebuffer->attachment_count = pCreateInfo->attachmentCount;
  1690. for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++) {
  1691. VkImageView _iview = pCreateInfo->pAttachments[i];
  1692. framebuffer->attachments[i] = anv_image_view_from_handle(_iview);
  1693. }
  1694. framebuffer->width = pCreateInfo->width;
  1695. framebuffer->height = pCreateInfo->height;
  1696. framebuffer->layers = pCreateInfo->layers;
  1697. *pFramebuffer = anv_framebuffer_to_handle(framebuffer);
  1698. return VK_SUCCESS;
  1699. }
  1700. void anv_DestroyFramebuffer(
  1701. VkDevice _device,
  1702. VkFramebuffer _fb,
  1703. const VkAllocationCallbacks* pAllocator)
  1704. {
  1705. ANV_FROM_HANDLE(anv_device, device, _device);
  1706. ANV_FROM_HANDLE(anv_framebuffer, fb, _fb);
  1707. if (!fb)
  1708. return;
  1709. vk_free2(&device->alloc, pAllocator, fb);
  1710. }
  1711. /* vk_icd.h does not declare this function, so we declare it here to
  1712. * suppress Wmissing-prototypes.
  1713. */
  1714. PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
  1715. vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion);
  1716. PUBLIC VKAPI_ATTR VkResult VKAPI_CALL
  1717. vk_icdNegotiateLoaderICDInterfaceVersion(uint32_t* pSupportedVersion)
  1718. {
  1719. /* For the full details on loader interface versioning, see
  1720. * <https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/loader/LoaderAndLayerInterface.md>.
  1721. * What follows is a condensed summary, to help you navigate the large and
  1722. * confusing official doc.
  1723. *
  1724. * - Loader interface v0 is incompatible with later versions. We don't
  1725. * support it.
  1726. *
  1727. * - In loader interface v1:
  1728. * - The first ICD entrypoint called by the loader is
  1729. * vk_icdGetInstanceProcAddr(). The ICD must statically expose this
  1730. * entrypoint.
  1731. * - The ICD must statically expose no other Vulkan symbol unless it is
  1732. * linked with -Bsymbolic.
  1733. * - Each dispatchable Vulkan handle created by the ICD must be
  1734. * a pointer to a struct whose first member is VK_LOADER_DATA. The
  1735. * ICD must initialize VK_LOADER_DATA.loadMagic to ICD_LOADER_MAGIC.
  1736. * - The loader implements vkCreate{PLATFORM}SurfaceKHR() and
  1737. * vkDestroySurfaceKHR(). The ICD must be capable of working with
  1738. * such loader-managed surfaces.
  1739. *
  1740. * - Loader interface v2 differs from v1 in:
  1741. * - The first ICD entrypoint called by the loader is
  1742. * vk_icdNegotiateLoaderICDInterfaceVersion(). The ICD must
  1743. * statically expose this entrypoint.
  1744. *
  1745. * - Loader interface v3 differs from v2 in:
  1746. * - The ICD must implement vkCreate{PLATFORM}SurfaceKHR(),
  1747. * vkDestroySurfaceKHR(), and other API which uses VKSurfaceKHR,
  1748. * because the loader no longer does so.
  1749. */
  1750. *pSupportedVersion = MIN2(*pSupportedVersion, 3u);
  1751. return VK_SUCCESS;
  1752. }