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_allocator.c 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  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 <stdlib.h>
  24. #include <unistd.h>
  25. #include <limits.h>
  26. #include <assert.h>
  27. #include <linux/memfd.h>
  28. #include <sys/mman.h>
  29. #include "anv_private.h"
  30. #include "util/hash_table.h"
  31. #include "util/simple_mtx.h"
  32. #ifdef HAVE_VALGRIND
  33. #define VG_NOACCESS_READ(__ptr) ({ \
  34. VALGRIND_MAKE_MEM_DEFINED((__ptr), sizeof(*(__ptr))); \
  35. __typeof(*(__ptr)) __val = *(__ptr); \
  36. VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr)));\
  37. __val; \
  38. })
  39. #define VG_NOACCESS_WRITE(__ptr, __val) ({ \
  40. VALGRIND_MAKE_MEM_UNDEFINED((__ptr), sizeof(*(__ptr))); \
  41. *(__ptr) = (__val); \
  42. VALGRIND_MAKE_MEM_NOACCESS((__ptr), sizeof(*(__ptr))); \
  43. })
  44. #else
  45. #define VG_NOACCESS_READ(__ptr) (*(__ptr))
  46. #define VG_NOACCESS_WRITE(__ptr, __val) (*(__ptr) = (__val))
  47. #endif
  48. /* Design goals:
  49. *
  50. * - Lock free (except when resizing underlying bos)
  51. *
  52. * - Constant time allocation with typically only one atomic
  53. *
  54. * - Multiple allocation sizes without fragmentation
  55. *
  56. * - Can grow while keeping addresses and offset of contents stable
  57. *
  58. * - All allocations within one bo so we can point one of the
  59. * STATE_BASE_ADDRESS pointers at it.
  60. *
  61. * The overall design is a two-level allocator: top level is a fixed size, big
  62. * block (8k) allocator, which operates out of a bo. Allocation is done by
  63. * either pulling a block from the free list or growing the used range of the
  64. * bo. Growing the range may run out of space in the bo which we then need to
  65. * grow. Growing the bo is tricky in a multi-threaded, lockless environment:
  66. * we need to keep all pointers and contents in the old map valid. GEM bos in
  67. * general can't grow, but we use a trick: we create a memfd and use ftruncate
  68. * to grow it as necessary. We mmap the new size and then create a gem bo for
  69. * it using the new gem userptr ioctl. Without heavy-handed locking around
  70. * our allocation fast-path, there isn't really a way to munmap the old mmap,
  71. * so we just keep it around until garbage collection time. While the block
  72. * allocator is lockless for normal operations, we block other threads trying
  73. * to allocate while we're growing the map. It sholdn't happen often, and
  74. * growing is fast anyway.
  75. *
  76. * At the next level we can use various sub-allocators. The state pool is a
  77. * pool of smaller, fixed size objects, which operates much like the block
  78. * pool. It uses a free list for freeing objects, but when it runs out of
  79. * space it just allocates a new block from the block pool. This allocator is
  80. * intended for longer lived state objects such as SURFACE_STATE and most
  81. * other persistent state objects in the API. We may need to track more info
  82. * with these object and a pointer back to the CPU object (eg VkImage). In
  83. * those cases we just allocate a slightly bigger object and put the extra
  84. * state after the GPU state object.
  85. *
  86. * The state stream allocator works similar to how the i965 DRI driver streams
  87. * all its state. Even with Vulkan, we need to emit transient state (whether
  88. * surface state base or dynamic state base), and for that we can just get a
  89. * block and fill it up. These cases are local to a command buffer and the
  90. * sub-allocator need not be thread safe. The streaming allocator gets a new
  91. * block when it runs out of space and chains them together so they can be
  92. * easily freed.
  93. */
  94. /* Allocations are always at least 64 byte aligned, so 1 is an invalid value.
  95. * We use it to indicate the free list is empty. */
  96. #define EMPTY 1
  97. struct anv_mmap_cleanup {
  98. void *map;
  99. size_t size;
  100. uint32_t gem_handle;
  101. };
  102. #define ANV_MMAP_CLEANUP_INIT ((struct anv_mmap_cleanup){0})
  103. #ifndef HAVE_MEMFD_CREATE
  104. static inline int
  105. memfd_create(const char *name, unsigned int flags)
  106. {
  107. return syscall(SYS_memfd_create, name, flags);
  108. }
  109. #endif
  110. static inline uint32_t
  111. ilog2_round_up(uint32_t value)
  112. {
  113. assert(value != 0);
  114. return 32 - __builtin_clz(value - 1);
  115. }
  116. static inline uint32_t
  117. round_to_power_of_two(uint32_t value)
  118. {
  119. return 1 << ilog2_round_up(value);
  120. }
  121. static bool
  122. anv_free_list_pop(union anv_free_list *list, void **map, int32_t *offset)
  123. {
  124. union anv_free_list current, new, old;
  125. current.u64 = list->u64;
  126. while (current.offset != EMPTY) {
  127. /* We have to add a memory barrier here so that the list head (and
  128. * offset) gets read before we read the map pointer. This way we
  129. * know that the map pointer is valid for the given offset at the
  130. * point where we read it.
  131. */
  132. __sync_synchronize();
  133. int32_t *next_ptr = *map + current.offset;
  134. new.offset = VG_NOACCESS_READ(next_ptr);
  135. new.count = current.count + 1;
  136. old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
  137. if (old.u64 == current.u64) {
  138. *offset = current.offset;
  139. return true;
  140. }
  141. current = old;
  142. }
  143. return false;
  144. }
  145. static void
  146. anv_free_list_push(union anv_free_list *list, void *map, int32_t offset,
  147. uint32_t size, uint32_t count)
  148. {
  149. union anv_free_list current, old, new;
  150. int32_t *next_ptr = map + offset;
  151. /* If we're returning more than one chunk, we need to build a chain to add
  152. * to the list. Fortunately, we can do this without any atomics since we
  153. * own everything in the chain right now. `offset` is left pointing to the
  154. * head of our chain list while `next_ptr` points to the tail.
  155. */
  156. for (uint32_t i = 1; i < count; i++) {
  157. VG_NOACCESS_WRITE(next_ptr, offset + i * size);
  158. next_ptr = map + offset + i * size;
  159. }
  160. old = *list;
  161. do {
  162. current = old;
  163. VG_NOACCESS_WRITE(next_ptr, current.offset);
  164. new.offset = offset;
  165. new.count = current.count + 1;
  166. old.u64 = __sync_val_compare_and_swap(&list->u64, current.u64, new.u64);
  167. } while (old.u64 != current.u64);
  168. }
  169. /* All pointers in the ptr_free_list are assumed to be page-aligned. This
  170. * means that the bottom 12 bits should all be zero.
  171. */
  172. #define PFL_COUNT(x) ((uintptr_t)(x) & 0xfff)
  173. #define PFL_PTR(x) ((void *)((uintptr_t)(x) & ~(uintptr_t)0xfff))
  174. #define PFL_PACK(ptr, count) ({ \
  175. (void *)(((uintptr_t)(ptr) & ~(uintptr_t)0xfff) | ((count) & 0xfff)); \
  176. })
  177. static bool
  178. anv_ptr_free_list_pop(void **list, void **elem)
  179. {
  180. void *current = *list;
  181. while (PFL_PTR(current) != NULL) {
  182. void **next_ptr = PFL_PTR(current);
  183. void *new_ptr = VG_NOACCESS_READ(next_ptr);
  184. unsigned new_count = PFL_COUNT(current) + 1;
  185. void *new = PFL_PACK(new_ptr, new_count);
  186. void *old = __sync_val_compare_and_swap(list, current, new);
  187. if (old == current) {
  188. *elem = PFL_PTR(current);
  189. return true;
  190. }
  191. current = old;
  192. }
  193. return false;
  194. }
  195. static void
  196. anv_ptr_free_list_push(void **list, void *elem)
  197. {
  198. void *old, *current;
  199. void **next_ptr = elem;
  200. /* The pointer-based free list requires that the pointer be
  201. * page-aligned. This is because we use the bottom 12 bits of the
  202. * pointer to store a counter to solve the ABA concurrency problem.
  203. */
  204. assert(((uintptr_t)elem & 0xfff) == 0);
  205. old = *list;
  206. do {
  207. current = old;
  208. VG_NOACCESS_WRITE(next_ptr, PFL_PTR(current));
  209. unsigned new_count = PFL_COUNT(current) + 1;
  210. void *new = PFL_PACK(elem, new_count);
  211. old = __sync_val_compare_and_swap(list, current, new);
  212. } while (old != current);
  213. }
  214. static VkResult
  215. anv_block_pool_expand_range(struct anv_block_pool *pool,
  216. uint32_t center_bo_offset, uint32_t size);
  217. VkResult
  218. anv_block_pool_init(struct anv_block_pool *pool,
  219. struct anv_device *device,
  220. uint64_t start_address,
  221. uint32_t initial_size,
  222. uint64_t bo_flags)
  223. {
  224. VkResult result;
  225. pool->device = device;
  226. pool->bo_flags = bo_flags;
  227. pool->start_address = gen_canonical_address(start_address);
  228. anv_bo_init(&pool->bo, 0, 0);
  229. pool->fd = memfd_create("block pool", MFD_CLOEXEC);
  230. if (pool->fd == -1)
  231. return vk_error(VK_ERROR_INITIALIZATION_FAILED);
  232. /* Just make it 2GB up-front. The Linux kernel won't actually back it
  233. * with pages until we either map and fault on one of them or we use
  234. * userptr and send a chunk of it off to the GPU.
  235. */
  236. if (ftruncate(pool->fd, BLOCK_POOL_MEMFD_SIZE) == -1) {
  237. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  238. goto fail_fd;
  239. }
  240. if (!u_vector_init(&pool->mmap_cleanups,
  241. round_to_power_of_two(sizeof(struct anv_mmap_cleanup)),
  242. 128)) {
  243. result = vk_error(VK_ERROR_INITIALIZATION_FAILED);
  244. goto fail_fd;
  245. }
  246. pool->state.next = 0;
  247. pool->state.end = 0;
  248. pool->back_state.next = 0;
  249. pool->back_state.end = 0;
  250. result = anv_block_pool_expand_range(pool, 0, initial_size);
  251. if (result != VK_SUCCESS)
  252. goto fail_mmap_cleanups;
  253. return VK_SUCCESS;
  254. fail_mmap_cleanups:
  255. u_vector_finish(&pool->mmap_cleanups);
  256. fail_fd:
  257. close(pool->fd);
  258. return result;
  259. }
  260. void
  261. anv_block_pool_finish(struct anv_block_pool *pool)
  262. {
  263. struct anv_mmap_cleanup *cleanup;
  264. u_vector_foreach(cleanup, &pool->mmap_cleanups) {
  265. if (cleanup->map)
  266. munmap(cleanup->map, cleanup->size);
  267. if (cleanup->gem_handle)
  268. anv_gem_close(pool->device, cleanup->gem_handle);
  269. }
  270. u_vector_finish(&pool->mmap_cleanups);
  271. close(pool->fd);
  272. }
  273. #define PAGE_SIZE 4096
  274. static VkResult
  275. anv_block_pool_expand_range(struct anv_block_pool *pool,
  276. uint32_t center_bo_offset, uint32_t size)
  277. {
  278. void *map;
  279. uint32_t gem_handle;
  280. struct anv_mmap_cleanup *cleanup;
  281. /* Assert that we only ever grow the pool */
  282. assert(center_bo_offset >= pool->back_state.end);
  283. assert(size - center_bo_offset >= pool->state.end);
  284. /* Assert that we don't go outside the bounds of the memfd */
  285. assert(center_bo_offset <= BLOCK_POOL_MEMFD_CENTER);
  286. assert(size - center_bo_offset <=
  287. BLOCK_POOL_MEMFD_SIZE - BLOCK_POOL_MEMFD_CENTER);
  288. cleanup = u_vector_add(&pool->mmap_cleanups);
  289. if (!cleanup)
  290. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  291. *cleanup = ANV_MMAP_CLEANUP_INIT;
  292. /* Just leak the old map until we destroy the pool. We can't munmap it
  293. * without races or imposing locking on the block allocate fast path. On
  294. * the whole the leaked maps adds up to less than the size of the
  295. * current map. MAP_POPULATE seems like the right thing to do, but we
  296. * should try to get some numbers.
  297. */
  298. map = mmap(NULL, size, PROT_READ | PROT_WRITE,
  299. MAP_SHARED | MAP_POPULATE, pool->fd,
  300. BLOCK_POOL_MEMFD_CENTER - center_bo_offset);
  301. if (map == MAP_FAILED)
  302. return vk_errorf(pool->device->instance, pool->device,
  303. VK_ERROR_MEMORY_MAP_FAILED, "mmap failed: %m");
  304. gem_handle = anv_gem_userptr(pool->device, map, size);
  305. if (gem_handle == 0) {
  306. munmap(map, size);
  307. return vk_errorf(pool->device->instance, pool->device,
  308. VK_ERROR_TOO_MANY_OBJECTS, "userptr failed: %m");
  309. }
  310. cleanup->map = map;
  311. cleanup->size = size;
  312. cleanup->gem_handle = gem_handle;
  313. #if 0
  314. /* Regular objects are created I915_CACHING_CACHED on LLC platforms and
  315. * I915_CACHING_NONE on non-LLC platforms. However, userptr objects are
  316. * always created as I915_CACHING_CACHED, which on non-LLC means
  317. * snooped. That can be useful but comes with a bit of overheard. Since
  318. * we're eplicitly clflushing and don't want the overhead we need to turn
  319. * it off. */
  320. if (!pool->device->info.has_llc) {
  321. anv_gem_set_caching(pool->device, gem_handle, I915_CACHING_NONE);
  322. anv_gem_set_domain(pool->device, gem_handle,
  323. I915_GEM_DOMAIN_GTT, I915_GEM_DOMAIN_GTT);
  324. }
  325. #endif
  326. /* Now that we successfull allocated everything, we can write the new
  327. * values back into pool. */
  328. pool->map = map + center_bo_offset;
  329. pool->center_bo_offset = center_bo_offset;
  330. /* For block pool BOs we have to be a bit careful about where we place them
  331. * in the GTT. There are two documented workarounds for state base address
  332. * placement : Wa32bitGeneralStateOffset and Wa32bitInstructionBaseOffset
  333. * which state that those two base addresses do not support 48-bit
  334. * addresses and need to be placed in the bottom 32-bit range.
  335. * Unfortunately, this is not quite accurate.
  336. *
  337. * The real problem is that we always set the size of our state pools in
  338. * STATE_BASE_ADDRESS to 0xfffff (the maximum) even though the BO is most
  339. * likely significantly smaller. We do this because we do not no at the
  340. * time we emit STATE_BASE_ADDRESS whether or not we will need to expand
  341. * the pool during command buffer building so we don't actually have a
  342. * valid final size. If the address + size, as seen by STATE_BASE_ADDRESS
  343. * overflows 48 bits, the GPU appears to treat all accesses to the buffer
  344. * as being out of bounds and returns zero. For dynamic state, this
  345. * usually just leads to rendering corruptions, but shaders that are all
  346. * zero hang the GPU immediately.
  347. *
  348. * The easiest solution to do is exactly what the bogus workarounds say to
  349. * do: restrict these buffers to 32-bit addresses. We could also pin the
  350. * BO to some particular location of our choosing, but that's significantly
  351. * more work than just not setting a flag. So, we explicitly DO NOT set
  352. * the EXEC_OBJECT_SUPPORTS_48B_ADDRESS flag and the kernel does all of the
  353. * hard work for us.
  354. */
  355. anv_bo_init(&pool->bo, gem_handle, size);
  356. if (pool->bo_flags & EXEC_OBJECT_PINNED) {
  357. pool->bo.offset = pool->start_address + BLOCK_POOL_MEMFD_CENTER -
  358. center_bo_offset;
  359. }
  360. pool->bo.flags = pool->bo_flags;
  361. pool->bo.map = map;
  362. return VK_SUCCESS;
  363. }
  364. /** Grows and re-centers the block pool.
  365. *
  366. * We grow the block pool in one or both directions in such a way that the
  367. * following conditions are met:
  368. *
  369. * 1) The size of the entire pool is always a power of two.
  370. *
  371. * 2) The pool only grows on both ends. Neither end can get
  372. * shortened.
  373. *
  374. * 3) At the end of the allocation, we have about twice as much space
  375. * allocated for each end as we have used. This way the pool doesn't
  376. * grow too far in one direction or the other.
  377. *
  378. * 4) If the _alloc_back() has never been called, then the back portion of
  379. * the pool retains a size of zero. (This makes it easier for users of
  380. * the block pool that only want a one-sided pool.)
  381. *
  382. * 5) We have enough space allocated for at least one more block in
  383. * whichever side `state` points to.
  384. *
  385. * 6) The center of the pool is always aligned to both the block_size of
  386. * the pool and a 4K CPU page.
  387. */
  388. static uint32_t
  389. anv_block_pool_grow(struct anv_block_pool *pool, struct anv_block_state *state)
  390. {
  391. VkResult result = VK_SUCCESS;
  392. pthread_mutex_lock(&pool->device->mutex);
  393. assert(state == &pool->state || state == &pool->back_state);
  394. /* Gather a little usage information on the pool. Since we may have
  395. * threadsd waiting in queue to get some storage while we resize, it's
  396. * actually possible that total_used will be larger than old_size. In
  397. * particular, block_pool_alloc() increments state->next prior to
  398. * calling block_pool_grow, so this ensures that we get enough space for
  399. * which ever side tries to grow the pool.
  400. *
  401. * We align to a page size because it makes it easier to do our
  402. * calculations later in such a way that we state page-aigned.
  403. */
  404. uint32_t back_used = align_u32(pool->back_state.next, PAGE_SIZE);
  405. uint32_t front_used = align_u32(pool->state.next, PAGE_SIZE);
  406. uint32_t total_used = front_used + back_used;
  407. assert(state == &pool->state || back_used > 0);
  408. uint32_t old_size = pool->bo.size;
  409. /* The block pool is always initialized to a nonzero size and this function
  410. * is always called after initialization.
  411. */
  412. assert(old_size > 0);
  413. /* The back_used and front_used may actually be smaller than the actual
  414. * requirement because they are based on the next pointers which are
  415. * updated prior to calling this function.
  416. */
  417. uint32_t back_required = MAX2(back_used, pool->center_bo_offset);
  418. uint32_t front_required = MAX2(front_used, old_size - pool->center_bo_offset);
  419. if (back_used * 2 <= back_required && front_used * 2 <= front_required) {
  420. /* If we're in this case then this isn't the firsta allocation and we
  421. * already have enough space on both sides to hold double what we
  422. * have allocated. There's nothing for us to do.
  423. */
  424. goto done;
  425. }
  426. uint32_t size = old_size * 2;
  427. while (size < back_required + front_required)
  428. size *= 2;
  429. assert(size > pool->bo.size);
  430. /* We compute a new center_bo_offset such that, when we double the size
  431. * of the pool, we maintain the ratio of how much is used by each side.
  432. * This way things should remain more-or-less balanced.
  433. */
  434. uint32_t center_bo_offset;
  435. if (back_used == 0) {
  436. /* If we're in this case then we have never called alloc_back(). In
  437. * this case, we want keep the offset at 0 to make things as simple
  438. * as possible for users that don't care about back allocations.
  439. */
  440. center_bo_offset = 0;
  441. } else {
  442. /* Try to "center" the allocation based on how much is currently in
  443. * use on each side of the center line.
  444. */
  445. center_bo_offset = ((uint64_t)size * back_used) / total_used;
  446. /* Align down to a multiple of the page size */
  447. center_bo_offset &= ~(PAGE_SIZE - 1);
  448. assert(center_bo_offset >= back_used);
  449. /* Make sure we don't shrink the back end of the pool */
  450. if (center_bo_offset < back_required)
  451. center_bo_offset = back_required;
  452. /* Make sure that we don't shrink the front end of the pool */
  453. if (size - center_bo_offset < front_required)
  454. center_bo_offset = size - front_required;
  455. }
  456. assert(center_bo_offset % PAGE_SIZE == 0);
  457. result = anv_block_pool_expand_range(pool, center_bo_offset, size);
  458. pool->bo.flags = pool->bo_flags;
  459. done:
  460. pthread_mutex_unlock(&pool->device->mutex);
  461. if (result == VK_SUCCESS) {
  462. /* Return the appropriate new size. This function never actually
  463. * updates state->next. Instead, we let the caller do that because it
  464. * needs to do so in order to maintain its concurrency model.
  465. */
  466. if (state == &pool->state) {
  467. return pool->bo.size - pool->center_bo_offset;
  468. } else {
  469. assert(pool->center_bo_offset > 0);
  470. return pool->center_bo_offset;
  471. }
  472. } else {
  473. return 0;
  474. }
  475. }
  476. static uint32_t
  477. anv_block_pool_alloc_new(struct anv_block_pool *pool,
  478. struct anv_block_state *pool_state,
  479. uint32_t block_size)
  480. {
  481. struct anv_block_state state, old, new;
  482. while (1) {
  483. state.u64 = __sync_fetch_and_add(&pool_state->u64, block_size);
  484. if (state.next + block_size <= state.end) {
  485. assert(pool->map);
  486. return state.next;
  487. } else if (state.next <= state.end) {
  488. /* We allocated the first block outside the pool so we have to grow
  489. * the pool. pool_state->next acts a mutex: threads who try to
  490. * allocate now will get block indexes above the current limit and
  491. * hit futex_wait below.
  492. */
  493. new.next = state.next + block_size;
  494. do {
  495. new.end = anv_block_pool_grow(pool, pool_state);
  496. } while (new.end < new.next);
  497. old.u64 = __sync_lock_test_and_set(&pool_state->u64, new.u64);
  498. if (old.next != state.next)
  499. futex_wake(&pool_state->end, INT_MAX);
  500. return state.next;
  501. } else {
  502. futex_wait(&pool_state->end, state.end, NULL);
  503. continue;
  504. }
  505. }
  506. }
  507. int32_t
  508. anv_block_pool_alloc(struct anv_block_pool *pool,
  509. uint32_t block_size)
  510. {
  511. return anv_block_pool_alloc_new(pool, &pool->state, block_size);
  512. }
  513. /* Allocates a block out of the back of the block pool.
  514. *
  515. * This will allocated a block earlier than the "start" of the block pool.
  516. * The offsets returned from this function will be negative but will still
  517. * be correct relative to the block pool's map pointer.
  518. *
  519. * If you ever use anv_block_pool_alloc_back, then you will have to do
  520. * gymnastics with the block pool's BO when doing relocations.
  521. */
  522. int32_t
  523. anv_block_pool_alloc_back(struct anv_block_pool *pool,
  524. uint32_t block_size)
  525. {
  526. int32_t offset = anv_block_pool_alloc_new(pool, &pool->back_state,
  527. block_size);
  528. /* The offset we get out of anv_block_pool_alloc_new() is actually the
  529. * number of bytes downwards from the middle to the end of the block.
  530. * We need to turn it into a (negative) offset from the middle to the
  531. * start of the block.
  532. */
  533. assert(offset >= 0);
  534. return -(offset + block_size);
  535. }
  536. VkResult
  537. anv_state_pool_init(struct anv_state_pool *pool,
  538. struct anv_device *device,
  539. uint64_t start_address,
  540. uint32_t block_size,
  541. uint64_t bo_flags)
  542. {
  543. VkResult result = anv_block_pool_init(&pool->block_pool, device,
  544. start_address,
  545. block_size * 16,
  546. bo_flags);
  547. if (result != VK_SUCCESS)
  548. return result;
  549. assert(util_is_power_of_two_or_zero(block_size));
  550. pool->block_size = block_size;
  551. pool->back_alloc_free_list = ANV_FREE_LIST_EMPTY;
  552. for (unsigned i = 0; i < ANV_STATE_BUCKETS; i++) {
  553. pool->buckets[i].free_list = ANV_FREE_LIST_EMPTY;
  554. pool->buckets[i].block.next = 0;
  555. pool->buckets[i].block.end = 0;
  556. }
  557. VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
  558. return VK_SUCCESS;
  559. }
  560. void
  561. anv_state_pool_finish(struct anv_state_pool *pool)
  562. {
  563. VG(VALGRIND_DESTROY_MEMPOOL(pool));
  564. anv_block_pool_finish(&pool->block_pool);
  565. }
  566. static uint32_t
  567. anv_fixed_size_state_pool_alloc_new(struct anv_fixed_size_state_pool *pool,
  568. struct anv_block_pool *block_pool,
  569. uint32_t state_size,
  570. uint32_t block_size)
  571. {
  572. struct anv_block_state block, old, new;
  573. uint32_t offset;
  574. /* If our state is large, we don't need any sub-allocation from a block.
  575. * Instead, we just grab whole (potentially large) blocks.
  576. */
  577. if (state_size >= block_size)
  578. return anv_block_pool_alloc(block_pool, state_size);
  579. restart:
  580. block.u64 = __sync_fetch_and_add(&pool->block.u64, state_size);
  581. if (block.next < block.end) {
  582. return block.next;
  583. } else if (block.next == block.end) {
  584. offset = anv_block_pool_alloc(block_pool, block_size);
  585. new.next = offset + state_size;
  586. new.end = offset + block_size;
  587. old.u64 = __sync_lock_test_and_set(&pool->block.u64, new.u64);
  588. if (old.next != block.next)
  589. futex_wake(&pool->block.end, INT_MAX);
  590. return offset;
  591. } else {
  592. futex_wait(&pool->block.end, block.end, NULL);
  593. goto restart;
  594. }
  595. }
  596. static uint32_t
  597. anv_state_pool_get_bucket(uint32_t size)
  598. {
  599. unsigned size_log2 = ilog2_round_up(size);
  600. assert(size_log2 <= ANV_MAX_STATE_SIZE_LOG2);
  601. if (size_log2 < ANV_MIN_STATE_SIZE_LOG2)
  602. size_log2 = ANV_MIN_STATE_SIZE_LOG2;
  603. return size_log2 - ANV_MIN_STATE_SIZE_LOG2;
  604. }
  605. static uint32_t
  606. anv_state_pool_get_bucket_size(uint32_t bucket)
  607. {
  608. uint32_t size_log2 = bucket + ANV_MIN_STATE_SIZE_LOG2;
  609. return 1 << size_log2;
  610. }
  611. static struct anv_state
  612. anv_state_pool_alloc_no_vg(struct anv_state_pool *pool,
  613. uint32_t size, uint32_t align)
  614. {
  615. uint32_t bucket = anv_state_pool_get_bucket(MAX2(size, align));
  616. struct anv_state state;
  617. state.alloc_size = anv_state_pool_get_bucket_size(bucket);
  618. /* Try free list first. */
  619. if (anv_free_list_pop(&pool->buckets[bucket].free_list,
  620. &pool->block_pool.map, &state.offset)) {
  621. assert(state.offset >= 0);
  622. goto done;
  623. }
  624. /* Try to grab a chunk from some larger bucket and split it up */
  625. for (unsigned b = bucket + 1; b < ANV_STATE_BUCKETS; b++) {
  626. int32_t chunk_offset;
  627. if (anv_free_list_pop(&pool->buckets[b].free_list,
  628. &pool->block_pool.map, &chunk_offset)) {
  629. unsigned chunk_size = anv_state_pool_get_bucket_size(b);
  630. /* We've found a chunk that's larger than the requested state size.
  631. * There are a couple of options as to what we do with it:
  632. *
  633. * 1) We could fully split the chunk into state.alloc_size sized
  634. * pieces. However, this would mean that allocating a 16B
  635. * state could potentially split a 2MB chunk into 512K smaller
  636. * chunks. This would lead to unnecessary fragmentation.
  637. *
  638. * 2) The classic "buddy allocator" method would have us split the
  639. * chunk in half and return one half. Then we would split the
  640. * remaining half in half and return one half, and repeat as
  641. * needed until we get down to the size we want. However, if
  642. * you are allocating a bunch of the same size state (which is
  643. * the common case), this means that every other allocation has
  644. * to go up a level and every fourth goes up two levels, etc.
  645. * This is not nearly as efficient as it could be if we did a
  646. * little more work up-front.
  647. *
  648. * 3) Split the difference between (1) and (2) by doing a
  649. * two-level split. If it's bigger than some fixed block_size,
  650. * we split it into block_size sized chunks and return all but
  651. * one of them. Then we split what remains into
  652. * state.alloc_size sized chunks and return all but one.
  653. *
  654. * We choose option (3).
  655. */
  656. if (chunk_size > pool->block_size &&
  657. state.alloc_size < pool->block_size) {
  658. assert(chunk_size % pool->block_size == 0);
  659. /* We don't want to split giant chunks into tiny chunks. Instead,
  660. * break anything bigger than a block into block-sized chunks and
  661. * then break it down into bucket-sized chunks from there. Return
  662. * all but the first block of the chunk to the block bucket.
  663. */
  664. const uint32_t block_bucket =
  665. anv_state_pool_get_bucket(pool->block_size);
  666. anv_free_list_push(&pool->buckets[block_bucket].free_list,
  667. pool->block_pool.map,
  668. chunk_offset + pool->block_size,
  669. pool->block_size,
  670. (chunk_size / pool->block_size) - 1);
  671. chunk_size = pool->block_size;
  672. }
  673. assert(chunk_size % state.alloc_size == 0);
  674. anv_free_list_push(&pool->buckets[bucket].free_list,
  675. pool->block_pool.map,
  676. chunk_offset + state.alloc_size,
  677. state.alloc_size,
  678. (chunk_size / state.alloc_size) - 1);
  679. state.offset = chunk_offset;
  680. goto done;
  681. }
  682. }
  683. state.offset = anv_fixed_size_state_pool_alloc_new(&pool->buckets[bucket],
  684. &pool->block_pool,
  685. state.alloc_size,
  686. pool->block_size);
  687. done:
  688. state.map = pool->block_pool.map + state.offset;
  689. return state;
  690. }
  691. struct anv_state
  692. anv_state_pool_alloc(struct anv_state_pool *pool, uint32_t size, uint32_t align)
  693. {
  694. if (size == 0)
  695. return ANV_STATE_NULL;
  696. struct anv_state state = anv_state_pool_alloc_no_vg(pool, size, align);
  697. VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, size));
  698. return state;
  699. }
  700. struct anv_state
  701. anv_state_pool_alloc_back(struct anv_state_pool *pool)
  702. {
  703. struct anv_state state;
  704. state.alloc_size = pool->block_size;
  705. if (anv_free_list_pop(&pool->back_alloc_free_list,
  706. &pool->block_pool.map, &state.offset)) {
  707. assert(state.offset < 0);
  708. goto done;
  709. }
  710. state.offset = anv_block_pool_alloc_back(&pool->block_pool,
  711. pool->block_size);
  712. done:
  713. state.map = pool->block_pool.map + state.offset;
  714. VG(VALGRIND_MEMPOOL_ALLOC(pool, state.map, state.alloc_size));
  715. return state;
  716. }
  717. static void
  718. anv_state_pool_free_no_vg(struct anv_state_pool *pool, struct anv_state state)
  719. {
  720. assert(util_is_power_of_two_or_zero(state.alloc_size));
  721. unsigned bucket = anv_state_pool_get_bucket(state.alloc_size);
  722. if (state.offset < 0) {
  723. assert(state.alloc_size == pool->block_size);
  724. anv_free_list_push(&pool->back_alloc_free_list,
  725. pool->block_pool.map, state.offset,
  726. state.alloc_size, 1);
  727. } else {
  728. anv_free_list_push(&pool->buckets[bucket].free_list,
  729. pool->block_pool.map, state.offset,
  730. state.alloc_size, 1);
  731. }
  732. }
  733. void
  734. anv_state_pool_free(struct anv_state_pool *pool, struct anv_state state)
  735. {
  736. if (state.alloc_size == 0)
  737. return;
  738. VG(VALGRIND_MEMPOOL_FREE(pool, state.map));
  739. anv_state_pool_free_no_vg(pool, state);
  740. }
  741. struct anv_state_stream_block {
  742. struct anv_state block;
  743. /* The next block */
  744. struct anv_state_stream_block *next;
  745. #ifdef HAVE_VALGRIND
  746. /* A pointer to the first user-allocated thing in this block. This is
  747. * what valgrind sees as the start of the block.
  748. */
  749. void *_vg_ptr;
  750. #endif
  751. };
  752. /* The state stream allocator is a one-shot, single threaded allocator for
  753. * variable sized blocks. We use it for allocating dynamic state.
  754. */
  755. void
  756. anv_state_stream_init(struct anv_state_stream *stream,
  757. struct anv_state_pool *state_pool,
  758. uint32_t block_size)
  759. {
  760. stream->state_pool = state_pool;
  761. stream->block_size = block_size;
  762. stream->block = ANV_STATE_NULL;
  763. stream->block_list = NULL;
  764. /* Ensure that next + whatever > block_size. This way the first call to
  765. * state_stream_alloc fetches a new block.
  766. */
  767. stream->next = block_size;
  768. VG(VALGRIND_CREATE_MEMPOOL(stream, 0, false));
  769. }
  770. void
  771. anv_state_stream_finish(struct anv_state_stream *stream)
  772. {
  773. struct anv_state_stream_block *next = stream->block_list;
  774. while (next != NULL) {
  775. struct anv_state_stream_block sb = VG_NOACCESS_READ(next);
  776. VG(VALGRIND_MEMPOOL_FREE(stream, sb._vg_ptr));
  777. VG(VALGRIND_MAKE_MEM_UNDEFINED(next, stream->block_size));
  778. anv_state_pool_free_no_vg(stream->state_pool, sb.block);
  779. next = sb.next;
  780. }
  781. VG(VALGRIND_DESTROY_MEMPOOL(stream));
  782. }
  783. struct anv_state
  784. anv_state_stream_alloc(struct anv_state_stream *stream,
  785. uint32_t size, uint32_t alignment)
  786. {
  787. if (size == 0)
  788. return ANV_STATE_NULL;
  789. assert(alignment <= PAGE_SIZE);
  790. uint32_t offset = align_u32(stream->next, alignment);
  791. if (offset + size > stream->block.alloc_size) {
  792. uint32_t block_size = stream->block_size;
  793. if (block_size < size)
  794. block_size = round_to_power_of_two(size);
  795. stream->block = anv_state_pool_alloc_no_vg(stream->state_pool,
  796. block_size, PAGE_SIZE);
  797. struct anv_state_stream_block *sb = stream->block.map;
  798. VG_NOACCESS_WRITE(&sb->block, stream->block);
  799. VG_NOACCESS_WRITE(&sb->next, stream->block_list);
  800. stream->block_list = sb;
  801. VG(VG_NOACCESS_WRITE(&sb->_vg_ptr, NULL));
  802. VG(VALGRIND_MAKE_MEM_NOACCESS(stream->block.map, stream->block_size));
  803. /* Reset back to the start plus space for the header */
  804. stream->next = sizeof(*sb);
  805. offset = align_u32(stream->next, alignment);
  806. assert(offset + size <= stream->block.alloc_size);
  807. }
  808. struct anv_state state = stream->block;
  809. state.offset += offset;
  810. state.alloc_size = size;
  811. state.map += offset;
  812. stream->next = offset + size;
  813. #ifdef HAVE_VALGRIND
  814. struct anv_state_stream_block *sb = stream->block_list;
  815. void *vg_ptr = VG_NOACCESS_READ(&sb->_vg_ptr);
  816. if (vg_ptr == NULL) {
  817. vg_ptr = state.map;
  818. VG_NOACCESS_WRITE(&sb->_vg_ptr, vg_ptr);
  819. VALGRIND_MEMPOOL_ALLOC(stream, vg_ptr, size);
  820. } else {
  821. void *state_end = state.map + state.alloc_size;
  822. /* This only updates the mempool. The newly allocated chunk is still
  823. * marked as NOACCESS. */
  824. VALGRIND_MEMPOOL_CHANGE(stream, vg_ptr, vg_ptr, state_end - vg_ptr);
  825. /* Mark the newly allocated chunk as undefined */
  826. VALGRIND_MAKE_MEM_UNDEFINED(state.map, state.alloc_size);
  827. }
  828. #endif
  829. return state;
  830. }
  831. struct bo_pool_bo_link {
  832. struct bo_pool_bo_link *next;
  833. struct anv_bo bo;
  834. };
  835. void
  836. anv_bo_pool_init(struct anv_bo_pool *pool, struct anv_device *device,
  837. uint64_t bo_flags)
  838. {
  839. pool->device = device;
  840. pool->bo_flags = bo_flags;
  841. memset(pool->free_list, 0, sizeof(pool->free_list));
  842. VG(VALGRIND_CREATE_MEMPOOL(pool, 0, false));
  843. }
  844. void
  845. anv_bo_pool_finish(struct anv_bo_pool *pool)
  846. {
  847. for (unsigned i = 0; i < ARRAY_SIZE(pool->free_list); i++) {
  848. struct bo_pool_bo_link *link = PFL_PTR(pool->free_list[i]);
  849. while (link != NULL) {
  850. struct bo_pool_bo_link link_copy = VG_NOACCESS_READ(link);
  851. anv_gem_munmap(link_copy.bo.map, link_copy.bo.size);
  852. anv_vma_free(pool->device, &link_copy.bo);
  853. anv_gem_close(pool->device, link_copy.bo.gem_handle);
  854. link = link_copy.next;
  855. }
  856. }
  857. VG(VALGRIND_DESTROY_MEMPOOL(pool));
  858. }
  859. VkResult
  860. anv_bo_pool_alloc(struct anv_bo_pool *pool, struct anv_bo *bo, uint32_t size)
  861. {
  862. VkResult result;
  863. const unsigned size_log2 = size < 4096 ? 12 : ilog2_round_up(size);
  864. const unsigned pow2_size = 1 << size_log2;
  865. const unsigned bucket = size_log2 - 12;
  866. assert(bucket < ARRAY_SIZE(pool->free_list));
  867. void *next_free_void;
  868. if (anv_ptr_free_list_pop(&pool->free_list[bucket], &next_free_void)) {
  869. struct bo_pool_bo_link *next_free = next_free_void;
  870. *bo = VG_NOACCESS_READ(&next_free->bo);
  871. assert(bo->gem_handle);
  872. assert(bo->map == next_free);
  873. assert(size <= bo->size);
  874. VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
  875. return VK_SUCCESS;
  876. }
  877. struct anv_bo new_bo;
  878. result = anv_bo_init_new(&new_bo, pool->device, pow2_size);
  879. if (result != VK_SUCCESS)
  880. return result;
  881. new_bo.flags = pool->bo_flags;
  882. if (!anv_vma_alloc(pool->device, &new_bo))
  883. return vk_error(VK_ERROR_OUT_OF_DEVICE_MEMORY);
  884. assert(new_bo.size == pow2_size);
  885. new_bo.map = anv_gem_mmap(pool->device, new_bo.gem_handle, 0, pow2_size, 0);
  886. if (new_bo.map == MAP_FAILED) {
  887. anv_gem_close(pool->device, new_bo.gem_handle);
  888. anv_vma_free(pool->device, &new_bo);
  889. return vk_error(VK_ERROR_MEMORY_MAP_FAILED);
  890. }
  891. *bo = new_bo;
  892. VG(VALGRIND_MEMPOOL_ALLOC(pool, bo->map, size));
  893. return VK_SUCCESS;
  894. }
  895. void
  896. anv_bo_pool_free(struct anv_bo_pool *pool, const struct anv_bo *bo_in)
  897. {
  898. /* Make a copy in case the anv_bo happens to be storred in the BO */
  899. struct anv_bo bo = *bo_in;
  900. VG(VALGRIND_MEMPOOL_FREE(pool, bo.map));
  901. struct bo_pool_bo_link *link = bo.map;
  902. VG_NOACCESS_WRITE(&link->bo, bo);
  903. assert(util_is_power_of_two_or_zero(bo.size));
  904. const unsigned size_log2 = ilog2_round_up(bo.size);
  905. const unsigned bucket = size_log2 - 12;
  906. assert(bucket < ARRAY_SIZE(pool->free_list));
  907. anv_ptr_free_list_push(&pool->free_list[bucket], link);
  908. }
  909. // Scratch pool
  910. void
  911. anv_scratch_pool_init(struct anv_device *device, struct anv_scratch_pool *pool)
  912. {
  913. memset(pool, 0, sizeof(*pool));
  914. }
  915. void
  916. anv_scratch_pool_finish(struct anv_device *device, struct anv_scratch_pool *pool)
  917. {
  918. for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
  919. for (unsigned i = 0; i < 16; i++) {
  920. struct anv_scratch_bo *bo = &pool->bos[i][s];
  921. if (bo->exists > 0) {
  922. anv_vma_free(device, &bo->bo);
  923. anv_gem_close(device, bo->bo.gem_handle);
  924. }
  925. }
  926. }
  927. }
  928. struct anv_bo *
  929. anv_scratch_pool_alloc(struct anv_device *device, struct anv_scratch_pool *pool,
  930. gl_shader_stage stage, unsigned per_thread_scratch)
  931. {
  932. if (per_thread_scratch == 0)
  933. return NULL;
  934. unsigned scratch_size_log2 = ffs(per_thread_scratch / 2048);
  935. assert(scratch_size_log2 < 16);
  936. struct anv_scratch_bo *bo = &pool->bos[scratch_size_log2][stage];
  937. /* We can use "exists" to shortcut and ignore the critical section */
  938. if (bo->exists)
  939. return &bo->bo;
  940. pthread_mutex_lock(&device->mutex);
  941. __sync_synchronize();
  942. if (bo->exists) {
  943. pthread_mutex_unlock(&device->mutex);
  944. return &bo->bo;
  945. }
  946. const struct anv_physical_device *physical_device =
  947. &device->instance->physicalDevice;
  948. const struct gen_device_info *devinfo = &physical_device->info;
  949. const unsigned subslices = MAX2(physical_device->subslice_total, 1);
  950. unsigned scratch_ids_per_subslice;
  951. if (devinfo->is_haswell) {
  952. /* WaCSScratchSize:hsw
  953. *
  954. * Haswell's scratch space address calculation appears to be sparse
  955. * rather than tightly packed. The Thread ID has bits indicating
  956. * which subslice, EU within a subslice, and thread within an EU it
  957. * is. There's a maximum of two slices and two subslices, so these
  958. * can be stored with a single bit. Even though there are only 10 EUs
  959. * per subslice, this is stored in 4 bits, so there's an effective
  960. * maximum value of 16 EUs. Similarly, although there are only 7
  961. * threads per EU, this is stored in a 3 bit number, giving an
  962. * effective maximum value of 8 threads per EU.
  963. *
  964. * This means that we need to use 16 * 8 instead of 10 * 7 for the
  965. * number of threads per subslice.
  966. */
  967. scratch_ids_per_subslice = 16 * 8;
  968. } else if (devinfo->is_cherryview) {
  969. /* Cherryview devices have either 6 or 8 EUs per subslice, and each EU
  970. * has 7 threads. The 6 EU devices appear to calculate thread IDs as if
  971. * it had 8 EUs.
  972. */
  973. scratch_ids_per_subslice = 8 * 7;
  974. } else {
  975. scratch_ids_per_subslice = devinfo->max_cs_threads;
  976. }
  977. uint32_t max_threads[] = {
  978. [MESA_SHADER_VERTEX] = devinfo->max_vs_threads,
  979. [MESA_SHADER_TESS_CTRL] = devinfo->max_tcs_threads,
  980. [MESA_SHADER_TESS_EVAL] = devinfo->max_tes_threads,
  981. [MESA_SHADER_GEOMETRY] = devinfo->max_gs_threads,
  982. [MESA_SHADER_FRAGMENT] = devinfo->max_wm_threads,
  983. [MESA_SHADER_COMPUTE] = scratch_ids_per_subslice * subslices,
  984. };
  985. uint32_t size = per_thread_scratch * max_threads[stage];
  986. anv_bo_init_new(&bo->bo, device, size);
  987. /* Even though the Scratch base pointers in 3DSTATE_*S are 64 bits, they
  988. * are still relative to the general state base address. When we emit
  989. * STATE_BASE_ADDRESS, we set general state base address to 0 and the size
  990. * to the maximum (1 page under 4GB). This allows us to just place the
  991. * scratch buffers anywhere we wish in the bottom 32 bits of address space
  992. * and just set the scratch base pointer in 3DSTATE_*S using a relocation.
  993. * However, in order to do so, we need to ensure that the kernel does not
  994. * place the scratch BO above the 32-bit boundary.
  995. *
  996. * NOTE: Technically, it can't go "anywhere" because the top page is off
  997. * limits. However, when EXEC_OBJECT_SUPPORTS_48B_ADDRESS is set, the
  998. * kernel allocates space using
  999. *
  1000. * end = min_t(u64, end, (1ULL << 32) - I915_GTT_PAGE_SIZE);
  1001. *
  1002. * so nothing will ever touch the top page.
  1003. */
  1004. assert(!(bo->bo.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS));
  1005. if (device->instance->physicalDevice.has_exec_async)
  1006. bo->bo.flags |= EXEC_OBJECT_ASYNC;
  1007. if (device->instance->physicalDevice.use_softpin)
  1008. bo->bo.flags |= EXEC_OBJECT_PINNED;
  1009. anv_vma_alloc(device, &bo->bo);
  1010. /* Set the exists last because it may be read by other threads */
  1011. __sync_synchronize();
  1012. bo->exists = true;
  1013. pthread_mutex_unlock(&device->mutex);
  1014. return &bo->bo;
  1015. }
  1016. struct anv_cached_bo {
  1017. struct anv_bo bo;
  1018. uint32_t refcount;
  1019. };
  1020. VkResult
  1021. anv_bo_cache_init(struct anv_bo_cache *cache)
  1022. {
  1023. cache->bo_map = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
  1024. _mesa_key_pointer_equal);
  1025. if (!cache->bo_map)
  1026. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  1027. if (pthread_mutex_init(&cache->mutex, NULL)) {
  1028. _mesa_hash_table_destroy(cache->bo_map, NULL);
  1029. return vk_errorf(NULL, NULL, VK_ERROR_OUT_OF_HOST_MEMORY,
  1030. "pthread_mutex_init failed: %m");
  1031. }
  1032. return VK_SUCCESS;
  1033. }
  1034. void
  1035. anv_bo_cache_finish(struct anv_bo_cache *cache)
  1036. {
  1037. _mesa_hash_table_destroy(cache->bo_map, NULL);
  1038. pthread_mutex_destroy(&cache->mutex);
  1039. }
  1040. static struct anv_cached_bo *
  1041. anv_bo_cache_lookup_locked(struct anv_bo_cache *cache, uint32_t gem_handle)
  1042. {
  1043. struct hash_entry *entry =
  1044. _mesa_hash_table_search(cache->bo_map,
  1045. (const void *)(uintptr_t)gem_handle);
  1046. if (!entry)
  1047. return NULL;
  1048. struct anv_cached_bo *bo = (struct anv_cached_bo *)entry->data;
  1049. assert(bo->bo.gem_handle == gem_handle);
  1050. return bo;
  1051. }
  1052. UNUSED static struct anv_bo *
  1053. anv_bo_cache_lookup(struct anv_bo_cache *cache, uint32_t gem_handle)
  1054. {
  1055. pthread_mutex_lock(&cache->mutex);
  1056. struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
  1057. pthread_mutex_unlock(&cache->mutex);
  1058. return bo ? &bo->bo : NULL;
  1059. }
  1060. #define ANV_BO_CACHE_SUPPORTED_FLAGS \
  1061. (EXEC_OBJECT_WRITE | \
  1062. EXEC_OBJECT_ASYNC | \
  1063. EXEC_OBJECT_SUPPORTS_48B_ADDRESS | \
  1064. EXEC_OBJECT_PINNED | \
  1065. ANV_BO_EXTERNAL)
  1066. VkResult
  1067. anv_bo_cache_alloc(struct anv_device *device,
  1068. struct anv_bo_cache *cache,
  1069. uint64_t size, uint64_t bo_flags,
  1070. struct anv_bo **bo_out)
  1071. {
  1072. assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
  1073. struct anv_cached_bo *bo =
  1074. vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
  1075. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  1076. if (!bo)
  1077. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  1078. bo->refcount = 1;
  1079. /* The kernel is going to give us whole pages anyway */
  1080. size = align_u64(size, 4096);
  1081. VkResult result = anv_bo_init_new(&bo->bo, device, size);
  1082. if (result != VK_SUCCESS) {
  1083. vk_free(&device->alloc, bo);
  1084. return result;
  1085. }
  1086. bo->bo.flags = bo_flags;
  1087. if (!anv_vma_alloc(device, &bo->bo)) {
  1088. anv_gem_close(device, bo->bo.gem_handle);
  1089. vk_free(&device->alloc, bo);
  1090. return vk_errorf(device->instance, NULL,
  1091. VK_ERROR_OUT_OF_DEVICE_MEMORY,
  1092. "failed to allocate virtual address for BO");
  1093. }
  1094. assert(bo->bo.gem_handle);
  1095. pthread_mutex_lock(&cache->mutex);
  1096. _mesa_hash_table_insert(cache->bo_map,
  1097. (void *)(uintptr_t)bo->bo.gem_handle, bo);
  1098. pthread_mutex_unlock(&cache->mutex);
  1099. *bo_out = &bo->bo;
  1100. return VK_SUCCESS;
  1101. }
  1102. VkResult
  1103. anv_bo_cache_import(struct anv_device *device,
  1104. struct anv_bo_cache *cache,
  1105. int fd, uint64_t bo_flags,
  1106. struct anv_bo **bo_out)
  1107. {
  1108. assert(bo_flags == (bo_flags & ANV_BO_CACHE_SUPPORTED_FLAGS));
  1109. assert(bo_flags & ANV_BO_EXTERNAL);
  1110. pthread_mutex_lock(&cache->mutex);
  1111. uint32_t gem_handle = anv_gem_fd_to_handle(device, fd);
  1112. if (!gem_handle) {
  1113. pthread_mutex_unlock(&cache->mutex);
  1114. return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR);
  1115. }
  1116. struct anv_cached_bo *bo = anv_bo_cache_lookup_locked(cache, gem_handle);
  1117. if (bo) {
  1118. /* We have to be careful how we combine flags so that it makes sense.
  1119. * Really, though, if we get to this case and it actually matters, the
  1120. * client has imported a BO twice in different ways and they get what
  1121. * they have coming.
  1122. */
  1123. uint64_t new_flags = ANV_BO_EXTERNAL;
  1124. new_flags |= (bo->bo.flags | bo_flags) & EXEC_OBJECT_WRITE;
  1125. new_flags |= (bo->bo.flags & bo_flags) & EXEC_OBJECT_ASYNC;
  1126. new_flags |= (bo->bo.flags & bo_flags) & EXEC_OBJECT_SUPPORTS_48B_ADDRESS;
  1127. new_flags |= (bo->bo.flags | bo_flags) & EXEC_OBJECT_PINNED;
  1128. /* It's theoretically possible for a BO to get imported such that it's
  1129. * both pinned and not pinned. The only way this can happen is if it
  1130. * gets imported as both a semaphore and a memory object and that would
  1131. * be an application error. Just fail out in that case.
  1132. */
  1133. if ((bo->bo.flags & EXEC_OBJECT_PINNED) !=
  1134. (bo_flags & EXEC_OBJECT_PINNED)) {
  1135. pthread_mutex_unlock(&cache->mutex);
  1136. return vk_errorf(device->instance, NULL,
  1137. VK_ERROR_INVALID_EXTERNAL_HANDLE,
  1138. "The same BO was imported two different ways");
  1139. }
  1140. /* It's also theoretically possible that someone could export a BO from
  1141. * one heap and import it into another or to import the same BO into two
  1142. * different heaps. If this happens, we could potentially end up both
  1143. * allowing and disallowing 48-bit addresses. There's not much we can
  1144. * do about it if we're pinning so we just throw an error and hope no
  1145. * app is actually that stupid.
  1146. */
  1147. if ((new_flags & EXEC_OBJECT_PINNED) &&
  1148. (bo->bo.flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS) !=
  1149. (bo_flags & EXEC_OBJECT_SUPPORTS_48B_ADDRESS)) {
  1150. return vk_errorf(device->instance, NULL,
  1151. VK_ERROR_INVALID_EXTERNAL_HANDLE,
  1152. "The same BO was imported on two different heaps");
  1153. }
  1154. bo->bo.flags = new_flags;
  1155. __sync_fetch_and_add(&bo->refcount, 1);
  1156. } else {
  1157. off_t size = lseek(fd, 0, SEEK_END);
  1158. if (size == (off_t)-1) {
  1159. anv_gem_close(device, gem_handle);
  1160. pthread_mutex_unlock(&cache->mutex);
  1161. return vk_error(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR);
  1162. }
  1163. bo = vk_alloc(&device->alloc, sizeof(struct anv_cached_bo), 8,
  1164. VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
  1165. if (!bo) {
  1166. anv_gem_close(device, gem_handle);
  1167. pthread_mutex_unlock(&cache->mutex);
  1168. return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
  1169. }
  1170. bo->refcount = 1;
  1171. anv_bo_init(&bo->bo, gem_handle, size);
  1172. bo->bo.flags = bo_flags;
  1173. if (!anv_vma_alloc(device, &bo->bo)) {
  1174. anv_gem_close(device, bo->bo.gem_handle);
  1175. pthread_mutex_unlock(&cache->mutex);
  1176. vk_free(&device->alloc, bo);
  1177. return vk_errorf(device->instance, NULL,
  1178. VK_ERROR_OUT_OF_DEVICE_MEMORY,
  1179. "failed to allocate virtual address for BO");
  1180. }
  1181. _mesa_hash_table_insert(cache->bo_map, (void *)(uintptr_t)gem_handle, bo);
  1182. }
  1183. pthread_mutex_unlock(&cache->mutex);
  1184. *bo_out = &bo->bo;
  1185. return VK_SUCCESS;
  1186. }
  1187. VkResult
  1188. anv_bo_cache_export(struct anv_device *device,
  1189. struct anv_bo_cache *cache,
  1190. struct anv_bo *bo_in, int *fd_out)
  1191. {
  1192. assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
  1193. struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
  1194. /* This BO must have been flagged external in order for us to be able
  1195. * to export it. This is done based on external options passed into
  1196. * anv_AllocateMemory.
  1197. */
  1198. assert(bo->bo.flags & ANV_BO_EXTERNAL);
  1199. int fd = anv_gem_handle_to_fd(device, bo->bo.gem_handle);
  1200. if (fd < 0)
  1201. return vk_error(VK_ERROR_TOO_MANY_OBJECTS);
  1202. *fd_out = fd;
  1203. return VK_SUCCESS;
  1204. }
  1205. static bool
  1206. atomic_dec_not_one(uint32_t *counter)
  1207. {
  1208. uint32_t old, val;
  1209. val = *counter;
  1210. while (1) {
  1211. if (val == 1)
  1212. return false;
  1213. old = __sync_val_compare_and_swap(counter, val, val - 1);
  1214. if (old == val)
  1215. return true;
  1216. val = old;
  1217. }
  1218. }
  1219. void
  1220. anv_bo_cache_release(struct anv_device *device,
  1221. struct anv_bo_cache *cache,
  1222. struct anv_bo *bo_in)
  1223. {
  1224. assert(anv_bo_cache_lookup(cache, bo_in->gem_handle) == bo_in);
  1225. struct anv_cached_bo *bo = (struct anv_cached_bo *)bo_in;
  1226. /* Try to decrement the counter but don't go below one. If this succeeds
  1227. * then the refcount has been decremented and we are not the last
  1228. * reference.
  1229. */
  1230. if (atomic_dec_not_one(&bo->refcount))
  1231. return;
  1232. pthread_mutex_lock(&cache->mutex);
  1233. /* We are probably the last reference since our attempt to decrement above
  1234. * failed. However, we can't actually know until we are inside the mutex.
  1235. * Otherwise, someone could import the BO between the decrement and our
  1236. * taking the mutex.
  1237. */
  1238. if (unlikely(__sync_sub_and_fetch(&bo->refcount, 1) > 0)) {
  1239. /* Turns out we're not the last reference. Unlock and bail. */
  1240. pthread_mutex_unlock(&cache->mutex);
  1241. return;
  1242. }
  1243. struct hash_entry *entry =
  1244. _mesa_hash_table_search(cache->bo_map,
  1245. (const void *)(uintptr_t)bo->bo.gem_handle);
  1246. assert(entry);
  1247. _mesa_hash_table_remove(cache->bo_map, entry);
  1248. if (bo->bo.map)
  1249. anv_gem_munmap(bo->bo.map, bo->bo.size);
  1250. anv_vma_free(device, &bo->bo);
  1251. anv_gem_close(device, bo->bo.gem_handle);
  1252. /* Don't unlock until we've actually closed the BO. The whole point of
  1253. * the BO cache is to ensure that we correctly handle races with creating
  1254. * and releasing GEM handles and we don't want to let someone import the BO
  1255. * again between mutex unlock and closing the GEM handle.
  1256. */
  1257. pthread_mutex_unlock(&cache->mutex);
  1258. vk_free(&device->alloc, bo);
  1259. }