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