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