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