1 // SPDX-License-Identifier: MIT 2 /* 3 * Copyright 2014-2018 Advanced Micro Devices, Inc. 4 * 5 * Permission is hereby granted, free of charge, to any person obtaining a 6 * copy of this software and associated documentation files (the "Software"), 7 * to deal in the Software without restriction, including without limitation 8 * the rights to use, copy, modify, merge, publish, distribute, sublicense, 9 * and/or sell copies of the Software, and to permit persons to whom the 10 * Software is furnished to do so, subject to the following conditions: 11 * 12 * The above copyright notice and this permission notice shall be included in 13 * all copies or substantial portions of the 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR 19 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 20 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 21 * OTHER DEALINGS IN THE SOFTWARE. 22 */ 23 #include <linux/dma-buf.h> 24 #include <linux/list.h> 25 #include <linux/pagemap.h> 26 #include <linux/sched/mm.h> 27 #include <linux/sched/task.h> 28 #include <drm/ttm/ttm_tt.h> 29 30 #include <drm/drm_exec.h> 31 32 #include "amdgpu_object.h" 33 #include "amdgpu_gem.h" 34 #include "amdgpu_vm.h" 35 #include "amdgpu_hmm.h" 36 #include "amdgpu_amdkfd.h" 37 #include "amdgpu_dma_buf.h" 38 #include <uapi/linux/kfd_ioctl.h> 39 #include "amdgpu_xgmi.h" 40 #include "kfd_priv.h" 41 #include "kfd_smi_events.h" 42 43 /* Userptr restore delay, just long enough to allow consecutive VM 44 * changes to accumulate 45 */ 46 #define AMDGPU_USERPTR_RESTORE_DELAY_MS 1 47 #define AMDGPU_RESERVE_MEM_LIMIT (3UL << 29) 48 49 /* 50 * Align VRAM availability to 2MB to avoid fragmentation caused by 4K allocations in the tail 2MB 51 * BO chunk 52 */ 53 #define VRAM_AVAILABLITY_ALIGN (1 << 21) 54 55 /* Impose limit on how much memory KFD can use */ 56 static struct { 57 uint64_t max_system_mem_limit; 58 uint64_t max_ttm_mem_limit; 59 int64_t system_mem_used; 60 int64_t ttm_mem_used; 61 spinlock_t mem_limit_lock; 62 } kfd_mem_limit; 63 64 static const char * const domain_bit_to_string[] = { 65 "CPU", 66 "GTT", 67 "VRAM", 68 "GDS", 69 "GWS", 70 "OA" 71 }; 72 73 #define domain_string(domain) domain_bit_to_string[ffs(domain)-1] 74 75 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work); 76 77 static bool kfd_mem_is_attached(struct amdgpu_vm *avm, 78 struct kgd_mem *mem) 79 { 80 struct kfd_mem_attachment *entry; 81 82 list_for_each_entry(entry, &mem->attachments, list) 83 if (entry->bo_va->base.vm == avm) 84 return true; 85 86 return false; 87 } 88 89 /** 90 * reuse_dmamap() - Check whether adev can share the original 91 * userptr BO 92 * 93 * If both adev and bo_adev are in direct mapping or 94 * in the same iommu group, they can share the original BO. 95 * 96 * @adev: Device to which can or cannot share the original BO 97 * @bo_adev: Device to which allocated BO belongs to 98 * 99 * Return: returns true if adev can share original userptr BO, 100 * false otherwise. 101 */ 102 static bool reuse_dmamap(struct amdgpu_device *adev, struct amdgpu_device *bo_adev) 103 { 104 return (adev->ram_is_direct_mapped && bo_adev->ram_is_direct_mapped) || 105 (adev->dev->iommu_group == bo_adev->dev->iommu_group); 106 } 107 108 /* Set memory usage limits. Current, limits are 109 * System (TTM + userptr) memory - 15/16th System RAM 110 * TTM memory - 3/8th System RAM 111 */ 112 void amdgpu_amdkfd_gpuvm_init_mem_limits(void) 113 { 114 struct sysinfo si; 115 uint64_t mem; 116 117 if (kfd_mem_limit.max_system_mem_limit) 118 return; 119 120 si_meminfo(&si); 121 mem = si.totalram - si.totalhigh; 122 mem *= si.mem_unit; 123 124 spin_lock_init(&kfd_mem_limit.mem_limit_lock); 125 kfd_mem_limit.max_system_mem_limit = mem - (mem >> 6); 126 if (kfd_mem_limit.max_system_mem_limit < 2 * AMDGPU_RESERVE_MEM_LIMIT) 127 kfd_mem_limit.max_system_mem_limit >>= 1; 128 else 129 kfd_mem_limit.max_system_mem_limit -= AMDGPU_RESERVE_MEM_LIMIT; 130 131 kfd_mem_limit.max_ttm_mem_limit = ttm_tt_pages_limit() << PAGE_SHIFT; 132 pr_debug("Kernel memory limit %lluM, TTM limit %lluM\n", 133 (kfd_mem_limit.max_system_mem_limit >> 20), 134 (kfd_mem_limit.max_ttm_mem_limit >> 20)); 135 } 136 137 void amdgpu_amdkfd_reserve_system_mem(uint64_t size) 138 { 139 kfd_mem_limit.system_mem_used += size; 140 } 141 142 /* Estimate page table size needed to represent a given memory size 143 * 144 * With 4KB pages, we need one 8 byte PTE for each 4KB of memory 145 * (factor 512, >> 9). With 2MB pages, we need one 8 byte PTE for 2MB 146 * of memory (factor 256K, >> 18). ROCm user mode tries to optimize 147 * for 2MB pages for TLB efficiency. However, small allocations and 148 * fragmented system memory still need some 4KB pages. We choose a 149 * compromise that should work in most cases without reserving too 150 * much memory for page tables unnecessarily (factor 16K, >> 14). 151 */ 152 153 #define ESTIMATE_PT_SIZE(mem_size) max(((mem_size) >> 14), AMDGPU_VM_RESERVED_VRAM) 154 155 /** 156 * amdgpu_amdkfd_reserve_mem_limit() - Decrease available memory by size 157 * of buffer. 158 * 159 * @adev: Device to which allocated BO belongs to 160 * @size: Size of buffer, in bytes, encapsulated by B0. This should be 161 * equivalent to amdgpu_bo_size(BO) 162 * @alloc_flag: Flag used in allocating a BO as noted above 163 * @xcp_id: xcp_id is used to get xcp from xcp manager, one xcp is 164 * managed as one compute node in driver for app 165 * 166 * Return: 167 * returns -ENOMEM in case of error, ZERO otherwise 168 */ 169 int amdgpu_amdkfd_reserve_mem_limit(struct amdgpu_device *adev, 170 uint64_t size, u32 alloc_flag, int8_t xcp_id) 171 { 172 uint64_t reserved_for_pt = 173 ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size); 174 struct amdgpu_ras *con = amdgpu_ras_get_context(adev); 175 uint64_t reserved_for_ras = (con ? con->reserved_pages_in_bytes : 0); 176 size_t system_mem_needed, ttm_mem_needed, vram_needed; 177 int ret = 0; 178 uint64_t vram_size = 0; 179 180 system_mem_needed = 0; 181 ttm_mem_needed = 0; 182 vram_needed = 0; 183 if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) { 184 system_mem_needed = size; 185 ttm_mem_needed = size; 186 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) { 187 /* 188 * Conservatively round up the allocation requirement to 2 MB 189 * to avoid fragmentation caused by 4K allocations in the tail 190 * 2M BO chunk. 191 */ 192 vram_needed = size; 193 /* 194 * For GFX 9.4.3, get the VRAM size from XCP structs 195 */ 196 if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id)) 197 return -EINVAL; 198 199 vram_size = KFD_XCP_MEMORY_SIZE(adev, xcp_id); 200 if (adev->apu_prefer_gtt) { 201 system_mem_needed = size; 202 ttm_mem_needed = size; 203 } 204 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) { 205 system_mem_needed = size; 206 } else if (!(alloc_flag & 207 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL | 208 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) { 209 pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag); 210 return -ENOMEM; 211 } 212 213 spin_lock(&kfd_mem_limit.mem_limit_lock); 214 215 if (kfd_mem_limit.system_mem_used + system_mem_needed > 216 kfd_mem_limit.max_system_mem_limit) { 217 pr_debug("Set no_system_mem_limit=1 if using shared memory\n"); 218 if (!no_system_mem_limit) { 219 ret = -ENOMEM; 220 goto release; 221 } 222 } 223 224 if (kfd_mem_limit.ttm_mem_used + ttm_mem_needed > 225 kfd_mem_limit.max_ttm_mem_limit) { 226 ret = -ENOMEM; 227 goto release; 228 } 229 230 /*if is_app_apu is false and apu_prefer_gtt is true, it is an APU with 231 * carve out < gtt. In that case, VRAM allocation will go to gtt domain, skip 232 * VRAM check since ttm_mem_limit check already cover this allocation 233 */ 234 235 if (adev && xcp_id >= 0 && (!adev->apu_prefer_gtt || adev->gmc.is_app_apu)) { 236 uint64_t vram_available = 237 vram_size - reserved_for_pt - reserved_for_ras - 238 atomic64_read(&adev->vram_pin_size); 239 if (adev->kfd.vram_used[xcp_id] + vram_needed > vram_available) { 240 ret = -ENOMEM; 241 goto release; 242 } 243 } 244 245 /* Update memory accounting by decreasing available system 246 * memory, TTM memory and GPU memory as computed above 247 */ 248 WARN_ONCE(vram_needed && !adev, 249 "adev reference can't be null when vram is used"); 250 if (adev && xcp_id >= 0) { 251 adev->kfd.vram_used[xcp_id] += vram_needed; 252 adev->kfd.vram_used_aligned[xcp_id] += 253 adev->apu_prefer_gtt ? 254 vram_needed : 255 ALIGN(vram_needed, VRAM_AVAILABLITY_ALIGN); 256 } 257 kfd_mem_limit.system_mem_used += system_mem_needed; 258 kfd_mem_limit.ttm_mem_used += ttm_mem_needed; 259 260 release: 261 spin_unlock(&kfd_mem_limit.mem_limit_lock); 262 return ret; 263 } 264 265 void amdgpu_amdkfd_unreserve_mem_limit(struct amdgpu_device *adev, 266 uint64_t size, u32 alloc_flag, int8_t xcp_id) 267 { 268 spin_lock(&kfd_mem_limit.mem_limit_lock); 269 270 if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_GTT) { 271 kfd_mem_limit.system_mem_used -= size; 272 kfd_mem_limit.ttm_mem_used -= size; 273 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) { 274 WARN_ONCE(!adev, 275 "adev reference can't be null when alloc mem flags vram is set"); 276 if (WARN_ONCE(xcp_id < 0, "invalid XCP ID %d", xcp_id)) 277 goto release; 278 279 if (adev) { 280 adev->kfd.vram_used[xcp_id] -= size; 281 if (adev->apu_prefer_gtt) { 282 adev->kfd.vram_used_aligned[xcp_id] -= size; 283 kfd_mem_limit.system_mem_used -= size; 284 kfd_mem_limit.ttm_mem_used -= size; 285 } else { 286 adev->kfd.vram_used_aligned[xcp_id] -= 287 ALIGN(size, VRAM_AVAILABLITY_ALIGN); 288 } 289 } 290 } else if (alloc_flag & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) { 291 kfd_mem_limit.system_mem_used -= size; 292 } else if (!(alloc_flag & 293 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL | 294 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) { 295 pr_err("%s: Invalid BO type %#x\n", __func__, alloc_flag); 296 goto release; 297 } 298 WARN_ONCE(adev && xcp_id >= 0 && adev->kfd.vram_used[xcp_id] < 0, 299 "KFD VRAM memory accounting unbalanced for xcp: %d", xcp_id); 300 WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0, 301 "KFD TTM memory accounting unbalanced"); 302 WARN_ONCE(kfd_mem_limit.system_mem_used < 0, 303 "KFD system memory accounting unbalanced"); 304 305 release: 306 spin_unlock(&kfd_mem_limit.mem_limit_lock); 307 } 308 309 void amdgpu_amdkfd_release_notify(struct amdgpu_bo *bo) 310 { 311 struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev); 312 u32 alloc_flags = bo->kfd_bo->alloc_flags; 313 u64 size = amdgpu_bo_size(bo); 314 315 amdgpu_amdkfd_unreserve_mem_limit(adev, size, alloc_flags, 316 bo->xcp_id); 317 318 kfree(bo->kfd_bo); 319 } 320 321 /** 322 * create_dmamap_sg_bo() - Creates a amdgpu_bo object to reflect information 323 * about USERPTR or DOOREBELL or MMIO BO. 324 * 325 * @adev: Device for which dmamap BO is being created 326 * @mem: BO of peer device that is being DMA mapped. Provides parameters 327 * in building the dmamap BO 328 * @bo_out: Output parameter updated with handle of dmamap BO 329 */ 330 static int 331 create_dmamap_sg_bo(struct amdgpu_device *adev, 332 struct kgd_mem *mem, struct amdgpu_bo **bo_out) 333 { 334 struct drm_gem_object *gem_obj; 335 int ret; 336 uint64_t flags = 0; 337 338 ret = amdgpu_bo_reserve(mem->bo, false); 339 if (ret) 340 return ret; 341 342 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) 343 flags |= mem->bo->flags & (AMDGPU_GEM_CREATE_COHERENT | 344 AMDGPU_GEM_CREATE_UNCACHED); 345 346 ret = amdgpu_gem_object_create(adev, mem->bo->tbo.base.size, 1, 347 AMDGPU_GEM_DOMAIN_CPU, AMDGPU_GEM_CREATE_PREEMPTIBLE | flags, 348 ttm_bo_type_sg, mem->bo->tbo.base.resv, &gem_obj, 0); 349 350 amdgpu_bo_unreserve(mem->bo); 351 352 if (ret) { 353 pr_err("Error in creating DMA mappable SG BO on domain: %d\n", ret); 354 return -EINVAL; 355 } 356 357 *bo_out = gem_to_amdgpu_bo(gem_obj); 358 (*bo_out)->parent = amdgpu_bo_ref(mem->bo); 359 return ret; 360 } 361 362 /* amdgpu_amdkfd_remove_eviction_fence - Removes eviction fence from BO's 363 * reservation object. 364 * 365 * @bo: [IN] Remove eviction fence(s) from this BO 366 * @ef: [IN] This eviction fence is removed if it 367 * is present in the shared list. 368 * 369 * NOTE: Must be called with BO reserved i.e. bo->tbo.resv->lock held. 370 */ 371 static int amdgpu_amdkfd_remove_eviction_fence(struct amdgpu_bo *bo, 372 struct amdgpu_amdkfd_fence *ef) 373 { 374 struct dma_fence *replacement; 375 376 if (!ef) 377 return -EINVAL; 378 379 /* TODO: Instead of block before we should use the fence of the page 380 * table update and TLB flush here directly. 381 */ 382 replacement = dma_fence_get_stub(); 383 dma_resv_replace_fences(bo->tbo.base.resv, ef->base.context, 384 replacement, DMA_RESV_USAGE_BOOKKEEP); 385 dma_fence_put(replacement); 386 return 0; 387 } 388 389 /** 390 * amdgpu_amdkfd_remove_all_eviction_fences - Remove all eviction fences 391 * @bo: the BO where to remove the evictions fences from. 392 * 393 * This functions should only be used on release when all references to the BO 394 * are already dropped. We remove the eviction fence from the private copy of 395 * the dma_resv object here since that is what is used during release to 396 * determine of the BO is idle or not. 397 */ 398 void amdgpu_amdkfd_remove_all_eviction_fences(struct amdgpu_bo *bo) 399 { 400 struct dma_resv *resv = &bo->tbo.base._resv; 401 struct dma_fence *fence, *stub; 402 struct dma_resv_iter cursor; 403 404 dma_resv_assert_held(resv); 405 406 stub = dma_fence_get_stub(); 407 dma_resv_for_each_fence(&cursor, resv, DMA_RESV_USAGE_BOOKKEEP, fence) { 408 if (!to_amdgpu_amdkfd_fence(fence)) 409 continue; 410 411 dma_resv_replace_fences(resv, fence->context, stub, 412 DMA_RESV_USAGE_BOOKKEEP); 413 } 414 dma_fence_put(stub); 415 } 416 417 static int amdgpu_amdkfd_bo_validate(struct amdgpu_bo *bo, uint32_t domain, 418 bool wait) 419 { 420 struct ttm_operation_ctx ctx = { false, false }; 421 int ret; 422 423 if (WARN(amdgpu_ttm_tt_get_usermm(bo->tbo.ttm), 424 "Called with userptr BO")) 425 return -EINVAL; 426 427 /* bo has been pinned, not need validate it */ 428 if (bo->tbo.pin_count) 429 return 0; 430 431 amdgpu_bo_placement_from_domain(bo, domain); 432 433 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 434 if (ret) 435 goto validate_fail; 436 if (wait) 437 amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false); 438 439 validate_fail: 440 return ret; 441 } 442 443 int amdgpu_amdkfd_bo_validate_and_fence(struct amdgpu_bo *bo, 444 uint32_t domain, 445 struct dma_fence *fence) 446 { 447 int ret = amdgpu_bo_reserve(bo, false); 448 449 if (ret) 450 return ret; 451 452 ret = amdgpu_amdkfd_bo_validate(bo, domain, true); 453 if (ret) 454 goto unreserve_out; 455 456 ret = dma_resv_reserve_fences(bo->tbo.base.resv, 1); 457 if (ret) 458 goto unreserve_out; 459 460 dma_resv_add_fence(bo->tbo.base.resv, fence, 461 DMA_RESV_USAGE_BOOKKEEP); 462 463 unreserve_out: 464 amdgpu_bo_unreserve(bo); 465 466 return ret; 467 } 468 469 static int amdgpu_amdkfd_validate_vm_bo(void *_unused, struct amdgpu_bo *bo) 470 { 471 return amdgpu_amdkfd_bo_validate(bo, bo->allowed_domains, false); 472 } 473 474 /* vm_validate_pt_pd_bos - Validate page table and directory BOs 475 * 476 * Page directories are not updated here because huge page handling 477 * during page table updates can invalidate page directory entries 478 * again. Page directories are only updated after updating page 479 * tables. 480 */ 481 static int vm_validate_pt_pd_bos(struct amdgpu_vm *vm, 482 struct ww_acquire_ctx *ticket) 483 { 484 struct amdgpu_bo *pd = vm->root.bo; 485 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev); 486 int ret; 487 488 ret = amdgpu_vm_validate(adev, vm, ticket, 489 amdgpu_amdkfd_validate_vm_bo, NULL); 490 if (ret) { 491 pr_err("failed to validate PT BOs\n"); 492 return ret; 493 } 494 495 vm->pd_phys_addr = amdgpu_gmc_pd_addr(vm->root.bo); 496 497 return 0; 498 } 499 500 static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync) 501 { 502 struct amdgpu_bo *pd = vm->root.bo; 503 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev); 504 int ret; 505 506 ret = amdgpu_vm_update_pdes(adev, vm, false); 507 if (ret) 508 return ret; 509 510 return amdgpu_sync_fence(sync, vm->last_update, GFP_KERNEL); 511 } 512 513 static uint64_t get_pte_flags(struct amdgpu_device *adev, struct kgd_mem *mem) 514 { 515 uint32_t mapping_flags = AMDGPU_VM_PAGE_READABLE | 516 AMDGPU_VM_MTYPE_DEFAULT; 517 518 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE) 519 mapping_flags |= AMDGPU_VM_PAGE_WRITEABLE; 520 if (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE) 521 mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE; 522 523 return amdgpu_gem_va_map_flags(adev, mapping_flags); 524 } 525 526 /** 527 * create_sg_table() - Create an sg_table for a contiguous DMA addr range 528 * @addr: The starting address to point to 529 * @size: Size of memory area in bytes being pointed to 530 * 531 * Allocates an instance of sg_table and initializes it to point to memory 532 * area specified by input parameters. The address used to build is assumed 533 * to be DMA mapped, if needed. 534 * 535 * DOORBELL or MMIO BOs use only one scatterlist node in their sg_table 536 * because they are physically contiguous. 537 * 538 * Return: Initialized instance of SG Table or NULL 539 */ 540 static struct sg_table *create_sg_table(uint64_t addr, uint32_t size) 541 { 542 struct sg_table *sg = kmalloc(sizeof(*sg), GFP_KERNEL); 543 544 if (!sg) 545 return NULL; 546 if (sg_alloc_table(sg, 1, GFP_KERNEL)) { 547 kfree(sg); 548 return NULL; 549 } 550 sg_dma_address(sg->sgl) = addr; 551 sg->sgl->length = size; 552 #ifdef CONFIG_NEED_SG_DMA_LENGTH 553 sg->sgl->dma_length = size; 554 #endif 555 return sg; 556 } 557 558 static int 559 kfd_mem_dmamap_userptr(struct kgd_mem *mem, 560 struct kfd_mem_attachment *attachment) 561 { 562 enum dma_data_direction direction = 563 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? 564 DMA_BIDIRECTIONAL : DMA_TO_DEVICE; 565 struct ttm_operation_ctx ctx = {.interruptible = true}; 566 struct amdgpu_bo *bo = attachment->bo_va->base.bo; 567 struct amdgpu_device *adev = attachment->adev; 568 struct ttm_tt *src_ttm = mem->bo->tbo.ttm; 569 struct ttm_tt *ttm = bo->tbo.ttm; 570 int ret; 571 572 if (WARN_ON(ttm->num_pages != src_ttm->num_pages)) 573 return -EINVAL; 574 575 ttm->sg = kmalloc(sizeof(*ttm->sg), GFP_KERNEL); 576 if (unlikely(!ttm->sg)) 577 return -ENOMEM; 578 579 /* Same sequence as in amdgpu_ttm_tt_pin_userptr */ 580 ret = sg_alloc_table_from_pages(ttm->sg, src_ttm->pages, 581 ttm->num_pages, 0, 582 (u64)ttm->num_pages << PAGE_SHIFT, 583 GFP_KERNEL); 584 if (unlikely(ret)) 585 goto free_sg; 586 587 ret = dma_map_sgtable(adev->dev, ttm->sg, direction, 0); 588 if (unlikely(ret)) 589 goto release_sg; 590 591 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT); 592 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 593 if (ret) 594 goto unmap_sg; 595 596 return 0; 597 598 unmap_sg: 599 dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0); 600 release_sg: 601 pr_err("DMA map userptr failed: %d\n", ret); 602 sg_free_table(ttm->sg); 603 free_sg: 604 kfree(ttm->sg); 605 ttm->sg = NULL; 606 return ret; 607 } 608 609 static int 610 kfd_mem_dmamap_dmabuf(struct kfd_mem_attachment *attachment) 611 { 612 struct ttm_operation_ctx ctx = {.interruptible = true}; 613 struct amdgpu_bo *bo = attachment->bo_va->base.bo; 614 615 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT); 616 return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 617 } 618 619 /** 620 * kfd_mem_dmamap_sg_bo() - Create DMA mapped sg_table to access DOORBELL or MMIO BO 621 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device 622 * @attachment: Virtual address attachment of the BO on accessing device 623 * 624 * An access request from the device that owns DOORBELL does not require DMA mapping. 625 * This is because the request doesn't go through PCIe root complex i.e. it instead 626 * loops back. The need to DMA map arises only when accessing peer device's DOORBELL 627 * 628 * In contrast, all access requests for MMIO need to be DMA mapped without regard to 629 * device ownership. This is because access requests for MMIO go through PCIe root 630 * complex. 631 * 632 * This is accomplished in two steps: 633 * - Obtain DMA mapped address of DOORBELL or MMIO memory that could be used 634 * in updating requesting device's page table 635 * - Signal TTM to mark memory pointed to by requesting device's BO as GPU 636 * accessible. This allows an update of requesting device's page table 637 * with entries associated with DOOREBELL or MMIO memory 638 * 639 * This method is invoked in the following contexts: 640 * - Mapping of DOORBELL or MMIO BO of same or peer device 641 * - Validating an evicted DOOREBELL or MMIO BO on device seeking access 642 * 643 * Return: ZERO if successful, NON-ZERO otherwise 644 */ 645 static int 646 kfd_mem_dmamap_sg_bo(struct kgd_mem *mem, 647 struct kfd_mem_attachment *attachment) 648 { 649 struct ttm_operation_ctx ctx = {.interruptible = true}; 650 struct amdgpu_bo *bo = attachment->bo_va->base.bo; 651 struct amdgpu_device *adev = attachment->adev; 652 struct ttm_tt *ttm = bo->tbo.ttm; 653 enum dma_data_direction dir; 654 dma_addr_t dma_addr; 655 bool mmio; 656 int ret; 657 658 /* Expect SG Table of dmapmap BO to be NULL */ 659 mmio = (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP); 660 if (unlikely(ttm->sg)) { 661 pr_err("SG Table of %d BO for peer device is UNEXPECTEDLY NON-NULL", mmio); 662 return -EINVAL; 663 } 664 665 dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? 666 DMA_BIDIRECTIONAL : DMA_TO_DEVICE; 667 dma_addr = mem->bo->tbo.sg->sgl->dma_address; 668 pr_debug("%d BO size: %d\n", mmio, mem->bo->tbo.sg->sgl->length); 669 pr_debug("%d BO address before DMA mapping: %llx\n", mmio, dma_addr); 670 dma_addr = dma_map_resource(adev->dev, dma_addr, 671 mem->bo->tbo.sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC); 672 ret = dma_mapping_error(adev->dev, dma_addr); 673 if (unlikely(ret)) 674 return ret; 675 pr_debug("%d BO address after DMA mapping: %llx\n", mmio, dma_addr); 676 677 ttm->sg = create_sg_table(dma_addr, mem->bo->tbo.sg->sgl->length); 678 if (unlikely(!ttm->sg)) { 679 ret = -ENOMEM; 680 goto unmap_sg; 681 } 682 683 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT); 684 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 685 if (unlikely(ret)) 686 goto free_sg; 687 688 return ret; 689 690 free_sg: 691 sg_free_table(ttm->sg); 692 kfree(ttm->sg); 693 ttm->sg = NULL; 694 unmap_sg: 695 dma_unmap_resource(adev->dev, dma_addr, mem->bo->tbo.sg->sgl->length, 696 dir, DMA_ATTR_SKIP_CPU_SYNC); 697 return ret; 698 } 699 700 static int 701 kfd_mem_dmamap_attachment(struct kgd_mem *mem, 702 struct kfd_mem_attachment *attachment) 703 { 704 switch (attachment->type) { 705 case KFD_MEM_ATT_SHARED: 706 return 0; 707 case KFD_MEM_ATT_USERPTR: 708 return kfd_mem_dmamap_userptr(mem, attachment); 709 case KFD_MEM_ATT_DMABUF: 710 return kfd_mem_dmamap_dmabuf(attachment); 711 case KFD_MEM_ATT_SG: 712 return kfd_mem_dmamap_sg_bo(mem, attachment); 713 default: 714 WARN_ON_ONCE(1); 715 } 716 return -EINVAL; 717 } 718 719 static void 720 kfd_mem_dmaunmap_userptr(struct kgd_mem *mem, 721 struct kfd_mem_attachment *attachment) 722 { 723 enum dma_data_direction direction = 724 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? 725 DMA_BIDIRECTIONAL : DMA_TO_DEVICE; 726 struct ttm_operation_ctx ctx = {.interruptible = false}; 727 struct amdgpu_bo *bo = attachment->bo_va->base.bo; 728 struct amdgpu_device *adev = attachment->adev; 729 struct ttm_tt *ttm = bo->tbo.ttm; 730 731 if (unlikely(!ttm->sg)) 732 return; 733 734 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU); 735 (void)ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 736 737 dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0); 738 sg_free_table(ttm->sg); 739 kfree(ttm->sg); 740 ttm->sg = NULL; 741 } 742 743 static void 744 kfd_mem_dmaunmap_dmabuf(struct kfd_mem_attachment *attachment) 745 { 746 /* This is a no-op. We don't want to trigger eviction fences when 747 * unmapping DMABufs. Therefore the invalidation (moving to system 748 * domain) is done in kfd_mem_dmamap_dmabuf. 749 */ 750 } 751 752 /** 753 * kfd_mem_dmaunmap_sg_bo() - Free DMA mapped sg_table of DOORBELL or MMIO BO 754 * @mem: SG BO of the DOORBELL or MMIO resource on the owning device 755 * @attachment: Virtual address attachment of the BO on accessing device 756 * 757 * The method performs following steps: 758 * - Signal TTM to mark memory pointed to by BO as GPU inaccessible 759 * - Free SG Table that is used to encapsulate DMA mapped memory of 760 * peer device's DOORBELL or MMIO memory 761 * 762 * This method is invoked in the following contexts: 763 * UNMapping of DOORBELL or MMIO BO on a device having access to its memory 764 * Eviction of DOOREBELL or MMIO BO on device having access to its memory 765 * 766 * Return: void 767 */ 768 static void 769 kfd_mem_dmaunmap_sg_bo(struct kgd_mem *mem, 770 struct kfd_mem_attachment *attachment) 771 { 772 struct ttm_operation_ctx ctx = {.interruptible = true}; 773 struct amdgpu_bo *bo = attachment->bo_va->base.bo; 774 struct amdgpu_device *adev = attachment->adev; 775 struct ttm_tt *ttm = bo->tbo.ttm; 776 enum dma_data_direction dir; 777 778 if (unlikely(!ttm->sg)) { 779 pr_debug("SG Table of BO is NULL"); 780 return; 781 } 782 783 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU); 784 (void)ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 785 786 dir = mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? 787 DMA_BIDIRECTIONAL : DMA_TO_DEVICE; 788 dma_unmap_resource(adev->dev, ttm->sg->sgl->dma_address, 789 ttm->sg->sgl->length, dir, DMA_ATTR_SKIP_CPU_SYNC); 790 sg_free_table(ttm->sg); 791 kfree(ttm->sg); 792 ttm->sg = NULL; 793 bo->tbo.sg = NULL; 794 } 795 796 static void 797 kfd_mem_dmaunmap_attachment(struct kgd_mem *mem, 798 struct kfd_mem_attachment *attachment) 799 { 800 switch (attachment->type) { 801 case KFD_MEM_ATT_SHARED: 802 break; 803 case KFD_MEM_ATT_USERPTR: 804 kfd_mem_dmaunmap_userptr(mem, attachment); 805 break; 806 case KFD_MEM_ATT_DMABUF: 807 kfd_mem_dmaunmap_dmabuf(attachment); 808 break; 809 case KFD_MEM_ATT_SG: 810 kfd_mem_dmaunmap_sg_bo(mem, attachment); 811 break; 812 default: 813 WARN_ON_ONCE(1); 814 } 815 } 816 817 static int kfd_mem_export_dmabuf(struct kgd_mem *mem) 818 { 819 if (!mem->dmabuf) { 820 struct amdgpu_device *bo_adev; 821 struct dma_buf *dmabuf; 822 823 bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev); 824 dmabuf = drm_gem_prime_handle_to_dmabuf(&bo_adev->ddev, bo_adev->kfd.client.file, 825 mem->gem_handle, 826 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE ? 827 DRM_RDWR : 0); 828 if (IS_ERR(dmabuf)) 829 return PTR_ERR(dmabuf); 830 mem->dmabuf = dmabuf; 831 } 832 833 return 0; 834 } 835 836 static int 837 kfd_mem_attach_dmabuf(struct amdgpu_device *adev, struct kgd_mem *mem, 838 struct amdgpu_bo **bo) 839 { 840 struct drm_gem_object *gobj; 841 int ret; 842 843 ret = kfd_mem_export_dmabuf(mem); 844 if (ret) 845 return ret; 846 847 gobj = amdgpu_gem_prime_import(adev_to_drm(adev), mem->dmabuf); 848 if (IS_ERR(gobj)) 849 return PTR_ERR(gobj); 850 851 *bo = gem_to_amdgpu_bo(gobj); 852 (*bo)->flags |= AMDGPU_GEM_CREATE_PREEMPTIBLE; 853 854 return 0; 855 } 856 857 /* kfd_mem_attach - Add a BO to a VM 858 * 859 * Everything that needs to bo done only once when a BO is first added 860 * to a VM. It can later be mapped and unmapped many times without 861 * repeating these steps. 862 * 863 * 0. Create BO for DMA mapping, if needed 864 * 1. Allocate and initialize BO VA entry data structure 865 * 2. Add BO to the VM 866 * 3. Determine ASIC-specific PTE flags 867 * 4. Alloc page tables and directories if needed 868 * 4a. Validate new page tables and directories 869 */ 870 static int kfd_mem_attach(struct amdgpu_device *adev, struct kgd_mem *mem, 871 struct amdgpu_vm *vm, bool is_aql) 872 { 873 struct amdgpu_device *bo_adev = amdgpu_ttm_adev(mem->bo->tbo.bdev); 874 unsigned long bo_size = mem->bo->tbo.base.size; 875 uint64_t va = mem->va; 876 struct kfd_mem_attachment *attachment[2] = {NULL, NULL}; 877 struct amdgpu_bo *bo[2] = {NULL, NULL}; 878 struct amdgpu_bo_va *bo_va; 879 bool same_hive = false; 880 int i, ret; 881 882 if (!va) { 883 pr_err("Invalid VA when adding BO to VM\n"); 884 return -EINVAL; 885 } 886 887 /* Determine access to VRAM, MMIO and DOORBELL BOs of peer devices 888 * 889 * The access path of MMIO and DOORBELL BOs of is always over PCIe. 890 * In contrast the access path of VRAM BOs depens upon the type of 891 * link that connects the peer device. Access over PCIe is allowed 892 * if peer device has large BAR. In contrast, access over xGMI is 893 * allowed for both small and large BAR configurations of peer device 894 */ 895 if ((adev != bo_adev && !adev->apu_prefer_gtt) && 896 ((mem->domain == AMDGPU_GEM_DOMAIN_VRAM) || 897 (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL) || 898 (mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP))) { 899 if (mem->domain == AMDGPU_GEM_DOMAIN_VRAM) 900 same_hive = amdgpu_xgmi_same_hive(adev, bo_adev); 901 if (!same_hive && !amdgpu_device_is_peer_accessible(bo_adev, adev)) 902 return -EINVAL; 903 } 904 905 for (i = 0; i <= is_aql; i++) { 906 attachment[i] = kzalloc(sizeof(*attachment[i]), GFP_KERNEL); 907 if (unlikely(!attachment[i])) { 908 ret = -ENOMEM; 909 goto unwind; 910 } 911 912 pr_debug("\t add VA 0x%llx - 0x%llx to vm %p\n", va, 913 va + bo_size, vm); 914 915 if ((adev == bo_adev && !(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) || 916 (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) && reuse_dmamap(adev, bo_adev)) || 917 (mem->domain == AMDGPU_GEM_DOMAIN_GTT && reuse_dmamap(adev, bo_adev)) || 918 same_hive) { 919 /* Mappings on the local GPU, or VRAM mappings in the 920 * local hive, or userptr, or GTT mapping can reuse dma map 921 * address space share the original BO 922 */ 923 attachment[i]->type = KFD_MEM_ATT_SHARED; 924 bo[i] = mem->bo; 925 drm_gem_object_get(&bo[i]->tbo.base); 926 } else if (i > 0) { 927 /* Multiple mappings on the same GPU share the BO */ 928 attachment[i]->type = KFD_MEM_ATT_SHARED; 929 bo[i] = bo[0]; 930 drm_gem_object_get(&bo[i]->tbo.base); 931 } else if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) { 932 /* Create an SG BO to DMA-map userptrs on other GPUs */ 933 attachment[i]->type = KFD_MEM_ATT_USERPTR; 934 ret = create_dmamap_sg_bo(adev, mem, &bo[i]); 935 if (ret) 936 goto unwind; 937 /* Handle DOORBELL BOs of peer devices and MMIO BOs of local and peer devices */ 938 } else if (mem->bo->tbo.type == ttm_bo_type_sg) { 939 WARN_ONCE(!(mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL || 940 mem->alloc_flags & KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP), 941 "Handing invalid SG BO in ATTACH request"); 942 attachment[i]->type = KFD_MEM_ATT_SG; 943 ret = create_dmamap_sg_bo(adev, mem, &bo[i]); 944 if (ret) 945 goto unwind; 946 /* Enable acces to GTT and VRAM BOs of peer devices */ 947 } else if (mem->domain == AMDGPU_GEM_DOMAIN_GTT || 948 mem->domain == AMDGPU_GEM_DOMAIN_VRAM) { 949 attachment[i]->type = KFD_MEM_ATT_DMABUF; 950 ret = kfd_mem_attach_dmabuf(adev, mem, &bo[i]); 951 if (ret) 952 goto unwind; 953 pr_debug("Employ DMABUF mechanism to enable peer GPU access\n"); 954 } else { 955 WARN_ONCE(true, "Handling invalid ATTACH request"); 956 ret = -EINVAL; 957 goto unwind; 958 } 959 960 /* Add BO to VM internal data structures */ 961 ret = amdgpu_bo_reserve(bo[i], false); 962 if (ret) { 963 pr_debug("Unable to reserve BO during memory attach"); 964 goto unwind; 965 } 966 bo_va = amdgpu_vm_bo_find(vm, bo[i]); 967 if (!bo_va) 968 bo_va = amdgpu_vm_bo_add(adev, vm, bo[i]); 969 else 970 ++bo_va->ref_count; 971 attachment[i]->bo_va = bo_va; 972 amdgpu_bo_unreserve(bo[i]); 973 if (unlikely(!attachment[i]->bo_va)) { 974 ret = -ENOMEM; 975 pr_err("Failed to add BO object to VM. ret == %d\n", 976 ret); 977 goto unwind; 978 } 979 attachment[i]->va = va; 980 attachment[i]->pte_flags = get_pte_flags(adev, mem); 981 attachment[i]->adev = adev; 982 list_add(&attachment[i]->list, &mem->attachments); 983 984 va += bo_size; 985 } 986 987 return 0; 988 989 unwind: 990 for (; i >= 0; i--) { 991 if (!attachment[i]) 992 continue; 993 if (attachment[i]->bo_va) { 994 (void)amdgpu_bo_reserve(bo[i], true); 995 if (--attachment[i]->bo_va->ref_count == 0) 996 amdgpu_vm_bo_del(adev, attachment[i]->bo_va); 997 amdgpu_bo_unreserve(bo[i]); 998 list_del(&attachment[i]->list); 999 } 1000 if (bo[i]) 1001 drm_gem_object_put(&bo[i]->tbo.base); 1002 kfree(attachment[i]); 1003 } 1004 return ret; 1005 } 1006 1007 static void kfd_mem_detach(struct kfd_mem_attachment *attachment) 1008 { 1009 struct amdgpu_bo *bo = attachment->bo_va->base.bo; 1010 1011 pr_debug("\t remove VA 0x%llx in entry %p\n", 1012 attachment->va, attachment); 1013 if (--attachment->bo_va->ref_count == 0) 1014 amdgpu_vm_bo_del(attachment->adev, attachment->bo_va); 1015 drm_gem_object_put(&bo->tbo.base); 1016 list_del(&attachment->list); 1017 kfree(attachment); 1018 } 1019 1020 static void add_kgd_mem_to_kfd_bo_list(struct kgd_mem *mem, 1021 struct amdkfd_process_info *process_info, 1022 bool userptr) 1023 { 1024 mutex_lock(&process_info->lock); 1025 if (userptr) 1026 list_add_tail(&mem->validate_list, 1027 &process_info->userptr_valid_list); 1028 else 1029 list_add_tail(&mem->validate_list, &process_info->kfd_bo_list); 1030 mutex_unlock(&process_info->lock); 1031 } 1032 1033 static void remove_kgd_mem_from_kfd_bo_list(struct kgd_mem *mem, 1034 struct amdkfd_process_info *process_info) 1035 { 1036 mutex_lock(&process_info->lock); 1037 list_del(&mem->validate_list); 1038 mutex_unlock(&process_info->lock); 1039 } 1040 1041 /* Initializes user pages. It registers the MMU notifier and validates 1042 * the userptr BO in the GTT domain. 1043 * 1044 * The BO must already be on the userptr_valid_list. Otherwise an 1045 * eviction and restore may happen that leaves the new BO unmapped 1046 * with the user mode queues running. 1047 * 1048 * Takes the process_info->lock to protect against concurrent restore 1049 * workers. 1050 * 1051 * Returns 0 for success, negative errno for errors. 1052 */ 1053 static int init_user_pages(struct kgd_mem *mem, uint64_t user_addr, 1054 bool criu_resume) 1055 { 1056 struct amdkfd_process_info *process_info = mem->process_info; 1057 struct amdgpu_bo *bo = mem->bo; 1058 struct ttm_operation_ctx ctx = { true, false }; 1059 struct hmm_range *range; 1060 int ret = 0; 1061 1062 mutex_lock(&process_info->lock); 1063 1064 ret = amdgpu_ttm_tt_set_userptr(&bo->tbo, user_addr, 0); 1065 if (ret) { 1066 pr_err("%s: Failed to set userptr: %d\n", __func__, ret); 1067 goto out; 1068 } 1069 1070 ret = amdgpu_hmm_register(bo, user_addr); 1071 if (ret) { 1072 pr_err("%s: Failed to register MMU notifier: %d\n", 1073 __func__, ret); 1074 goto out; 1075 } 1076 1077 if (criu_resume) { 1078 /* 1079 * During a CRIU restore operation, the userptr buffer objects 1080 * will be validated in the restore_userptr_work worker at a 1081 * later stage when it is scheduled by another ioctl called by 1082 * CRIU master process for the target pid for restore. 1083 */ 1084 mutex_lock(&process_info->notifier_lock); 1085 mem->invalid++; 1086 mutex_unlock(&process_info->notifier_lock); 1087 mutex_unlock(&process_info->lock); 1088 return 0; 1089 } 1090 1091 ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages, &range); 1092 if (ret) { 1093 if (ret == -EAGAIN) 1094 pr_debug("Failed to get user pages, try again\n"); 1095 else 1096 pr_err("%s: Failed to get user pages: %d\n", __func__, ret); 1097 goto unregister_out; 1098 } 1099 1100 ret = amdgpu_bo_reserve(bo, true); 1101 if (ret) { 1102 pr_err("%s: Failed to reserve BO\n", __func__); 1103 goto release_out; 1104 } 1105 amdgpu_bo_placement_from_domain(bo, mem->domain); 1106 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 1107 if (ret) 1108 pr_err("%s: failed to validate BO\n", __func__); 1109 amdgpu_bo_unreserve(bo); 1110 1111 release_out: 1112 amdgpu_ttm_tt_get_user_pages_done(bo->tbo.ttm, range); 1113 unregister_out: 1114 if (ret) 1115 amdgpu_hmm_unregister(bo); 1116 out: 1117 mutex_unlock(&process_info->lock); 1118 return ret; 1119 } 1120 1121 /* Reserving a BO and its page table BOs must happen atomically to 1122 * avoid deadlocks. Some operations update multiple VMs at once. Track 1123 * all the reservation info in a context structure. Optionally a sync 1124 * object can track VM updates. 1125 */ 1126 struct bo_vm_reservation_context { 1127 /* DRM execution context for the reservation */ 1128 struct drm_exec exec; 1129 /* Number of VMs reserved */ 1130 unsigned int n_vms; 1131 /* Pointer to sync object */ 1132 struct amdgpu_sync *sync; 1133 }; 1134 1135 enum bo_vm_match { 1136 BO_VM_NOT_MAPPED = 0, /* Match VMs where a BO is not mapped */ 1137 BO_VM_MAPPED, /* Match VMs where a BO is mapped */ 1138 BO_VM_ALL, /* Match all VMs a BO was added to */ 1139 }; 1140 1141 /** 1142 * reserve_bo_and_vm - reserve a BO and a VM unconditionally. 1143 * @mem: KFD BO structure. 1144 * @vm: the VM to reserve. 1145 * @ctx: the struct that will be used in unreserve_bo_and_vms(). 1146 */ 1147 static int reserve_bo_and_vm(struct kgd_mem *mem, 1148 struct amdgpu_vm *vm, 1149 struct bo_vm_reservation_context *ctx) 1150 { 1151 struct amdgpu_bo *bo = mem->bo; 1152 int ret; 1153 1154 WARN_ON(!vm); 1155 1156 ctx->n_vms = 1; 1157 ctx->sync = &mem->sync; 1158 drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT, 0); 1159 drm_exec_until_all_locked(&ctx->exec) { 1160 ret = amdgpu_vm_lock_pd(vm, &ctx->exec, 2); 1161 drm_exec_retry_on_contention(&ctx->exec); 1162 if (unlikely(ret)) 1163 goto error; 1164 1165 ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1); 1166 drm_exec_retry_on_contention(&ctx->exec); 1167 if (unlikely(ret)) 1168 goto error; 1169 } 1170 return 0; 1171 1172 error: 1173 pr_err("Failed to reserve buffers in ttm.\n"); 1174 drm_exec_fini(&ctx->exec); 1175 return ret; 1176 } 1177 1178 /** 1179 * reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally 1180 * @mem: KFD BO structure. 1181 * @vm: the VM to reserve. If NULL, then all VMs associated with the BO 1182 * is used. Otherwise, a single VM associated with the BO. 1183 * @map_type: the mapping status that will be used to filter the VMs. 1184 * @ctx: the struct that will be used in unreserve_bo_and_vms(). 1185 * 1186 * Returns 0 for success, negative for failure. 1187 */ 1188 static int reserve_bo_and_cond_vms(struct kgd_mem *mem, 1189 struct amdgpu_vm *vm, enum bo_vm_match map_type, 1190 struct bo_vm_reservation_context *ctx) 1191 { 1192 struct kfd_mem_attachment *entry; 1193 struct amdgpu_bo *bo = mem->bo; 1194 int ret; 1195 1196 ctx->sync = &mem->sync; 1197 drm_exec_init(&ctx->exec, DRM_EXEC_INTERRUPTIBLE_WAIT | 1198 DRM_EXEC_IGNORE_DUPLICATES, 0); 1199 drm_exec_until_all_locked(&ctx->exec) { 1200 ctx->n_vms = 0; 1201 list_for_each_entry(entry, &mem->attachments, list) { 1202 if ((vm && vm != entry->bo_va->base.vm) || 1203 (entry->is_mapped != map_type 1204 && map_type != BO_VM_ALL)) 1205 continue; 1206 1207 ret = amdgpu_vm_lock_pd(entry->bo_va->base.vm, 1208 &ctx->exec, 2); 1209 drm_exec_retry_on_contention(&ctx->exec); 1210 if (unlikely(ret)) 1211 goto error; 1212 ++ctx->n_vms; 1213 } 1214 1215 ret = drm_exec_prepare_obj(&ctx->exec, &bo->tbo.base, 1); 1216 drm_exec_retry_on_contention(&ctx->exec); 1217 if (unlikely(ret)) 1218 goto error; 1219 } 1220 return 0; 1221 1222 error: 1223 pr_err("Failed to reserve buffers in ttm.\n"); 1224 drm_exec_fini(&ctx->exec); 1225 return ret; 1226 } 1227 1228 /** 1229 * unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context 1230 * @ctx: Reservation context to unreserve 1231 * @wait: Optionally wait for a sync object representing pending VM updates 1232 * @intr: Whether the wait is interruptible 1233 * 1234 * Also frees any resources allocated in 1235 * reserve_bo_and_(cond_)vm(s). Returns the status from 1236 * amdgpu_sync_wait. 1237 */ 1238 static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx, 1239 bool wait, bool intr) 1240 { 1241 int ret = 0; 1242 1243 if (wait) 1244 ret = amdgpu_sync_wait(ctx->sync, intr); 1245 1246 drm_exec_fini(&ctx->exec); 1247 ctx->sync = NULL; 1248 return ret; 1249 } 1250 1251 static int unmap_bo_from_gpuvm(struct kgd_mem *mem, 1252 struct kfd_mem_attachment *entry, 1253 struct amdgpu_sync *sync) 1254 { 1255 struct amdgpu_bo_va *bo_va = entry->bo_va; 1256 struct amdgpu_device *adev = entry->adev; 1257 struct amdgpu_vm *vm = bo_va->base.vm; 1258 1259 if (bo_va->queue_refcount) { 1260 pr_debug("bo_va->queue_refcount %d\n", bo_va->queue_refcount); 1261 return -EBUSY; 1262 } 1263 1264 (void)amdgpu_vm_bo_unmap(adev, bo_va, entry->va); 1265 1266 (void)amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update); 1267 1268 (void)amdgpu_sync_fence(sync, bo_va->last_pt_update, GFP_KERNEL); 1269 1270 return 0; 1271 } 1272 1273 static int update_gpuvm_pte(struct kgd_mem *mem, 1274 struct kfd_mem_attachment *entry, 1275 struct amdgpu_sync *sync) 1276 { 1277 struct amdgpu_bo_va *bo_va = entry->bo_va; 1278 struct amdgpu_device *adev = entry->adev; 1279 int ret; 1280 1281 ret = kfd_mem_dmamap_attachment(mem, entry); 1282 if (ret) 1283 return ret; 1284 1285 /* Update the page tables */ 1286 ret = amdgpu_vm_bo_update(adev, bo_va, false); 1287 if (ret) { 1288 pr_err("amdgpu_vm_bo_update failed\n"); 1289 return ret; 1290 } 1291 1292 return amdgpu_sync_fence(sync, bo_va->last_pt_update, GFP_KERNEL); 1293 } 1294 1295 static int map_bo_to_gpuvm(struct kgd_mem *mem, 1296 struct kfd_mem_attachment *entry, 1297 struct amdgpu_sync *sync, 1298 bool no_update_pte) 1299 { 1300 int ret; 1301 1302 /* Set virtual address for the allocation */ 1303 ret = amdgpu_vm_bo_map(entry->adev, entry->bo_va, entry->va, 0, 1304 amdgpu_bo_size(entry->bo_va->base.bo), 1305 entry->pte_flags); 1306 if (ret) { 1307 pr_err("Failed to map VA 0x%llx in vm. ret %d\n", 1308 entry->va, ret); 1309 return ret; 1310 } 1311 1312 if (no_update_pte) 1313 return 0; 1314 1315 ret = update_gpuvm_pte(mem, entry, sync); 1316 if (ret) { 1317 pr_err("update_gpuvm_pte() failed\n"); 1318 goto update_gpuvm_pte_failed; 1319 } 1320 1321 return 0; 1322 1323 update_gpuvm_pte_failed: 1324 unmap_bo_from_gpuvm(mem, entry, sync); 1325 kfd_mem_dmaunmap_attachment(mem, entry); 1326 return ret; 1327 } 1328 1329 static int process_validate_vms(struct amdkfd_process_info *process_info, 1330 struct ww_acquire_ctx *ticket) 1331 { 1332 struct amdgpu_vm *peer_vm; 1333 int ret; 1334 1335 list_for_each_entry(peer_vm, &process_info->vm_list_head, 1336 vm_list_node) { 1337 ret = vm_validate_pt_pd_bos(peer_vm, ticket); 1338 if (ret) 1339 return ret; 1340 } 1341 1342 return 0; 1343 } 1344 1345 static int process_sync_pds_resv(struct amdkfd_process_info *process_info, 1346 struct amdgpu_sync *sync) 1347 { 1348 struct amdgpu_vm *peer_vm; 1349 int ret; 1350 1351 list_for_each_entry(peer_vm, &process_info->vm_list_head, 1352 vm_list_node) { 1353 struct amdgpu_bo *pd = peer_vm->root.bo; 1354 1355 ret = amdgpu_sync_resv(NULL, sync, pd->tbo.base.resv, 1356 AMDGPU_SYNC_NE_OWNER, 1357 AMDGPU_FENCE_OWNER_KFD); 1358 if (ret) 1359 return ret; 1360 } 1361 1362 return 0; 1363 } 1364 1365 static int process_update_pds(struct amdkfd_process_info *process_info, 1366 struct amdgpu_sync *sync) 1367 { 1368 struct amdgpu_vm *peer_vm; 1369 int ret; 1370 1371 list_for_each_entry(peer_vm, &process_info->vm_list_head, 1372 vm_list_node) { 1373 ret = vm_update_pds(peer_vm, sync); 1374 if (ret) 1375 return ret; 1376 } 1377 1378 return 0; 1379 } 1380 1381 static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info, 1382 struct dma_fence **ef) 1383 { 1384 struct amdkfd_process_info *info = NULL; 1385 int ret; 1386 1387 if (!*process_info) { 1388 info = kzalloc(sizeof(*info), GFP_KERNEL); 1389 if (!info) 1390 return -ENOMEM; 1391 1392 mutex_init(&info->lock); 1393 mutex_init(&info->notifier_lock); 1394 INIT_LIST_HEAD(&info->vm_list_head); 1395 INIT_LIST_HEAD(&info->kfd_bo_list); 1396 INIT_LIST_HEAD(&info->userptr_valid_list); 1397 INIT_LIST_HEAD(&info->userptr_inval_list); 1398 1399 info->eviction_fence = 1400 amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1), 1401 current->mm, 1402 NULL); 1403 if (!info->eviction_fence) { 1404 pr_err("Failed to create eviction fence\n"); 1405 ret = -ENOMEM; 1406 goto create_evict_fence_fail; 1407 } 1408 1409 info->pid = get_task_pid(current->group_leader, PIDTYPE_PID); 1410 INIT_DELAYED_WORK(&info->restore_userptr_work, 1411 amdgpu_amdkfd_restore_userptr_worker); 1412 1413 *process_info = info; 1414 } 1415 1416 vm->process_info = *process_info; 1417 1418 /* Validate page directory and attach eviction fence */ 1419 ret = amdgpu_bo_reserve(vm->root.bo, true); 1420 if (ret) 1421 goto reserve_pd_fail; 1422 ret = vm_validate_pt_pd_bos(vm, NULL); 1423 if (ret) { 1424 pr_err("validate_pt_pd_bos() failed\n"); 1425 goto validate_pd_fail; 1426 } 1427 ret = amdgpu_bo_sync_wait(vm->root.bo, 1428 AMDGPU_FENCE_OWNER_KFD, false); 1429 if (ret) 1430 goto wait_pd_fail; 1431 ret = dma_resv_reserve_fences(vm->root.bo->tbo.base.resv, 1); 1432 if (ret) 1433 goto reserve_shared_fail; 1434 dma_resv_add_fence(vm->root.bo->tbo.base.resv, 1435 &vm->process_info->eviction_fence->base, 1436 DMA_RESV_USAGE_BOOKKEEP); 1437 amdgpu_bo_unreserve(vm->root.bo); 1438 1439 /* Update process info */ 1440 mutex_lock(&vm->process_info->lock); 1441 list_add_tail(&vm->vm_list_node, 1442 &(vm->process_info->vm_list_head)); 1443 vm->process_info->n_vms++; 1444 if (ef) 1445 *ef = dma_fence_get(&vm->process_info->eviction_fence->base); 1446 mutex_unlock(&vm->process_info->lock); 1447 1448 return 0; 1449 1450 reserve_shared_fail: 1451 wait_pd_fail: 1452 validate_pd_fail: 1453 amdgpu_bo_unreserve(vm->root.bo); 1454 reserve_pd_fail: 1455 vm->process_info = NULL; 1456 if (info) { 1457 dma_fence_put(&info->eviction_fence->base); 1458 *process_info = NULL; 1459 put_pid(info->pid); 1460 create_evict_fence_fail: 1461 mutex_destroy(&info->lock); 1462 mutex_destroy(&info->notifier_lock); 1463 kfree(info); 1464 } 1465 return ret; 1466 } 1467 1468 /** 1469 * amdgpu_amdkfd_gpuvm_pin_bo() - Pins a BO using following criteria 1470 * @bo: Handle of buffer object being pinned 1471 * @domain: Domain into which BO should be pinned 1472 * 1473 * - USERPTR BOs are UNPINNABLE and will return error 1474 * - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their 1475 * PIN count incremented. It is valid to PIN a BO multiple times 1476 * 1477 * Return: ZERO if successful in pinning, Non-Zero in case of error. 1478 */ 1479 static int amdgpu_amdkfd_gpuvm_pin_bo(struct amdgpu_bo *bo, u32 domain) 1480 { 1481 int ret = 0; 1482 1483 ret = amdgpu_bo_reserve(bo, false); 1484 if (unlikely(ret)) 1485 return ret; 1486 1487 if (bo->flags & AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS) { 1488 /* 1489 * If bo is not contiguous on VRAM, move to system memory first to ensure 1490 * we can get contiguous VRAM space after evicting other BOs. 1491 */ 1492 if (!(bo->tbo.resource->placement & TTM_PL_FLAG_CONTIGUOUS)) { 1493 struct ttm_operation_ctx ctx = { true, false }; 1494 1495 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_GTT); 1496 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 1497 if (unlikely(ret)) { 1498 pr_debug("validate bo 0x%p to GTT failed %d\n", &bo->tbo, ret); 1499 goto out; 1500 } 1501 } 1502 } 1503 1504 ret = amdgpu_bo_pin(bo, domain); 1505 if (ret) 1506 pr_err("Error in Pinning BO to domain: %d\n", domain); 1507 1508 amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false); 1509 out: 1510 amdgpu_bo_unreserve(bo); 1511 return ret; 1512 } 1513 1514 /** 1515 * amdgpu_amdkfd_gpuvm_unpin_bo() - Unpins BO using following criteria 1516 * @bo: Handle of buffer object being unpinned 1517 * 1518 * - Is a illegal request for USERPTR BOs and is ignored 1519 * - All other BO types (GTT, VRAM, MMIO and DOORBELL) will have their 1520 * PIN count decremented. Calls to UNPIN must balance calls to PIN 1521 */ 1522 static void amdgpu_amdkfd_gpuvm_unpin_bo(struct amdgpu_bo *bo) 1523 { 1524 int ret = 0; 1525 1526 ret = amdgpu_bo_reserve(bo, false); 1527 if (unlikely(ret)) 1528 return; 1529 1530 amdgpu_bo_unpin(bo); 1531 amdgpu_bo_unreserve(bo); 1532 } 1533 1534 int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct amdgpu_device *adev, 1535 struct amdgpu_vm *avm, 1536 void **process_info, 1537 struct dma_fence **ef) 1538 { 1539 int ret; 1540 1541 /* Already a compute VM? */ 1542 if (avm->process_info) 1543 return -EINVAL; 1544 1545 /* Convert VM into a compute VM */ 1546 ret = amdgpu_vm_make_compute(adev, avm); 1547 if (ret) 1548 return ret; 1549 1550 /* Initialize KFD part of the VM and process info */ 1551 ret = init_kfd_vm(avm, process_info, ef); 1552 if (ret) 1553 return ret; 1554 1555 amdgpu_vm_set_task_info(avm); 1556 1557 return 0; 1558 } 1559 1560 void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev, 1561 struct amdgpu_vm *vm) 1562 { 1563 struct amdkfd_process_info *process_info = vm->process_info; 1564 1565 if (!process_info) 1566 return; 1567 1568 /* Update process info */ 1569 mutex_lock(&process_info->lock); 1570 process_info->n_vms--; 1571 list_del(&vm->vm_list_node); 1572 mutex_unlock(&process_info->lock); 1573 1574 vm->process_info = NULL; 1575 1576 /* Release per-process resources when last compute VM is destroyed */ 1577 if (!process_info->n_vms) { 1578 WARN_ON(!list_empty(&process_info->kfd_bo_list)); 1579 WARN_ON(!list_empty(&process_info->userptr_valid_list)); 1580 WARN_ON(!list_empty(&process_info->userptr_inval_list)); 1581 1582 dma_fence_put(&process_info->eviction_fence->base); 1583 cancel_delayed_work_sync(&process_info->restore_userptr_work); 1584 put_pid(process_info->pid); 1585 mutex_destroy(&process_info->lock); 1586 mutex_destroy(&process_info->notifier_lock); 1587 kfree(process_info); 1588 } 1589 } 1590 1591 uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *drm_priv) 1592 { 1593 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv); 1594 struct amdgpu_bo *pd = avm->root.bo; 1595 struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev); 1596 1597 if (adev->asic_type < CHIP_VEGA10) 1598 return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT; 1599 return avm->pd_phys_addr; 1600 } 1601 1602 void amdgpu_amdkfd_block_mmu_notifications(void *p) 1603 { 1604 struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p; 1605 1606 mutex_lock(&pinfo->lock); 1607 WRITE_ONCE(pinfo->block_mmu_notifications, true); 1608 mutex_unlock(&pinfo->lock); 1609 } 1610 1611 int amdgpu_amdkfd_criu_resume(void *p) 1612 { 1613 int ret = 0; 1614 struct amdkfd_process_info *pinfo = (struct amdkfd_process_info *)p; 1615 1616 mutex_lock(&pinfo->lock); 1617 pr_debug("scheduling work\n"); 1618 mutex_lock(&pinfo->notifier_lock); 1619 pinfo->evicted_bos++; 1620 mutex_unlock(&pinfo->notifier_lock); 1621 if (!READ_ONCE(pinfo->block_mmu_notifications)) { 1622 ret = -EINVAL; 1623 goto out_unlock; 1624 } 1625 WRITE_ONCE(pinfo->block_mmu_notifications, false); 1626 queue_delayed_work(system_freezable_wq, 1627 &pinfo->restore_userptr_work, 0); 1628 1629 out_unlock: 1630 mutex_unlock(&pinfo->lock); 1631 return ret; 1632 } 1633 1634 size_t amdgpu_amdkfd_get_available_memory(struct amdgpu_device *adev, 1635 uint8_t xcp_id) 1636 { 1637 uint64_t reserved_for_pt = 1638 ESTIMATE_PT_SIZE(amdgpu_amdkfd_total_mem_size); 1639 struct amdgpu_ras *con = amdgpu_ras_get_context(adev); 1640 uint64_t reserved_for_ras = (con ? con->reserved_pages_in_bytes : 0); 1641 ssize_t available; 1642 uint64_t vram_available, system_mem_available, ttm_mem_available; 1643 1644 spin_lock(&kfd_mem_limit.mem_limit_lock); 1645 if (adev->apu_prefer_gtt && !adev->gmc.is_app_apu) 1646 vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id) 1647 - adev->kfd.vram_used_aligned[xcp_id]; 1648 else 1649 vram_available = KFD_XCP_MEMORY_SIZE(adev, xcp_id) 1650 - adev->kfd.vram_used_aligned[xcp_id] 1651 - atomic64_read(&adev->vram_pin_size) 1652 - reserved_for_pt 1653 - reserved_for_ras; 1654 1655 if (adev->apu_prefer_gtt) { 1656 system_mem_available = no_system_mem_limit ? 1657 kfd_mem_limit.max_system_mem_limit : 1658 kfd_mem_limit.max_system_mem_limit - 1659 kfd_mem_limit.system_mem_used; 1660 1661 ttm_mem_available = kfd_mem_limit.max_ttm_mem_limit - 1662 kfd_mem_limit.ttm_mem_used; 1663 1664 available = min3(system_mem_available, ttm_mem_available, 1665 vram_available); 1666 available = ALIGN_DOWN(available, PAGE_SIZE); 1667 } else { 1668 available = ALIGN_DOWN(vram_available, VRAM_AVAILABLITY_ALIGN); 1669 } 1670 1671 spin_unlock(&kfd_mem_limit.mem_limit_lock); 1672 1673 if (available < 0) 1674 available = 0; 1675 1676 return available; 1677 } 1678 1679 int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu( 1680 struct amdgpu_device *adev, uint64_t va, uint64_t size, 1681 void *drm_priv, struct kgd_mem **mem, 1682 uint64_t *offset, uint32_t flags, bool criu_resume) 1683 { 1684 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv); 1685 struct amdgpu_fpriv *fpriv = container_of(avm, struct amdgpu_fpriv, vm); 1686 enum ttm_bo_type bo_type = ttm_bo_type_device; 1687 struct sg_table *sg = NULL; 1688 uint64_t user_addr = 0; 1689 struct amdgpu_bo *bo; 1690 struct drm_gem_object *gobj = NULL; 1691 u32 domain, alloc_domain; 1692 uint64_t aligned_size; 1693 int8_t xcp_id = -1; 1694 u64 alloc_flags; 1695 int ret; 1696 1697 /* 1698 * Check on which domain to allocate BO 1699 */ 1700 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_VRAM) { 1701 domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM; 1702 1703 if (adev->apu_prefer_gtt) { 1704 domain = AMDGPU_GEM_DOMAIN_GTT; 1705 alloc_domain = AMDGPU_GEM_DOMAIN_GTT; 1706 alloc_flags = 0; 1707 } else { 1708 alloc_flags = AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE; 1709 alloc_flags |= (flags & KFD_IOC_ALLOC_MEM_FLAGS_PUBLIC) ? 1710 AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED : 0; 1711 1712 /* For contiguous VRAM allocation */ 1713 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_CONTIGUOUS) 1714 alloc_flags |= AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS; 1715 } 1716 xcp_id = fpriv->xcp_id == AMDGPU_XCP_NO_PARTITION ? 1717 0 : fpriv->xcp_id; 1718 } else if (flags & KFD_IOC_ALLOC_MEM_FLAGS_GTT) { 1719 domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT; 1720 alloc_flags = 0; 1721 } else { 1722 domain = AMDGPU_GEM_DOMAIN_GTT; 1723 alloc_domain = AMDGPU_GEM_DOMAIN_CPU; 1724 alloc_flags = AMDGPU_GEM_CREATE_PREEMPTIBLE; 1725 1726 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_USERPTR) { 1727 if (!offset || !*offset) 1728 return -EINVAL; 1729 user_addr = untagged_addr(*offset); 1730 } else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL | 1731 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) { 1732 bo_type = ttm_bo_type_sg; 1733 if (size > UINT_MAX) 1734 return -EINVAL; 1735 sg = create_sg_table(*offset, size); 1736 if (!sg) 1737 return -ENOMEM; 1738 } else { 1739 return -EINVAL; 1740 } 1741 } 1742 1743 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_COHERENT) 1744 alloc_flags |= AMDGPU_GEM_CREATE_COHERENT; 1745 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_EXT_COHERENT) 1746 alloc_flags |= AMDGPU_GEM_CREATE_EXT_COHERENT; 1747 if (flags & KFD_IOC_ALLOC_MEM_FLAGS_UNCACHED) 1748 alloc_flags |= AMDGPU_GEM_CREATE_UNCACHED; 1749 1750 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL); 1751 if (!*mem) { 1752 ret = -ENOMEM; 1753 goto err; 1754 } 1755 INIT_LIST_HEAD(&(*mem)->attachments); 1756 mutex_init(&(*mem)->lock); 1757 (*mem)->aql_queue = !!(flags & KFD_IOC_ALLOC_MEM_FLAGS_AQL_QUEUE_MEM); 1758 1759 /* Workaround for AQL queue wraparound bug. Map the same 1760 * memory twice. That means we only actually allocate half 1761 * the memory. 1762 */ 1763 if ((*mem)->aql_queue) 1764 size >>= 1; 1765 aligned_size = PAGE_ALIGN(size); 1766 1767 (*mem)->alloc_flags = flags; 1768 1769 amdgpu_sync_create(&(*mem)->sync); 1770 1771 ret = amdgpu_amdkfd_reserve_mem_limit(adev, aligned_size, flags, 1772 xcp_id); 1773 if (ret) { 1774 pr_debug("Insufficient memory\n"); 1775 goto err_reserve_limit; 1776 } 1777 1778 pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s xcp_id %d\n", 1779 va, (*mem)->aql_queue ? size << 1 : size, 1780 domain_string(alloc_domain), xcp_id); 1781 1782 ret = amdgpu_gem_object_create(adev, aligned_size, 1, alloc_domain, alloc_flags, 1783 bo_type, NULL, &gobj, xcp_id + 1); 1784 if (ret) { 1785 pr_debug("Failed to create BO on domain %s. ret %d\n", 1786 domain_string(alloc_domain), ret); 1787 goto err_bo_create; 1788 } 1789 ret = drm_vma_node_allow(&gobj->vma_node, drm_priv); 1790 if (ret) { 1791 pr_debug("Failed to allow vma node access. ret %d\n", ret); 1792 goto err_node_allow; 1793 } 1794 ret = drm_gem_handle_create(adev->kfd.client.file, gobj, &(*mem)->gem_handle); 1795 if (ret) 1796 goto err_gem_handle_create; 1797 bo = gem_to_amdgpu_bo(gobj); 1798 if (bo_type == ttm_bo_type_sg) { 1799 bo->tbo.sg = sg; 1800 bo->tbo.ttm->sg = sg; 1801 } 1802 bo->kfd_bo = *mem; 1803 (*mem)->bo = bo; 1804 if (user_addr) 1805 bo->flags |= AMDGPU_AMDKFD_CREATE_USERPTR_BO; 1806 1807 (*mem)->va = va; 1808 (*mem)->domain = domain; 1809 (*mem)->mapped_to_gpu_memory = 0; 1810 (*mem)->process_info = avm->process_info; 1811 1812 add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr); 1813 1814 if (user_addr) { 1815 pr_debug("creating userptr BO for user_addr = %llx\n", user_addr); 1816 ret = init_user_pages(*mem, user_addr, criu_resume); 1817 if (ret) 1818 goto allocate_init_user_pages_failed; 1819 } else if (flags & (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL | 1820 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) { 1821 ret = amdgpu_amdkfd_gpuvm_pin_bo(bo, AMDGPU_GEM_DOMAIN_GTT); 1822 if (ret) { 1823 pr_err("Pinning MMIO/DOORBELL BO during ALLOC FAILED\n"); 1824 goto err_pin_bo; 1825 } 1826 bo->allowed_domains = AMDGPU_GEM_DOMAIN_GTT; 1827 bo->preferred_domains = AMDGPU_GEM_DOMAIN_GTT; 1828 } else { 1829 mutex_lock(&avm->process_info->lock); 1830 if (avm->process_info->eviction_fence && 1831 !dma_fence_is_signaled(&avm->process_info->eviction_fence->base)) 1832 ret = amdgpu_amdkfd_bo_validate_and_fence(bo, domain, 1833 &avm->process_info->eviction_fence->base); 1834 mutex_unlock(&avm->process_info->lock); 1835 if (ret) 1836 goto err_validate_bo; 1837 } 1838 1839 if (offset) 1840 *offset = amdgpu_bo_mmap_offset(bo); 1841 1842 return 0; 1843 1844 allocate_init_user_pages_failed: 1845 err_pin_bo: 1846 err_validate_bo: 1847 remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info); 1848 drm_gem_handle_delete(adev->kfd.client.file, (*mem)->gem_handle); 1849 err_gem_handle_create: 1850 drm_vma_node_revoke(&gobj->vma_node, drm_priv); 1851 err_node_allow: 1852 /* Don't unreserve system mem limit twice */ 1853 goto err_reserve_limit; 1854 err_bo_create: 1855 amdgpu_amdkfd_unreserve_mem_limit(adev, aligned_size, flags, xcp_id); 1856 err_reserve_limit: 1857 amdgpu_sync_free(&(*mem)->sync); 1858 mutex_destroy(&(*mem)->lock); 1859 if (gobj) 1860 drm_gem_object_put(gobj); 1861 else 1862 kfree(*mem); 1863 err: 1864 if (sg) { 1865 sg_free_table(sg); 1866 kfree(sg); 1867 } 1868 return ret; 1869 } 1870 1871 int amdgpu_amdkfd_gpuvm_free_memory_of_gpu( 1872 struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv, 1873 uint64_t *size) 1874 { 1875 struct amdkfd_process_info *process_info = mem->process_info; 1876 unsigned long bo_size = mem->bo->tbo.base.size; 1877 bool use_release_notifier = (mem->bo->kfd_bo == mem); 1878 struct kfd_mem_attachment *entry, *tmp; 1879 struct bo_vm_reservation_context ctx; 1880 unsigned int mapped_to_gpu_memory; 1881 int ret; 1882 bool is_imported = false; 1883 1884 mutex_lock(&mem->lock); 1885 1886 /* Unpin MMIO/DOORBELL BO's that were pinned during allocation */ 1887 if (mem->alloc_flags & 1888 (KFD_IOC_ALLOC_MEM_FLAGS_DOORBELL | 1889 KFD_IOC_ALLOC_MEM_FLAGS_MMIO_REMAP)) { 1890 amdgpu_amdkfd_gpuvm_unpin_bo(mem->bo); 1891 } 1892 1893 mapped_to_gpu_memory = mem->mapped_to_gpu_memory; 1894 is_imported = mem->is_imported; 1895 mutex_unlock(&mem->lock); 1896 /* lock is not needed after this, since mem is unused and will 1897 * be freed anyway 1898 */ 1899 1900 if (mapped_to_gpu_memory > 0) { 1901 pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n", 1902 mem->va, bo_size); 1903 return -EBUSY; 1904 } 1905 1906 /* Make sure restore workers don't access the BO any more */ 1907 mutex_lock(&process_info->lock); 1908 list_del(&mem->validate_list); 1909 mutex_unlock(&process_info->lock); 1910 1911 /* Cleanup user pages and MMU notifiers */ 1912 if (amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm)) { 1913 amdgpu_hmm_unregister(mem->bo); 1914 mutex_lock(&process_info->notifier_lock); 1915 amdgpu_ttm_tt_discard_user_pages(mem->bo->tbo.ttm, mem->range); 1916 mutex_unlock(&process_info->notifier_lock); 1917 } 1918 1919 ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx); 1920 if (unlikely(ret)) 1921 return ret; 1922 1923 amdgpu_amdkfd_remove_eviction_fence(mem->bo, 1924 process_info->eviction_fence); 1925 pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va, 1926 mem->va + bo_size * (1 + mem->aql_queue)); 1927 1928 /* Remove from VM internal data structures */ 1929 list_for_each_entry_safe(entry, tmp, &mem->attachments, list) { 1930 kfd_mem_dmaunmap_attachment(mem, entry); 1931 kfd_mem_detach(entry); 1932 } 1933 1934 ret = unreserve_bo_and_vms(&ctx, false, false); 1935 1936 /* Free the sync object */ 1937 amdgpu_sync_free(&mem->sync); 1938 1939 /* If the SG is not NULL, it's one we created for a doorbell or mmio 1940 * remap BO. We need to free it. 1941 */ 1942 if (mem->bo->tbo.sg) { 1943 sg_free_table(mem->bo->tbo.sg); 1944 kfree(mem->bo->tbo.sg); 1945 } 1946 1947 /* Update the size of the BO being freed if it was allocated from 1948 * VRAM and is not imported. For APP APU VRAM allocations are done 1949 * in GTT domain 1950 */ 1951 if (size) { 1952 if (!is_imported && 1953 (mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_VRAM || 1954 (adev->apu_prefer_gtt && 1955 mem->bo->preferred_domains == AMDGPU_GEM_DOMAIN_GTT))) 1956 *size = bo_size; 1957 else 1958 *size = 0; 1959 } 1960 1961 /* Free the BO*/ 1962 drm_vma_node_revoke(&mem->bo->tbo.base.vma_node, drm_priv); 1963 drm_gem_handle_delete(adev->kfd.client.file, mem->gem_handle); 1964 if (mem->dmabuf) { 1965 dma_buf_put(mem->dmabuf); 1966 mem->dmabuf = NULL; 1967 } 1968 mutex_destroy(&mem->lock); 1969 1970 /* If this releases the last reference, it will end up calling 1971 * amdgpu_amdkfd_release_notify and kfree the mem struct. That's why 1972 * this needs to be the last call here. 1973 */ 1974 drm_gem_object_put(&mem->bo->tbo.base); 1975 1976 /* 1977 * For kgd_mem allocated in amdgpu_amdkfd_gpuvm_import_dmabuf(), 1978 * explicitly free it here. 1979 */ 1980 if (!use_release_notifier) 1981 kfree(mem); 1982 1983 return ret; 1984 } 1985 1986 int amdgpu_amdkfd_gpuvm_map_memory_to_gpu( 1987 struct amdgpu_device *adev, struct kgd_mem *mem, 1988 void *drm_priv) 1989 { 1990 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv); 1991 int ret; 1992 struct amdgpu_bo *bo; 1993 uint32_t domain; 1994 struct kfd_mem_attachment *entry; 1995 struct bo_vm_reservation_context ctx; 1996 unsigned long bo_size; 1997 bool is_invalid_userptr = false; 1998 1999 bo = mem->bo; 2000 if (!bo) { 2001 pr_err("Invalid BO when mapping memory to GPU\n"); 2002 return -EINVAL; 2003 } 2004 2005 /* Make sure restore is not running concurrently. Since we 2006 * don't map invalid userptr BOs, we rely on the next restore 2007 * worker to do the mapping 2008 */ 2009 mutex_lock(&mem->process_info->lock); 2010 2011 /* Lock notifier lock. If we find an invalid userptr BO, we can be 2012 * sure that the MMU notifier is no longer running 2013 * concurrently and the queues are actually stopped 2014 */ 2015 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) { 2016 mutex_lock(&mem->process_info->notifier_lock); 2017 is_invalid_userptr = !!mem->invalid; 2018 mutex_unlock(&mem->process_info->notifier_lock); 2019 } 2020 2021 mutex_lock(&mem->lock); 2022 2023 domain = mem->domain; 2024 bo_size = bo->tbo.base.size; 2025 2026 pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n", 2027 mem->va, 2028 mem->va + bo_size * (1 + mem->aql_queue), 2029 avm, domain_string(domain)); 2030 2031 if (!kfd_mem_is_attached(avm, mem)) { 2032 ret = kfd_mem_attach(adev, mem, avm, mem->aql_queue); 2033 if (ret) 2034 goto out; 2035 } 2036 2037 ret = reserve_bo_and_vm(mem, avm, &ctx); 2038 if (unlikely(ret)) 2039 goto out; 2040 2041 /* Userptr can be marked as "not invalid", but not actually be 2042 * validated yet (still in the system domain). In that case 2043 * the queues are still stopped and we can leave mapping for 2044 * the next restore worker 2045 */ 2046 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) && 2047 bo->tbo.resource->mem_type == TTM_PL_SYSTEM) 2048 is_invalid_userptr = true; 2049 2050 ret = vm_validate_pt_pd_bos(avm, NULL); 2051 if (unlikely(ret)) 2052 goto out_unreserve; 2053 2054 list_for_each_entry(entry, &mem->attachments, list) { 2055 if (entry->bo_va->base.vm != avm || entry->is_mapped) 2056 continue; 2057 2058 pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n", 2059 entry->va, entry->va + bo_size, entry); 2060 2061 ret = map_bo_to_gpuvm(mem, entry, ctx.sync, 2062 is_invalid_userptr); 2063 if (ret) { 2064 pr_err("Failed to map bo to gpuvm\n"); 2065 goto out_unreserve; 2066 } 2067 2068 ret = vm_update_pds(avm, ctx.sync); 2069 if (ret) { 2070 pr_err("Failed to update page directories\n"); 2071 goto out_unreserve; 2072 } 2073 2074 entry->is_mapped = true; 2075 mem->mapped_to_gpu_memory++; 2076 pr_debug("\t INC mapping count %d\n", 2077 mem->mapped_to_gpu_memory); 2078 } 2079 2080 ret = unreserve_bo_and_vms(&ctx, false, false); 2081 2082 goto out; 2083 2084 out_unreserve: 2085 unreserve_bo_and_vms(&ctx, false, false); 2086 out: 2087 mutex_unlock(&mem->process_info->lock); 2088 mutex_unlock(&mem->lock); 2089 return ret; 2090 } 2091 2092 int amdgpu_amdkfd_gpuvm_dmaunmap_mem(struct kgd_mem *mem, void *drm_priv) 2093 { 2094 struct kfd_mem_attachment *entry; 2095 struct amdgpu_vm *vm; 2096 int ret; 2097 2098 vm = drm_priv_to_vm(drm_priv); 2099 2100 mutex_lock(&mem->lock); 2101 2102 ret = amdgpu_bo_reserve(mem->bo, true); 2103 if (ret) 2104 goto out; 2105 2106 list_for_each_entry(entry, &mem->attachments, list) { 2107 if (entry->bo_va->base.vm != vm) 2108 continue; 2109 if (entry->bo_va->base.bo->tbo.ttm && 2110 !entry->bo_va->base.bo->tbo.ttm->sg) 2111 continue; 2112 2113 kfd_mem_dmaunmap_attachment(mem, entry); 2114 } 2115 2116 amdgpu_bo_unreserve(mem->bo); 2117 out: 2118 mutex_unlock(&mem->lock); 2119 2120 return ret; 2121 } 2122 2123 int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu( 2124 struct amdgpu_device *adev, struct kgd_mem *mem, void *drm_priv) 2125 { 2126 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv); 2127 unsigned long bo_size = mem->bo->tbo.base.size; 2128 struct kfd_mem_attachment *entry; 2129 struct bo_vm_reservation_context ctx; 2130 int ret; 2131 2132 mutex_lock(&mem->lock); 2133 2134 ret = reserve_bo_and_cond_vms(mem, avm, BO_VM_MAPPED, &ctx); 2135 if (unlikely(ret)) 2136 goto out; 2137 /* If no VMs were reserved, it means the BO wasn't actually mapped */ 2138 if (ctx.n_vms == 0) { 2139 ret = -EINVAL; 2140 goto unreserve_out; 2141 } 2142 2143 ret = vm_validate_pt_pd_bos(avm, NULL); 2144 if (unlikely(ret)) 2145 goto unreserve_out; 2146 2147 pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n", 2148 mem->va, 2149 mem->va + bo_size * (1 + mem->aql_queue), 2150 avm); 2151 2152 list_for_each_entry(entry, &mem->attachments, list) { 2153 if (entry->bo_va->base.vm != avm || !entry->is_mapped) 2154 continue; 2155 2156 pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n", 2157 entry->va, entry->va + bo_size, entry); 2158 2159 ret = unmap_bo_from_gpuvm(mem, entry, ctx.sync); 2160 if (ret) 2161 goto unreserve_out; 2162 2163 entry->is_mapped = false; 2164 2165 mem->mapped_to_gpu_memory--; 2166 pr_debug("\t DEC mapping count %d\n", 2167 mem->mapped_to_gpu_memory); 2168 } 2169 2170 unreserve_out: 2171 unreserve_bo_and_vms(&ctx, false, false); 2172 out: 2173 mutex_unlock(&mem->lock); 2174 return ret; 2175 } 2176 2177 int amdgpu_amdkfd_gpuvm_sync_memory( 2178 struct amdgpu_device *adev, struct kgd_mem *mem, bool intr) 2179 { 2180 struct amdgpu_sync sync; 2181 int ret; 2182 2183 amdgpu_sync_create(&sync); 2184 2185 mutex_lock(&mem->lock); 2186 amdgpu_sync_clone(&mem->sync, &sync); 2187 mutex_unlock(&mem->lock); 2188 2189 ret = amdgpu_sync_wait(&sync, intr); 2190 amdgpu_sync_free(&sync); 2191 return ret; 2192 } 2193 2194 /** 2195 * amdgpu_amdkfd_map_gtt_bo_to_gart - Map BO to GART and increment reference count 2196 * @bo: Buffer object to be mapped 2197 * @bo_gart: Return bo reference 2198 * 2199 * Before return, bo reference count is incremented. To release the reference and unpin/ 2200 * unmap the BO, call amdgpu_amdkfd_free_gtt_mem. 2201 */ 2202 int amdgpu_amdkfd_map_gtt_bo_to_gart(struct amdgpu_bo *bo, struct amdgpu_bo **bo_gart) 2203 { 2204 int ret; 2205 2206 ret = amdgpu_bo_reserve(bo, true); 2207 if (ret) { 2208 pr_err("Failed to reserve bo. ret %d\n", ret); 2209 goto err_reserve_bo_failed; 2210 } 2211 2212 ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT); 2213 if (ret) { 2214 pr_err("Failed to pin bo. ret %d\n", ret); 2215 goto err_pin_bo_failed; 2216 } 2217 2218 ret = amdgpu_ttm_alloc_gart(&bo->tbo); 2219 if (ret) { 2220 pr_err("Failed to bind bo to GART. ret %d\n", ret); 2221 goto err_map_bo_gart_failed; 2222 } 2223 2224 amdgpu_amdkfd_remove_eviction_fence( 2225 bo, bo->vm_bo->vm->process_info->eviction_fence); 2226 2227 amdgpu_bo_unreserve(bo); 2228 2229 *bo_gart = amdgpu_bo_ref(bo); 2230 2231 return 0; 2232 2233 err_map_bo_gart_failed: 2234 amdgpu_bo_unpin(bo); 2235 err_pin_bo_failed: 2236 amdgpu_bo_unreserve(bo); 2237 err_reserve_bo_failed: 2238 2239 return ret; 2240 } 2241 2242 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Map a GTT BO for kernel CPU access 2243 * 2244 * @mem: Buffer object to be mapped for CPU access 2245 * @kptr[out]: pointer in kernel CPU address space 2246 * @size[out]: size of the buffer 2247 * 2248 * Pins the BO and maps it for kernel CPU access. The eviction fence is removed 2249 * from the BO, since pinned BOs cannot be evicted. The bo must remain on the 2250 * validate_list, so the GPU mapping can be restored after a page table was 2251 * evicted. 2252 * 2253 * Return: 0 on success, error code on failure 2254 */ 2255 int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_mem *mem, 2256 void **kptr, uint64_t *size) 2257 { 2258 int ret; 2259 struct amdgpu_bo *bo = mem->bo; 2260 2261 if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) { 2262 pr_err("userptr can't be mapped to kernel\n"); 2263 return -EINVAL; 2264 } 2265 2266 mutex_lock(&mem->process_info->lock); 2267 2268 ret = amdgpu_bo_reserve(bo, true); 2269 if (ret) { 2270 pr_err("Failed to reserve bo. ret %d\n", ret); 2271 goto bo_reserve_failed; 2272 } 2273 2274 ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT); 2275 if (ret) { 2276 pr_err("Failed to pin bo. ret %d\n", ret); 2277 goto pin_failed; 2278 } 2279 2280 ret = amdgpu_bo_kmap(bo, kptr); 2281 if (ret) { 2282 pr_err("Failed to map bo to kernel. ret %d\n", ret); 2283 goto kmap_failed; 2284 } 2285 2286 amdgpu_amdkfd_remove_eviction_fence( 2287 bo, mem->process_info->eviction_fence); 2288 2289 if (size) 2290 *size = amdgpu_bo_size(bo); 2291 2292 amdgpu_bo_unreserve(bo); 2293 2294 mutex_unlock(&mem->process_info->lock); 2295 return 0; 2296 2297 kmap_failed: 2298 amdgpu_bo_unpin(bo); 2299 pin_failed: 2300 amdgpu_bo_unreserve(bo); 2301 bo_reserve_failed: 2302 mutex_unlock(&mem->process_info->lock); 2303 2304 return ret; 2305 } 2306 2307 /** amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel() - Unmap a GTT BO for kernel CPU access 2308 * 2309 * @mem: Buffer object to be unmapped for CPU access 2310 * 2311 * Removes the kernel CPU mapping and unpins the BO. It does not restore the 2312 * eviction fence, so this function should only be used for cleanup before the 2313 * BO is destroyed. 2314 */ 2315 void amdgpu_amdkfd_gpuvm_unmap_gtt_bo_from_kernel(struct kgd_mem *mem) 2316 { 2317 struct amdgpu_bo *bo = mem->bo; 2318 2319 (void)amdgpu_bo_reserve(bo, true); 2320 amdgpu_bo_kunmap(bo); 2321 amdgpu_bo_unpin(bo); 2322 amdgpu_bo_unreserve(bo); 2323 } 2324 2325 int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct amdgpu_device *adev, 2326 struct kfd_vm_fault_info *mem) 2327 { 2328 if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) { 2329 *mem = *adev->gmc.vm_fault_info; 2330 mb(); /* make sure read happened */ 2331 atomic_set(&adev->gmc.vm_fault_info_updated, 0); 2332 } 2333 return 0; 2334 } 2335 2336 static int import_obj_create(struct amdgpu_device *adev, 2337 struct dma_buf *dma_buf, 2338 struct drm_gem_object *obj, 2339 uint64_t va, void *drm_priv, 2340 struct kgd_mem **mem, uint64_t *size, 2341 uint64_t *mmap_offset) 2342 { 2343 struct amdgpu_vm *avm = drm_priv_to_vm(drm_priv); 2344 struct amdgpu_bo *bo; 2345 int ret; 2346 2347 bo = gem_to_amdgpu_bo(obj); 2348 if (!(bo->preferred_domains & (AMDGPU_GEM_DOMAIN_VRAM | 2349 AMDGPU_GEM_DOMAIN_GTT))) 2350 /* Only VRAM and GTT BOs are supported */ 2351 return -EINVAL; 2352 2353 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL); 2354 if (!*mem) 2355 return -ENOMEM; 2356 2357 ret = drm_vma_node_allow(&obj->vma_node, drm_priv); 2358 if (ret) 2359 goto err_free_mem; 2360 2361 if (size) 2362 *size = amdgpu_bo_size(bo); 2363 2364 if (mmap_offset) 2365 *mmap_offset = amdgpu_bo_mmap_offset(bo); 2366 2367 INIT_LIST_HEAD(&(*mem)->attachments); 2368 mutex_init(&(*mem)->lock); 2369 2370 (*mem)->alloc_flags = 2371 ((bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) ? 2372 KFD_IOC_ALLOC_MEM_FLAGS_VRAM : KFD_IOC_ALLOC_MEM_FLAGS_GTT) 2373 | KFD_IOC_ALLOC_MEM_FLAGS_WRITABLE 2374 | KFD_IOC_ALLOC_MEM_FLAGS_EXECUTABLE; 2375 2376 get_dma_buf(dma_buf); 2377 (*mem)->dmabuf = dma_buf; 2378 (*mem)->bo = bo; 2379 (*mem)->va = va; 2380 (*mem)->domain = (bo->preferred_domains & AMDGPU_GEM_DOMAIN_VRAM) && 2381 !adev->apu_prefer_gtt ? 2382 AMDGPU_GEM_DOMAIN_VRAM : AMDGPU_GEM_DOMAIN_GTT; 2383 2384 (*mem)->mapped_to_gpu_memory = 0; 2385 (*mem)->process_info = avm->process_info; 2386 add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, false); 2387 amdgpu_sync_create(&(*mem)->sync); 2388 (*mem)->is_imported = true; 2389 2390 mutex_lock(&avm->process_info->lock); 2391 if (avm->process_info->eviction_fence && 2392 !dma_fence_is_signaled(&avm->process_info->eviction_fence->base)) 2393 ret = amdgpu_amdkfd_bo_validate_and_fence(bo, (*mem)->domain, 2394 &avm->process_info->eviction_fence->base); 2395 mutex_unlock(&avm->process_info->lock); 2396 if (ret) 2397 goto err_remove_mem; 2398 2399 return 0; 2400 2401 err_remove_mem: 2402 remove_kgd_mem_from_kfd_bo_list(*mem, avm->process_info); 2403 drm_vma_node_revoke(&obj->vma_node, drm_priv); 2404 err_free_mem: 2405 kfree(*mem); 2406 return ret; 2407 } 2408 2409 int amdgpu_amdkfd_gpuvm_import_dmabuf_fd(struct amdgpu_device *adev, int fd, 2410 uint64_t va, void *drm_priv, 2411 struct kgd_mem **mem, uint64_t *size, 2412 uint64_t *mmap_offset) 2413 { 2414 struct drm_gem_object *obj; 2415 uint32_t handle; 2416 int ret; 2417 2418 ret = drm_gem_prime_fd_to_handle(&adev->ddev, adev->kfd.client.file, fd, 2419 &handle); 2420 if (ret) 2421 return ret; 2422 obj = drm_gem_object_lookup(adev->kfd.client.file, handle); 2423 if (!obj) { 2424 ret = -EINVAL; 2425 goto err_release_handle; 2426 } 2427 2428 ret = import_obj_create(adev, obj->dma_buf, obj, va, drm_priv, mem, size, 2429 mmap_offset); 2430 if (ret) 2431 goto err_put_obj; 2432 2433 (*mem)->gem_handle = handle; 2434 2435 return 0; 2436 2437 err_put_obj: 2438 drm_gem_object_put(obj); 2439 err_release_handle: 2440 drm_gem_handle_delete(adev->kfd.client.file, handle); 2441 return ret; 2442 } 2443 2444 int amdgpu_amdkfd_gpuvm_export_dmabuf(struct kgd_mem *mem, 2445 struct dma_buf **dma_buf) 2446 { 2447 int ret; 2448 2449 mutex_lock(&mem->lock); 2450 ret = kfd_mem_export_dmabuf(mem); 2451 if (ret) 2452 goto out; 2453 2454 get_dma_buf(mem->dmabuf); 2455 *dma_buf = mem->dmabuf; 2456 out: 2457 mutex_unlock(&mem->lock); 2458 return ret; 2459 } 2460 2461 /* Evict a userptr BO by stopping the queues if necessary 2462 * 2463 * Runs in MMU notifier, may be in RECLAIM_FS context. This means it 2464 * cannot do any memory allocations, and cannot take any locks that 2465 * are held elsewhere while allocating memory. 2466 * 2467 * It doesn't do anything to the BO itself. The real work happens in 2468 * restore, where we get updated page addresses. This function only 2469 * ensures that GPU access to the BO is stopped. 2470 */ 2471 int amdgpu_amdkfd_evict_userptr(struct mmu_interval_notifier *mni, 2472 unsigned long cur_seq, struct kgd_mem *mem) 2473 { 2474 struct amdkfd_process_info *process_info = mem->process_info; 2475 int r = 0; 2476 2477 /* Do not process MMU notifications during CRIU restore until 2478 * KFD_CRIU_OP_RESUME IOCTL is received 2479 */ 2480 if (READ_ONCE(process_info->block_mmu_notifications)) 2481 return 0; 2482 2483 mutex_lock(&process_info->notifier_lock); 2484 mmu_interval_set_seq(mni, cur_seq); 2485 2486 mem->invalid++; 2487 if (++process_info->evicted_bos == 1) { 2488 /* First eviction, stop the queues */ 2489 r = kgd2kfd_quiesce_mm(mni->mm, 2490 KFD_QUEUE_EVICTION_TRIGGER_USERPTR); 2491 2492 if (r && r != -ESRCH) 2493 pr_err("Failed to quiesce KFD\n"); 2494 2495 if (r != -ESRCH) 2496 queue_delayed_work(system_freezable_wq, 2497 &process_info->restore_userptr_work, 2498 msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS)); 2499 } 2500 mutex_unlock(&process_info->notifier_lock); 2501 2502 return r; 2503 } 2504 2505 /* Update invalid userptr BOs 2506 * 2507 * Moves invalidated (evicted) userptr BOs from userptr_valid_list to 2508 * userptr_inval_list and updates user pages for all BOs that have 2509 * been invalidated since their last update. 2510 */ 2511 static int update_invalid_user_pages(struct amdkfd_process_info *process_info, 2512 struct mm_struct *mm) 2513 { 2514 struct kgd_mem *mem, *tmp_mem; 2515 struct amdgpu_bo *bo; 2516 struct ttm_operation_ctx ctx = { false, false }; 2517 uint32_t invalid; 2518 int ret = 0; 2519 2520 mutex_lock(&process_info->notifier_lock); 2521 2522 /* Move all invalidated BOs to the userptr_inval_list */ 2523 list_for_each_entry_safe(mem, tmp_mem, 2524 &process_info->userptr_valid_list, 2525 validate_list) 2526 if (mem->invalid) 2527 list_move_tail(&mem->validate_list, 2528 &process_info->userptr_inval_list); 2529 2530 /* Go through userptr_inval_list and update any invalid user_pages */ 2531 list_for_each_entry(mem, &process_info->userptr_inval_list, 2532 validate_list) { 2533 invalid = mem->invalid; 2534 if (!invalid) 2535 /* BO hasn't been invalidated since the last 2536 * revalidation attempt. Keep its page list. 2537 */ 2538 continue; 2539 2540 bo = mem->bo; 2541 2542 amdgpu_ttm_tt_discard_user_pages(bo->tbo.ttm, mem->range); 2543 mem->range = NULL; 2544 2545 /* BO reservations and getting user pages (hmm_range_fault) 2546 * must happen outside the notifier lock 2547 */ 2548 mutex_unlock(&process_info->notifier_lock); 2549 2550 /* Move the BO to system (CPU) domain if necessary to unmap 2551 * and free the SG table 2552 */ 2553 if (bo->tbo.resource->mem_type != TTM_PL_SYSTEM) { 2554 if (amdgpu_bo_reserve(bo, true)) 2555 return -EAGAIN; 2556 amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU); 2557 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 2558 amdgpu_bo_unreserve(bo); 2559 if (ret) { 2560 pr_err("%s: Failed to invalidate userptr BO\n", 2561 __func__); 2562 return -EAGAIN; 2563 } 2564 } 2565 2566 /* Get updated user pages */ 2567 ret = amdgpu_ttm_tt_get_user_pages(bo, bo->tbo.ttm->pages, 2568 &mem->range); 2569 if (ret) { 2570 pr_debug("Failed %d to get user pages\n", ret); 2571 2572 /* Return -EFAULT bad address error as success. It will 2573 * fail later with a VM fault if the GPU tries to access 2574 * it. Better than hanging indefinitely with stalled 2575 * user mode queues. 2576 * 2577 * Return other error -EBUSY or -ENOMEM to retry restore 2578 */ 2579 if (ret != -EFAULT) 2580 return ret; 2581 2582 /* If applications unmap memory before destroying the userptr 2583 * from the KFD, trigger a segmentation fault in VM debug mode. 2584 */ 2585 if (amdgpu_ttm_adev(bo->tbo.bdev)->debug_vm_userptr) { 2586 pr_err("Pid %d unmapped memory before destroying userptr at GPU addr 0x%llx\n", 2587 pid_nr(process_info->pid), mem->va); 2588 2589 // Send GPU VM fault to user space 2590 kfd_signal_vm_fault_event_with_userptr(kfd_lookup_process_by_pid(process_info->pid), 2591 mem->va); 2592 } 2593 2594 ret = 0; 2595 } 2596 2597 mutex_lock(&process_info->notifier_lock); 2598 2599 /* Mark the BO as valid unless it was invalidated 2600 * again concurrently. 2601 */ 2602 if (mem->invalid != invalid) { 2603 ret = -EAGAIN; 2604 goto unlock_out; 2605 } 2606 /* set mem valid if mem has hmm range associated */ 2607 if (mem->range) 2608 mem->invalid = 0; 2609 } 2610 2611 unlock_out: 2612 mutex_unlock(&process_info->notifier_lock); 2613 2614 return ret; 2615 } 2616 2617 /* Validate invalid userptr BOs 2618 * 2619 * Validates BOs on the userptr_inval_list. Also updates GPUVM page tables 2620 * with new page addresses and waits for the page table updates to complete. 2621 */ 2622 static int validate_invalid_user_pages(struct amdkfd_process_info *process_info) 2623 { 2624 struct ttm_operation_ctx ctx = { false, false }; 2625 struct amdgpu_sync sync; 2626 struct drm_exec exec; 2627 2628 struct amdgpu_vm *peer_vm; 2629 struct kgd_mem *mem, *tmp_mem; 2630 struct amdgpu_bo *bo; 2631 int ret; 2632 2633 amdgpu_sync_create(&sync); 2634 2635 drm_exec_init(&exec, 0, 0); 2636 /* Reserve all BOs and page tables for validation */ 2637 drm_exec_until_all_locked(&exec) { 2638 /* Reserve all the page directories */ 2639 list_for_each_entry(peer_vm, &process_info->vm_list_head, 2640 vm_list_node) { 2641 ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2); 2642 drm_exec_retry_on_contention(&exec); 2643 if (unlikely(ret)) 2644 goto unreserve_out; 2645 } 2646 2647 /* Reserve the userptr_inval_list entries to resv_list */ 2648 list_for_each_entry(mem, &process_info->userptr_inval_list, 2649 validate_list) { 2650 struct drm_gem_object *gobj; 2651 2652 gobj = &mem->bo->tbo.base; 2653 ret = drm_exec_prepare_obj(&exec, gobj, 1); 2654 drm_exec_retry_on_contention(&exec); 2655 if (unlikely(ret)) 2656 goto unreserve_out; 2657 } 2658 } 2659 2660 ret = process_validate_vms(process_info, NULL); 2661 if (ret) 2662 goto unreserve_out; 2663 2664 /* Validate BOs and update GPUVM page tables */ 2665 list_for_each_entry_safe(mem, tmp_mem, 2666 &process_info->userptr_inval_list, 2667 validate_list) { 2668 struct kfd_mem_attachment *attachment; 2669 2670 bo = mem->bo; 2671 2672 /* Validate the BO if we got user pages */ 2673 if (bo->tbo.ttm->pages[0]) { 2674 amdgpu_bo_placement_from_domain(bo, mem->domain); 2675 ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx); 2676 if (ret) { 2677 pr_err("%s: failed to validate BO\n", __func__); 2678 goto unreserve_out; 2679 } 2680 } 2681 2682 /* Update mapping. If the BO was not validated 2683 * (because we couldn't get user pages), this will 2684 * clear the page table entries, which will result in 2685 * VM faults if the GPU tries to access the invalid 2686 * memory. 2687 */ 2688 list_for_each_entry(attachment, &mem->attachments, list) { 2689 if (!attachment->is_mapped) 2690 continue; 2691 2692 kfd_mem_dmaunmap_attachment(mem, attachment); 2693 ret = update_gpuvm_pte(mem, attachment, &sync); 2694 if (ret) { 2695 pr_err("%s: update PTE failed\n", __func__); 2696 /* make sure this gets validated again */ 2697 mutex_lock(&process_info->notifier_lock); 2698 mem->invalid++; 2699 mutex_unlock(&process_info->notifier_lock); 2700 goto unreserve_out; 2701 } 2702 } 2703 } 2704 2705 /* Update page directories */ 2706 ret = process_update_pds(process_info, &sync); 2707 2708 unreserve_out: 2709 drm_exec_fini(&exec); 2710 amdgpu_sync_wait(&sync, false); 2711 amdgpu_sync_free(&sync); 2712 2713 return ret; 2714 } 2715 2716 /* Confirm that all user pages are valid while holding the notifier lock 2717 * 2718 * Moves valid BOs from the userptr_inval_list back to userptr_val_list. 2719 */ 2720 static int confirm_valid_user_pages_locked(struct amdkfd_process_info *process_info) 2721 { 2722 struct kgd_mem *mem, *tmp_mem; 2723 int ret = 0; 2724 2725 list_for_each_entry_safe(mem, tmp_mem, 2726 &process_info->userptr_inval_list, 2727 validate_list) { 2728 bool valid; 2729 2730 /* keep mem without hmm range at userptr_inval_list */ 2731 if (!mem->range) 2732 continue; 2733 2734 /* Only check mem with hmm range associated */ 2735 valid = amdgpu_ttm_tt_get_user_pages_done( 2736 mem->bo->tbo.ttm, mem->range); 2737 2738 mem->range = NULL; 2739 if (!valid) { 2740 WARN(!mem->invalid, "Invalid BO not marked invalid"); 2741 ret = -EAGAIN; 2742 continue; 2743 } 2744 2745 if (mem->invalid) { 2746 WARN(1, "Valid BO is marked invalid"); 2747 ret = -EAGAIN; 2748 continue; 2749 } 2750 2751 list_move_tail(&mem->validate_list, 2752 &process_info->userptr_valid_list); 2753 } 2754 2755 return ret; 2756 } 2757 2758 /* Worker callback to restore evicted userptr BOs 2759 * 2760 * Tries to update and validate all userptr BOs. If successful and no 2761 * concurrent evictions happened, the queues are restarted. Otherwise, 2762 * reschedule for another attempt later. 2763 */ 2764 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work) 2765 { 2766 struct delayed_work *dwork = to_delayed_work(work); 2767 struct amdkfd_process_info *process_info = 2768 container_of(dwork, struct amdkfd_process_info, 2769 restore_userptr_work); 2770 struct task_struct *usertask; 2771 struct mm_struct *mm; 2772 uint32_t evicted_bos; 2773 2774 mutex_lock(&process_info->notifier_lock); 2775 evicted_bos = process_info->evicted_bos; 2776 mutex_unlock(&process_info->notifier_lock); 2777 if (!evicted_bos) 2778 return; 2779 2780 /* Reference task and mm in case of concurrent process termination */ 2781 usertask = get_pid_task(process_info->pid, PIDTYPE_PID); 2782 if (!usertask) 2783 return; 2784 mm = get_task_mm(usertask); 2785 if (!mm) { 2786 put_task_struct(usertask); 2787 return; 2788 } 2789 2790 mutex_lock(&process_info->lock); 2791 2792 if (update_invalid_user_pages(process_info, mm)) 2793 goto unlock_out; 2794 /* userptr_inval_list can be empty if all evicted userptr BOs 2795 * have been freed. In that case there is nothing to validate 2796 * and we can just restart the queues. 2797 */ 2798 if (!list_empty(&process_info->userptr_inval_list)) { 2799 if (validate_invalid_user_pages(process_info)) 2800 goto unlock_out; 2801 } 2802 /* Final check for concurrent evicton and atomic update. If 2803 * another eviction happens after successful update, it will 2804 * be a first eviction that calls quiesce_mm. The eviction 2805 * reference counting inside KFD will handle this case. 2806 */ 2807 mutex_lock(&process_info->notifier_lock); 2808 if (process_info->evicted_bos != evicted_bos) 2809 goto unlock_notifier_out; 2810 2811 if (confirm_valid_user_pages_locked(process_info)) { 2812 WARN(1, "User pages unexpectedly invalid"); 2813 goto unlock_notifier_out; 2814 } 2815 2816 process_info->evicted_bos = evicted_bos = 0; 2817 2818 if (kgd2kfd_resume_mm(mm)) { 2819 pr_err("%s: Failed to resume KFD\n", __func__); 2820 /* No recovery from this failure. Probably the CP is 2821 * hanging. No point trying again. 2822 */ 2823 } 2824 2825 unlock_notifier_out: 2826 mutex_unlock(&process_info->notifier_lock); 2827 unlock_out: 2828 mutex_unlock(&process_info->lock); 2829 2830 /* If validation failed, reschedule another attempt */ 2831 if (evicted_bos) { 2832 queue_delayed_work(system_freezable_wq, 2833 &process_info->restore_userptr_work, 2834 msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS)); 2835 2836 kfd_smi_event_queue_restore_rescheduled(mm); 2837 } 2838 mmput(mm); 2839 put_task_struct(usertask); 2840 } 2841 2842 static void replace_eviction_fence(struct dma_fence __rcu **ef, 2843 struct dma_fence *new_ef) 2844 { 2845 struct dma_fence *old_ef = rcu_replace_pointer(*ef, new_ef, true 2846 /* protected by process_info->lock */); 2847 2848 /* If we're replacing an unsignaled eviction fence, that fence will 2849 * never be signaled, and if anyone is still waiting on that fence, 2850 * they will hang forever. This should never happen. We should only 2851 * replace the fence in restore_work that only gets scheduled after 2852 * eviction work signaled the fence. 2853 */ 2854 WARN_ONCE(!dma_fence_is_signaled(old_ef), 2855 "Replacing unsignaled eviction fence"); 2856 dma_fence_put(old_ef); 2857 } 2858 2859 /** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given 2860 * KFD process identified by process_info 2861 * 2862 * @process_info: amdkfd_process_info of the KFD process 2863 * 2864 * After memory eviction, restore thread calls this function. The function 2865 * should be called when the Process is still valid. BO restore involves - 2866 * 2867 * 1. Release old eviction fence and create new one 2868 * 2. Get two copies of PD BO list from all the VMs. Keep one copy as pd_list. 2869 * 3 Use the second PD list and kfd_bo_list to create a list (ctx.list) of 2870 * BOs that need to be reserved. 2871 * 4. Reserve all the BOs 2872 * 5. Validate of PD and PT BOs. 2873 * 6. Validate all KFD BOs using kfd_bo_list and Map them and add new fence 2874 * 7. Add fence to all PD and PT BOs. 2875 * 8. Unreserve all BOs 2876 */ 2877 int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence __rcu **ef) 2878 { 2879 struct amdkfd_process_info *process_info = info; 2880 struct amdgpu_vm *peer_vm; 2881 struct kgd_mem *mem; 2882 struct list_head duplicate_save; 2883 struct amdgpu_sync sync_obj; 2884 unsigned long failed_size = 0; 2885 unsigned long total_size = 0; 2886 struct drm_exec exec; 2887 int ret; 2888 2889 INIT_LIST_HEAD(&duplicate_save); 2890 2891 mutex_lock(&process_info->lock); 2892 2893 drm_exec_init(&exec, DRM_EXEC_IGNORE_DUPLICATES, 0); 2894 drm_exec_until_all_locked(&exec) { 2895 list_for_each_entry(peer_vm, &process_info->vm_list_head, 2896 vm_list_node) { 2897 ret = amdgpu_vm_lock_pd(peer_vm, &exec, 2); 2898 drm_exec_retry_on_contention(&exec); 2899 if (unlikely(ret)) { 2900 pr_err("Locking VM PD failed, ret: %d\n", ret); 2901 goto ttm_reserve_fail; 2902 } 2903 } 2904 2905 /* Reserve all BOs and page tables/directory. Add all BOs from 2906 * kfd_bo_list to ctx.list 2907 */ 2908 list_for_each_entry(mem, &process_info->kfd_bo_list, 2909 validate_list) { 2910 struct drm_gem_object *gobj; 2911 2912 gobj = &mem->bo->tbo.base; 2913 ret = drm_exec_prepare_obj(&exec, gobj, 1); 2914 drm_exec_retry_on_contention(&exec); 2915 if (unlikely(ret)) { 2916 pr_err("drm_exec_prepare_obj failed, ret: %d\n", ret); 2917 goto ttm_reserve_fail; 2918 } 2919 } 2920 } 2921 2922 amdgpu_sync_create(&sync_obj); 2923 2924 /* Validate BOs managed by KFD */ 2925 list_for_each_entry(mem, &process_info->kfd_bo_list, 2926 validate_list) { 2927 2928 struct amdgpu_bo *bo = mem->bo; 2929 uint32_t domain = mem->domain; 2930 struct dma_resv_iter cursor; 2931 struct dma_fence *fence; 2932 2933 total_size += amdgpu_bo_size(bo); 2934 2935 ret = amdgpu_amdkfd_bo_validate(bo, domain, false); 2936 if (ret) { 2937 pr_debug("Memory eviction: Validate BOs failed\n"); 2938 failed_size += amdgpu_bo_size(bo); 2939 ret = amdgpu_amdkfd_bo_validate(bo, 2940 AMDGPU_GEM_DOMAIN_GTT, false); 2941 if (ret) { 2942 pr_debug("Memory eviction: Try again\n"); 2943 goto validate_map_fail; 2944 } 2945 } 2946 dma_resv_for_each_fence(&cursor, bo->tbo.base.resv, 2947 DMA_RESV_USAGE_KERNEL, fence) { 2948 ret = amdgpu_sync_fence(&sync_obj, fence, GFP_KERNEL); 2949 if (ret) { 2950 pr_debug("Memory eviction: Sync BO fence failed. Try again\n"); 2951 goto validate_map_fail; 2952 } 2953 } 2954 } 2955 2956 if (failed_size) 2957 pr_debug("0x%lx/0x%lx in system\n", failed_size, total_size); 2958 2959 /* Validate PDs, PTs and evicted DMABuf imports last. Otherwise BO 2960 * validations above would invalidate DMABuf imports again. 2961 */ 2962 ret = process_validate_vms(process_info, &exec.ticket); 2963 if (ret) { 2964 pr_debug("Validating VMs failed, ret: %d\n", ret); 2965 goto validate_map_fail; 2966 } 2967 2968 /* Update mappings managed by KFD. */ 2969 list_for_each_entry(mem, &process_info->kfd_bo_list, 2970 validate_list) { 2971 struct kfd_mem_attachment *attachment; 2972 2973 list_for_each_entry(attachment, &mem->attachments, list) { 2974 if (!attachment->is_mapped) 2975 continue; 2976 2977 kfd_mem_dmaunmap_attachment(mem, attachment); 2978 ret = update_gpuvm_pte(mem, attachment, &sync_obj); 2979 if (ret) { 2980 pr_debug("Memory eviction: update PTE failed. Try again\n"); 2981 goto validate_map_fail; 2982 } 2983 } 2984 } 2985 2986 /* Update mappings not managed by KFD */ 2987 list_for_each_entry(peer_vm, &process_info->vm_list_head, 2988 vm_list_node) { 2989 struct amdgpu_device *adev = amdgpu_ttm_adev( 2990 peer_vm->root.bo->tbo.bdev); 2991 2992 ret = amdgpu_vm_handle_moved(adev, peer_vm, &exec.ticket); 2993 if (ret) { 2994 pr_debug("Memory eviction: handle moved failed. Try again\n"); 2995 goto validate_map_fail; 2996 } 2997 } 2998 2999 /* Update page directories */ 3000 ret = process_update_pds(process_info, &sync_obj); 3001 if (ret) { 3002 pr_debug("Memory eviction: update PDs failed. Try again\n"); 3003 goto validate_map_fail; 3004 } 3005 3006 /* Sync with fences on all the page tables. They implicitly depend on any 3007 * move fences from amdgpu_vm_handle_moved above. 3008 */ 3009 ret = process_sync_pds_resv(process_info, &sync_obj); 3010 if (ret) { 3011 pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n"); 3012 goto validate_map_fail; 3013 } 3014 3015 /* Wait for validate and PT updates to finish */ 3016 amdgpu_sync_wait(&sync_obj, false); 3017 3018 /* The old eviction fence may be unsignaled if restore happens 3019 * after a GPU reset or suspend/resume. Keep the old fence in that 3020 * case. Otherwise release the old eviction fence and create new 3021 * one, because fence only goes from unsignaled to signaled once 3022 * and cannot be reused. Use context and mm from the old fence. 3023 * 3024 * If an old eviction fence signals after this check, that's OK. 3025 * Anyone signaling an eviction fence must stop the queues first 3026 * and schedule another restore worker. 3027 */ 3028 if (dma_fence_is_signaled(&process_info->eviction_fence->base)) { 3029 struct amdgpu_amdkfd_fence *new_fence = 3030 amdgpu_amdkfd_fence_create( 3031 process_info->eviction_fence->base.context, 3032 process_info->eviction_fence->mm, 3033 NULL); 3034 3035 if (!new_fence) { 3036 pr_err("Failed to create eviction fence\n"); 3037 ret = -ENOMEM; 3038 goto validate_map_fail; 3039 } 3040 dma_fence_put(&process_info->eviction_fence->base); 3041 process_info->eviction_fence = new_fence; 3042 replace_eviction_fence(ef, dma_fence_get(&new_fence->base)); 3043 } else { 3044 WARN_ONCE(*ef != &process_info->eviction_fence->base, 3045 "KFD eviction fence doesn't match KGD process_info"); 3046 } 3047 3048 /* Attach new eviction fence to all BOs except pinned ones */ 3049 list_for_each_entry(mem, &process_info->kfd_bo_list, validate_list) { 3050 if (mem->bo->tbo.pin_count) 3051 continue; 3052 3053 dma_resv_add_fence(mem->bo->tbo.base.resv, 3054 &process_info->eviction_fence->base, 3055 DMA_RESV_USAGE_BOOKKEEP); 3056 } 3057 /* Attach eviction fence to PD / PT BOs and DMABuf imports */ 3058 list_for_each_entry(peer_vm, &process_info->vm_list_head, 3059 vm_list_node) { 3060 struct amdgpu_bo *bo = peer_vm->root.bo; 3061 3062 dma_resv_add_fence(bo->tbo.base.resv, 3063 &process_info->eviction_fence->base, 3064 DMA_RESV_USAGE_BOOKKEEP); 3065 } 3066 3067 validate_map_fail: 3068 amdgpu_sync_free(&sync_obj); 3069 ttm_reserve_fail: 3070 drm_exec_fini(&exec); 3071 mutex_unlock(&process_info->lock); 3072 return ret; 3073 } 3074 3075 int amdgpu_amdkfd_add_gws_to_process(void *info, void *gws, struct kgd_mem **mem) 3076 { 3077 struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info; 3078 struct amdgpu_bo *gws_bo = (struct amdgpu_bo *)gws; 3079 int ret; 3080 3081 if (!info || !gws) 3082 return -EINVAL; 3083 3084 *mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL); 3085 if (!*mem) 3086 return -ENOMEM; 3087 3088 mutex_init(&(*mem)->lock); 3089 INIT_LIST_HEAD(&(*mem)->attachments); 3090 (*mem)->bo = amdgpu_bo_ref(gws_bo); 3091 (*mem)->domain = AMDGPU_GEM_DOMAIN_GWS; 3092 (*mem)->process_info = process_info; 3093 add_kgd_mem_to_kfd_bo_list(*mem, process_info, false); 3094 amdgpu_sync_create(&(*mem)->sync); 3095 3096 3097 /* Validate gws bo the first time it is added to process */ 3098 mutex_lock(&(*mem)->process_info->lock); 3099 ret = amdgpu_bo_reserve(gws_bo, false); 3100 if (unlikely(ret)) { 3101 pr_err("Reserve gws bo failed %d\n", ret); 3102 goto bo_reservation_failure; 3103 } 3104 3105 ret = amdgpu_amdkfd_bo_validate(gws_bo, AMDGPU_GEM_DOMAIN_GWS, true); 3106 if (ret) { 3107 pr_err("GWS BO validate failed %d\n", ret); 3108 goto bo_validation_failure; 3109 } 3110 /* GWS resource is shared b/t amdgpu and amdkfd 3111 * Add process eviction fence to bo so they can 3112 * evict each other. 3113 */ 3114 ret = dma_resv_reserve_fences(gws_bo->tbo.base.resv, 1); 3115 if (ret) 3116 goto reserve_shared_fail; 3117 dma_resv_add_fence(gws_bo->tbo.base.resv, 3118 &process_info->eviction_fence->base, 3119 DMA_RESV_USAGE_BOOKKEEP); 3120 amdgpu_bo_unreserve(gws_bo); 3121 mutex_unlock(&(*mem)->process_info->lock); 3122 3123 return ret; 3124 3125 reserve_shared_fail: 3126 bo_validation_failure: 3127 amdgpu_bo_unreserve(gws_bo); 3128 bo_reservation_failure: 3129 mutex_unlock(&(*mem)->process_info->lock); 3130 amdgpu_sync_free(&(*mem)->sync); 3131 remove_kgd_mem_from_kfd_bo_list(*mem, process_info); 3132 amdgpu_bo_unref(&gws_bo); 3133 mutex_destroy(&(*mem)->lock); 3134 kfree(*mem); 3135 *mem = NULL; 3136 return ret; 3137 } 3138 3139 int amdgpu_amdkfd_remove_gws_from_process(void *info, void *mem) 3140 { 3141 int ret; 3142 struct amdkfd_process_info *process_info = (struct amdkfd_process_info *)info; 3143 struct kgd_mem *kgd_mem = (struct kgd_mem *)mem; 3144 struct amdgpu_bo *gws_bo = kgd_mem->bo; 3145 3146 /* Remove BO from process's validate list so restore worker won't touch 3147 * it anymore 3148 */ 3149 remove_kgd_mem_from_kfd_bo_list(kgd_mem, process_info); 3150 3151 ret = amdgpu_bo_reserve(gws_bo, false); 3152 if (unlikely(ret)) { 3153 pr_err("Reserve gws bo failed %d\n", ret); 3154 //TODO add BO back to validate_list? 3155 return ret; 3156 } 3157 amdgpu_amdkfd_remove_eviction_fence(gws_bo, 3158 process_info->eviction_fence); 3159 amdgpu_bo_unreserve(gws_bo); 3160 amdgpu_sync_free(&kgd_mem->sync); 3161 amdgpu_bo_unref(&gws_bo); 3162 mutex_destroy(&kgd_mem->lock); 3163 kfree(mem); 3164 return 0; 3165 } 3166 3167 /* Returns GPU-specific tiling mode information */ 3168 int amdgpu_amdkfd_get_tile_config(struct amdgpu_device *adev, 3169 struct tile_config *config) 3170 { 3171 config->gb_addr_config = adev->gfx.config.gb_addr_config; 3172 config->tile_config_ptr = adev->gfx.config.tile_mode_array; 3173 config->num_tile_configs = 3174 ARRAY_SIZE(adev->gfx.config.tile_mode_array); 3175 config->macro_tile_config_ptr = 3176 adev->gfx.config.macrotile_mode_array; 3177 config->num_macro_tile_configs = 3178 ARRAY_SIZE(adev->gfx.config.macrotile_mode_array); 3179 3180 /* Those values are not set from GFX9 onwards */ 3181 config->num_banks = adev->gfx.config.num_banks; 3182 config->num_ranks = adev->gfx.config.num_ranks; 3183 3184 return 0; 3185 } 3186 3187 bool amdgpu_amdkfd_bo_mapped_to_dev(void *drm_priv, struct kgd_mem *mem) 3188 { 3189 struct amdgpu_vm *vm = drm_priv_to_vm(drm_priv); 3190 struct kfd_mem_attachment *entry; 3191 3192 list_for_each_entry(entry, &mem->attachments, list) { 3193 if (entry->is_mapped && entry->bo_va->base.vm == vm) 3194 return true; 3195 } 3196 return false; 3197 } 3198 3199 #if defined(CONFIG_DEBUG_FS) 3200 3201 int kfd_debugfs_kfd_mem_limits(struct seq_file *m, void *data) 3202 { 3203 3204 spin_lock(&kfd_mem_limit.mem_limit_lock); 3205 seq_printf(m, "System mem used %lldM out of %lluM\n", 3206 (kfd_mem_limit.system_mem_used >> 20), 3207 (kfd_mem_limit.max_system_mem_limit >> 20)); 3208 seq_printf(m, "TTM mem used %lldM out of %lluM\n", 3209 (kfd_mem_limit.ttm_mem_used >> 20), 3210 (kfd_mem_limit.max_ttm_mem_limit >> 20)); 3211 spin_unlock(&kfd_mem_limit.mem_limit_lock); 3212 3213 return 0; 3214 } 3215 3216 #endif 3217