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