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