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