]> Git Repo - linux.git/blob - drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c
drm/amdgpu: consistenly use VM moved flag
[linux.git] / drivers / gpu / drm / amd / amdgpu / amdgpu_vm.c
1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  */
28 #include <linux/dma-fence-array.h>
29 #include <linux/interval_tree_generic.h>
30 #include <linux/idr.h>
31 #include <drm/drmP.h>
32 #include <drm/amdgpu_drm.h>
33 #include "amdgpu.h"
34 #include "amdgpu_trace.h"
35 #include "amdgpu_amdkfd.h"
36
37 /*
38  * GPUVM
39  * GPUVM is similar to the legacy gart on older asics, however
40  * rather than there being a single global gart table
41  * for the entire GPU, there are multiple VM page tables active
42  * at any given time.  The VM page tables can contain a mix
43  * vram pages and system memory pages and system memory pages
44  * can be mapped as snooped (cached system pages) or unsnooped
45  * (uncached system pages).
46  * Each VM has an ID associated with it and there is a page table
47  * associated with each VMID.  When execting a command buffer,
48  * the kernel tells the the ring what VMID to use for that command
49  * buffer.  VMIDs are allocated dynamically as commands are submitted.
50  * The userspace drivers maintain their own address space and the kernel
51  * sets up their pages tables accordingly when they submit their
52  * command buffers and a VMID is assigned.
53  * Cayman/Trinity support up to 8 active VMs at any given time;
54  * SI supports 16.
55  */
56
57 #define START(node) ((node)->start)
58 #define LAST(node) ((node)->last)
59
60 INTERVAL_TREE_DEFINE(struct amdgpu_bo_va_mapping, rb, uint64_t, __subtree_last,
61                      START, LAST, static, amdgpu_vm_it)
62
63 #undef START
64 #undef LAST
65
66 /* Local structure. Encapsulate some VM table update parameters to reduce
67  * the number of function parameters
68  */
69 struct amdgpu_pte_update_params {
70         /* amdgpu device we do this update for */
71         struct amdgpu_device *adev;
72         /* optional amdgpu_vm we do this update for */
73         struct amdgpu_vm *vm;
74         /* address where to copy page table entries from */
75         uint64_t src;
76         /* indirect buffer to fill with commands */
77         struct amdgpu_ib *ib;
78         /* Function which actually does the update */
79         void (*func)(struct amdgpu_pte_update_params *params,
80                      struct amdgpu_bo *bo, uint64_t pe,
81                      uint64_t addr, unsigned count, uint32_t incr,
82                      uint64_t flags);
83         /* The next two are used during VM update by CPU
84          *  DMA addresses to use for mapping
85          *  Kernel pointer of PD/PT BO that needs to be updated
86          */
87         dma_addr_t *pages_addr;
88         void *kptr;
89 };
90
91 /* Helper to disable partial resident texture feature from a fence callback */
92 struct amdgpu_prt_cb {
93         struct amdgpu_device *adev;
94         struct dma_fence_cb cb;
95 };
96
97 static void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base,
98                                    struct amdgpu_vm *vm,
99                                    struct amdgpu_bo *bo)
100 {
101         base->vm = vm;
102         base->bo = bo;
103         INIT_LIST_HEAD(&base->bo_list);
104         INIT_LIST_HEAD(&base->vm_status);
105
106         if (!bo)
107                 return;
108         list_add_tail(&base->bo_list, &bo->va);
109
110         if (bo->tbo.resv != vm->root.base.bo->tbo.resv)
111                 return;
112
113         if (bo->preferred_domains &
114             amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type))
115                 return;
116
117         /*
118          * we checked all the prerequisites, but it looks like this per vm bo
119          * is currently evicted. add the bo to the evicted list to make sure it
120          * is validated on next vm use to avoid fault.
121          * */
122         list_move_tail(&base->vm_status, &vm->evicted);
123 }
124
125 /**
126  * amdgpu_vm_level_shift - return the addr shift for each level
127  *
128  * @adev: amdgpu_device pointer
129  *
130  * Returns the number of bits the pfn needs to be right shifted for a level.
131  */
132 static unsigned amdgpu_vm_level_shift(struct amdgpu_device *adev,
133                                       unsigned level)
134 {
135         unsigned shift = 0xff;
136
137         switch (level) {
138         case AMDGPU_VM_PDB2:
139         case AMDGPU_VM_PDB1:
140         case AMDGPU_VM_PDB0:
141                 shift = 9 * (AMDGPU_VM_PDB0 - level) +
142                         adev->vm_manager.block_size;
143                 break;
144         case AMDGPU_VM_PTB:
145                 shift = 0;
146                 break;
147         default:
148                 dev_err(adev->dev, "the level%d isn't supported.\n", level);
149         }
150
151         return shift;
152 }
153
154 /**
155  * amdgpu_vm_num_entries - return the number of entries in a PD/PT
156  *
157  * @adev: amdgpu_device pointer
158  *
159  * Calculate the number of entries in a page directory or page table.
160  */
161 static unsigned amdgpu_vm_num_entries(struct amdgpu_device *adev,
162                                       unsigned level)
163 {
164         unsigned shift = amdgpu_vm_level_shift(adev,
165                                                adev->vm_manager.root_level);
166
167         if (level == adev->vm_manager.root_level)
168                 /* For the root directory */
169                 return round_up(adev->vm_manager.max_pfn, 1 << shift) >> shift;
170         else if (level != AMDGPU_VM_PTB)
171                 /* Everything in between */
172                 return 512;
173         else
174                 /* For the page tables on the leaves */
175                 return AMDGPU_VM_PTE_COUNT(adev);
176 }
177
178 /**
179  * amdgpu_vm_bo_size - returns the size of the BOs in bytes
180  *
181  * @adev: amdgpu_device pointer
182  *
183  * Calculate the size of the BO for a page directory or page table in bytes.
184  */
185 static unsigned amdgpu_vm_bo_size(struct amdgpu_device *adev, unsigned level)
186 {
187         return AMDGPU_GPU_PAGE_ALIGN(amdgpu_vm_num_entries(adev, level) * 8);
188 }
189
190 /**
191  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
192  *
193  * @vm: vm providing the BOs
194  * @validated: head of validation list
195  * @entry: entry to add
196  *
197  * Add the page directory to the list of BOs to
198  * validate for command submission.
199  */
200 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
201                          struct list_head *validated,
202                          struct amdgpu_bo_list_entry *entry)
203 {
204         entry->robj = vm->root.base.bo;
205         entry->priority = 0;
206         entry->tv.bo = &entry->robj->tbo;
207         entry->tv.shared = true;
208         entry->user_pages = NULL;
209         list_add(&entry->tv.head, validated);
210 }
211
212 /**
213  * amdgpu_vm_validate_pt_bos - validate the page table BOs
214  *
215  * @adev: amdgpu device pointer
216  * @vm: vm providing the BOs
217  * @validate: callback to do the validation
218  * @param: parameter for the validation callback
219  *
220  * Validate the page table BOs on command submission if neccessary.
221  */
222 int amdgpu_vm_validate_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
223                               int (*validate)(void *p, struct amdgpu_bo *bo),
224                               void *param)
225 {
226         struct ttm_bo_global *glob = adev->mman.bdev.glob;
227         struct amdgpu_vm_bo_base *bo_base, *tmp;
228         int r = 0;
229
230         list_for_each_entry_safe(bo_base, tmp, &vm->evicted, vm_status) {
231                 struct amdgpu_bo *bo = bo_base->bo;
232
233                 if (bo->parent) {
234                         r = validate(param, bo);
235                         if (r)
236                                 break;
237
238                         spin_lock(&glob->lru_lock);
239                         ttm_bo_move_to_lru_tail(&bo->tbo);
240                         if (bo->shadow)
241                                 ttm_bo_move_to_lru_tail(&bo->shadow->tbo);
242                         spin_unlock(&glob->lru_lock);
243                 }
244
245                 if (bo->tbo.type != ttm_bo_type_kernel) {
246                         spin_lock(&vm->moved_lock);
247                         list_move(&bo_base->vm_status, &vm->moved);
248                         spin_unlock(&vm->moved_lock);
249                 } else {
250                         list_move(&bo_base->vm_status, &vm->relocated);
251                 }
252         }
253
254         return r;
255 }
256
257 /**
258  * amdgpu_vm_ready - check VM is ready for updates
259  *
260  * @vm: VM to check
261  *
262  * Check if all VM PDs/PTs are ready for updates
263  */
264 bool amdgpu_vm_ready(struct amdgpu_vm *vm)
265 {
266         return list_empty(&vm->evicted);
267 }
268
269 /**
270  * amdgpu_vm_clear_bo - initially clear the PDs/PTs
271  *
272  * @adev: amdgpu_device pointer
273  * @bo: BO to clear
274  * @level: level this BO is at
275  *
276  * Root PD needs to be reserved when calling this.
277  */
278 static int amdgpu_vm_clear_bo(struct amdgpu_device *adev,
279                               struct amdgpu_vm *vm, struct amdgpu_bo *bo,
280                               unsigned level, bool pte_support_ats)
281 {
282         struct ttm_operation_ctx ctx = { true, false };
283         struct dma_fence *fence = NULL;
284         unsigned entries, ats_entries;
285         struct amdgpu_ring *ring;
286         struct amdgpu_job *job;
287         uint64_t addr;
288         int r;
289
290         addr = amdgpu_bo_gpu_offset(bo);
291         entries = amdgpu_bo_size(bo) / 8;
292
293         if (pte_support_ats) {
294                 if (level == adev->vm_manager.root_level) {
295                         ats_entries = amdgpu_vm_level_shift(adev, level);
296                         ats_entries += AMDGPU_GPU_PAGE_SHIFT;
297                         ats_entries = AMDGPU_VA_HOLE_START >> ats_entries;
298                         ats_entries = min(ats_entries, entries);
299                         entries -= ats_entries;
300                 } else {
301                         ats_entries = entries;
302                         entries = 0;
303                 }
304         } else {
305                 ats_entries = 0;
306         }
307
308         ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
309
310         r = reservation_object_reserve_shared(bo->tbo.resv);
311         if (r)
312                 return r;
313
314         r = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
315         if (r)
316                 goto error;
317
318         r = amdgpu_job_alloc_with_ib(adev, 64, &job);
319         if (r)
320                 goto error;
321
322         if (ats_entries) {
323                 uint64_t ats_value;
324
325                 ats_value = AMDGPU_PTE_DEFAULT_ATC;
326                 if (level != AMDGPU_VM_PTB)
327                         ats_value |= AMDGPU_PDE_PTE;
328
329                 amdgpu_vm_set_pte_pde(adev, &job->ibs[0], addr, 0,
330                                       ats_entries, 0, ats_value);
331                 addr += ats_entries * 8;
332         }
333
334         if (entries)
335                 amdgpu_vm_set_pte_pde(adev, &job->ibs[0], addr, 0,
336                                       entries, 0, 0);
337
338         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
339
340         WARN_ON(job->ibs[0].length_dw > 64);
341         r = amdgpu_sync_resv(adev, &job->sync, bo->tbo.resv,
342                              AMDGPU_FENCE_OWNER_UNDEFINED, false);
343         if (r)
344                 goto error_free;
345
346         r = amdgpu_job_submit(job, ring, &vm->entity,
347                               AMDGPU_FENCE_OWNER_UNDEFINED, &fence);
348         if (r)
349                 goto error_free;
350
351         amdgpu_bo_fence(bo, fence, true);
352         dma_fence_put(fence);
353
354         if (bo->shadow)
355                 return amdgpu_vm_clear_bo(adev, vm, bo->shadow,
356                                           level, pte_support_ats);
357
358         return 0;
359
360 error_free:
361         amdgpu_job_free(job);
362
363 error:
364         return r;
365 }
366
367 /**
368  * amdgpu_vm_alloc_levels - allocate the PD/PT levels
369  *
370  * @adev: amdgpu_device pointer
371  * @vm: requested vm
372  * @saddr: start of the address range
373  * @eaddr: end of the address range
374  *
375  * Make sure the page directories and page tables are allocated
376  */
377 static int amdgpu_vm_alloc_levels(struct amdgpu_device *adev,
378                                   struct amdgpu_vm *vm,
379                                   struct amdgpu_vm_pt *parent,
380                                   uint64_t saddr, uint64_t eaddr,
381                                   unsigned level, bool ats)
382 {
383         unsigned shift = amdgpu_vm_level_shift(adev, level);
384         unsigned pt_idx, from, to;
385         u64 flags;
386         int r;
387
388         if (!parent->entries) {
389                 unsigned num_entries = amdgpu_vm_num_entries(adev, level);
390
391                 parent->entries = kvmalloc_array(num_entries,
392                                                    sizeof(struct amdgpu_vm_pt),
393                                                    GFP_KERNEL | __GFP_ZERO);
394                 if (!parent->entries)
395                         return -ENOMEM;
396                 memset(parent->entries, 0 , sizeof(struct amdgpu_vm_pt));
397         }
398
399         from = saddr >> shift;
400         to = eaddr >> shift;
401         if (from >= amdgpu_vm_num_entries(adev, level) ||
402             to >= amdgpu_vm_num_entries(adev, level))
403                 return -EINVAL;
404
405         ++level;
406         saddr = saddr & ((1 << shift) - 1);
407         eaddr = eaddr & ((1 << shift) - 1);
408
409         flags = AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
410         if (vm->use_cpu_for_update)
411                 flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
412         else
413                 flags |= (AMDGPU_GEM_CREATE_NO_CPU_ACCESS |
414                                 AMDGPU_GEM_CREATE_SHADOW);
415
416         /* walk over the address space and allocate the page tables */
417         for (pt_idx = from; pt_idx <= to; ++pt_idx) {
418                 struct reservation_object *resv = vm->root.base.bo->tbo.resv;
419                 struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
420                 struct amdgpu_bo *pt;
421
422                 if (!entry->base.bo) {
423                         struct amdgpu_bo_param bp;
424
425                         memset(&bp, 0, sizeof(bp));
426                         bp.size = amdgpu_vm_bo_size(adev, level);
427                         bp.byte_align = AMDGPU_GPU_PAGE_SIZE;
428                         bp.domain = AMDGPU_GEM_DOMAIN_VRAM;
429                         bp.flags = flags;
430                         bp.type = ttm_bo_type_kernel;
431                         bp.resv = resv;
432                         r = amdgpu_bo_create(adev, &bp, &pt);
433                         if (r)
434                                 return r;
435
436                         r = amdgpu_vm_clear_bo(adev, vm, pt, level, ats);
437                         if (r) {
438                                 amdgpu_bo_unref(&pt->shadow);
439                                 amdgpu_bo_unref(&pt);
440                                 return r;
441                         }
442
443                         if (vm->use_cpu_for_update) {
444                                 r = amdgpu_bo_kmap(pt, NULL);
445                                 if (r) {
446                                         amdgpu_bo_unref(&pt->shadow);
447                                         amdgpu_bo_unref(&pt);
448                                         return r;
449                                 }
450                         }
451
452                         /* Keep a reference to the root directory to avoid
453                         * freeing them up in the wrong order.
454                         */
455                         pt->parent = amdgpu_bo_ref(parent->base.bo);
456
457                         amdgpu_vm_bo_base_init(&entry->base, vm, pt);
458                         list_move(&entry->base.vm_status, &vm->relocated);
459                 }
460
461                 if (level < AMDGPU_VM_PTB) {
462                         uint64_t sub_saddr = (pt_idx == from) ? saddr : 0;
463                         uint64_t sub_eaddr = (pt_idx == to) ? eaddr :
464                                 ((1 << shift) - 1);
465                         r = amdgpu_vm_alloc_levels(adev, vm, entry, sub_saddr,
466                                                    sub_eaddr, level, ats);
467                         if (r)
468                                 return r;
469                 }
470         }
471
472         return 0;
473 }
474
475 /**
476  * amdgpu_vm_alloc_pts - Allocate page tables.
477  *
478  * @adev: amdgpu_device pointer
479  * @vm: VM to allocate page tables for
480  * @saddr: Start address which needs to be allocated
481  * @size: Size from start address we need.
482  *
483  * Make sure the page tables are allocated.
484  */
485 int amdgpu_vm_alloc_pts(struct amdgpu_device *adev,
486                         struct amdgpu_vm *vm,
487                         uint64_t saddr, uint64_t size)
488 {
489         uint64_t eaddr;
490         bool ats = false;
491
492         /* validate the parameters */
493         if (saddr & AMDGPU_GPU_PAGE_MASK || size & AMDGPU_GPU_PAGE_MASK)
494                 return -EINVAL;
495
496         eaddr = saddr + size - 1;
497
498         if (vm->pte_support_ats)
499                 ats = saddr < AMDGPU_VA_HOLE_START;
500
501         saddr /= AMDGPU_GPU_PAGE_SIZE;
502         eaddr /= AMDGPU_GPU_PAGE_SIZE;
503
504         if (eaddr >= adev->vm_manager.max_pfn) {
505                 dev_err(adev->dev, "va above limit (0x%08llX >= 0x%08llX)\n",
506                         eaddr, adev->vm_manager.max_pfn);
507                 return -EINVAL;
508         }
509
510         return amdgpu_vm_alloc_levels(adev, vm, &vm->root, saddr, eaddr,
511                                       adev->vm_manager.root_level, ats);
512 }
513
514 /**
515  * amdgpu_vm_check_compute_bug - check whether asic has compute vm bug
516  *
517  * @adev: amdgpu_device pointer
518  */
519 void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
520 {
521         const struct amdgpu_ip_block *ip_block;
522         bool has_compute_vm_bug;
523         struct amdgpu_ring *ring;
524         int i;
525
526         has_compute_vm_bug = false;
527
528         ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
529         if (ip_block) {
530                 /* Compute has a VM bug for GFX version < 7.
531                    Compute has a VM bug for GFX 8 MEC firmware version < 673.*/
532                 if (ip_block->version->major <= 7)
533                         has_compute_vm_bug = true;
534                 else if (ip_block->version->major == 8)
535                         if (adev->gfx.mec_fw_version < 673)
536                                 has_compute_vm_bug = true;
537         }
538
539         for (i = 0; i < adev->num_rings; i++) {
540                 ring = adev->rings[i];
541                 if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE)
542                         /* only compute rings */
543                         ring->has_compute_vm_bug = has_compute_vm_bug;
544                 else
545                         ring->has_compute_vm_bug = false;
546         }
547 }
548
549 bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring,
550                                   struct amdgpu_job *job)
551 {
552         struct amdgpu_device *adev = ring->adev;
553         unsigned vmhub = ring->funcs->vmhub;
554         struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
555         struct amdgpu_vmid *id;
556         bool gds_switch_needed;
557         bool vm_flush_needed = job->vm_needs_flush || ring->has_compute_vm_bug;
558
559         if (job->vmid == 0)
560                 return false;
561         id = &id_mgr->ids[job->vmid];
562         gds_switch_needed = ring->funcs->emit_gds_switch && (
563                 id->gds_base != job->gds_base ||
564                 id->gds_size != job->gds_size ||
565                 id->gws_base != job->gws_base ||
566                 id->gws_size != job->gws_size ||
567                 id->oa_base != job->oa_base ||
568                 id->oa_size != job->oa_size);
569
570         if (amdgpu_vmid_had_gpu_reset(adev, id))
571                 return true;
572
573         return vm_flush_needed || gds_switch_needed;
574 }
575
576 static bool amdgpu_vm_is_large_bar(struct amdgpu_device *adev)
577 {
578         return (adev->gmc.real_vram_size == adev->gmc.visible_vram_size);
579 }
580
581 /**
582  * amdgpu_vm_flush - hardware flush the vm
583  *
584  * @ring: ring to use for flush
585  * @vmid: vmid number to use
586  * @pd_addr: address of the page directory
587  *
588  * Emit a VM flush when it is necessary.
589  */
590 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job, bool need_pipe_sync)
591 {
592         struct amdgpu_device *adev = ring->adev;
593         unsigned vmhub = ring->funcs->vmhub;
594         struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
595         struct amdgpu_vmid *id = &id_mgr->ids[job->vmid];
596         bool gds_switch_needed = ring->funcs->emit_gds_switch && (
597                 id->gds_base != job->gds_base ||
598                 id->gds_size != job->gds_size ||
599                 id->gws_base != job->gws_base ||
600                 id->gws_size != job->gws_size ||
601                 id->oa_base != job->oa_base ||
602                 id->oa_size != job->oa_size);
603         bool vm_flush_needed = job->vm_needs_flush;
604         bool pasid_mapping_needed = id->pasid != job->pasid ||
605                 !id->pasid_mapping ||
606                 !dma_fence_is_signaled(id->pasid_mapping);
607         struct dma_fence *fence = NULL;
608         unsigned patch_offset = 0;
609         int r;
610
611         if (amdgpu_vmid_had_gpu_reset(adev, id)) {
612                 gds_switch_needed = true;
613                 vm_flush_needed = true;
614                 pasid_mapping_needed = true;
615         }
616
617         gds_switch_needed &= !!ring->funcs->emit_gds_switch;
618         vm_flush_needed &= !!ring->funcs->emit_vm_flush;
619         pasid_mapping_needed &= adev->gmc.gmc_funcs->emit_pasid_mapping &&
620                 ring->funcs->emit_wreg;
621
622         if (!vm_flush_needed && !gds_switch_needed && !need_pipe_sync)
623                 return 0;
624
625         if (ring->funcs->init_cond_exec)
626                 patch_offset = amdgpu_ring_init_cond_exec(ring);
627
628         if (need_pipe_sync)
629                 amdgpu_ring_emit_pipeline_sync(ring);
630
631         if (vm_flush_needed) {
632                 trace_amdgpu_vm_flush(ring, job->vmid, job->vm_pd_addr);
633                 amdgpu_ring_emit_vm_flush(ring, job->vmid, job->vm_pd_addr);
634         }
635
636         if (pasid_mapping_needed)
637                 amdgpu_gmc_emit_pasid_mapping(ring, job->vmid, job->pasid);
638
639         if (vm_flush_needed || pasid_mapping_needed) {
640                 r = amdgpu_fence_emit(ring, &fence, 0);
641                 if (r)
642                         return r;
643         }
644
645         if (vm_flush_needed) {
646                 mutex_lock(&id_mgr->lock);
647                 dma_fence_put(id->last_flush);
648                 id->last_flush = dma_fence_get(fence);
649                 id->current_gpu_reset_count =
650                         atomic_read(&adev->gpu_reset_counter);
651                 mutex_unlock(&id_mgr->lock);
652         }
653
654         if (pasid_mapping_needed) {
655                 id->pasid = job->pasid;
656                 dma_fence_put(id->pasid_mapping);
657                 id->pasid_mapping = dma_fence_get(fence);
658         }
659         dma_fence_put(fence);
660
661         if (ring->funcs->emit_gds_switch && gds_switch_needed) {
662                 id->gds_base = job->gds_base;
663                 id->gds_size = job->gds_size;
664                 id->gws_base = job->gws_base;
665                 id->gws_size = job->gws_size;
666                 id->oa_base = job->oa_base;
667                 id->oa_size = job->oa_size;
668                 amdgpu_ring_emit_gds_switch(ring, job->vmid, job->gds_base,
669                                             job->gds_size, job->gws_base,
670                                             job->gws_size, job->oa_base,
671                                             job->oa_size);
672         }
673
674         if (ring->funcs->patch_cond_exec)
675                 amdgpu_ring_patch_cond_exec(ring, patch_offset);
676
677         /* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
678         if (ring->funcs->emit_switch_buffer) {
679                 amdgpu_ring_emit_switch_buffer(ring);
680                 amdgpu_ring_emit_switch_buffer(ring);
681         }
682         return 0;
683 }
684
685 /**
686  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
687  *
688  * @vm: requested vm
689  * @bo: requested buffer object
690  *
691  * Find @bo inside the requested vm.
692  * Search inside the @bos vm list for the requested vm
693  * Returns the found bo_va or NULL if none is found
694  *
695  * Object has to be reserved!
696  */
697 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
698                                        struct amdgpu_bo *bo)
699 {
700         struct amdgpu_bo_va *bo_va;
701
702         list_for_each_entry(bo_va, &bo->va, base.bo_list) {
703                 if (bo_va->base.vm == vm) {
704                         return bo_va;
705                 }
706         }
707         return NULL;
708 }
709
710 /**
711  * amdgpu_vm_do_set_ptes - helper to call the right asic function
712  *
713  * @params: see amdgpu_pte_update_params definition
714  * @bo: PD/PT to update
715  * @pe: addr of the page entry
716  * @addr: dst addr to write into pe
717  * @count: number of page entries to update
718  * @incr: increase next addr by incr bytes
719  * @flags: hw access flags
720  *
721  * Traces the parameters and calls the right asic functions
722  * to setup the page table using the DMA.
723  */
724 static void amdgpu_vm_do_set_ptes(struct amdgpu_pte_update_params *params,
725                                   struct amdgpu_bo *bo,
726                                   uint64_t pe, uint64_t addr,
727                                   unsigned count, uint32_t incr,
728                                   uint64_t flags)
729 {
730         pe += amdgpu_bo_gpu_offset(bo);
731         trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
732
733         if (count < 3) {
734                 amdgpu_vm_write_pte(params->adev, params->ib, pe,
735                                     addr | flags, count, incr);
736
737         } else {
738                 amdgpu_vm_set_pte_pde(params->adev, params->ib, pe, addr,
739                                       count, incr, flags);
740         }
741 }
742
743 /**
744  * amdgpu_vm_do_copy_ptes - copy the PTEs from the GART
745  *
746  * @params: see amdgpu_pte_update_params definition
747  * @bo: PD/PT to update
748  * @pe: addr of the page entry
749  * @addr: dst addr to write into pe
750  * @count: number of page entries to update
751  * @incr: increase next addr by incr bytes
752  * @flags: hw access flags
753  *
754  * Traces the parameters and calls the DMA function to copy the PTEs.
755  */
756 static void amdgpu_vm_do_copy_ptes(struct amdgpu_pte_update_params *params,
757                                    struct amdgpu_bo *bo,
758                                    uint64_t pe, uint64_t addr,
759                                    unsigned count, uint32_t incr,
760                                    uint64_t flags)
761 {
762         uint64_t src = (params->src + (addr >> 12) * 8);
763
764         pe += amdgpu_bo_gpu_offset(bo);
765         trace_amdgpu_vm_copy_ptes(pe, src, count);
766
767         amdgpu_vm_copy_pte(params->adev, params->ib, pe, src, count);
768 }
769
770 /**
771  * amdgpu_vm_map_gart - Resolve gart mapping of addr
772  *
773  * @pages_addr: optional DMA address to use for lookup
774  * @addr: the unmapped addr
775  *
776  * Look up the physical address of the page that the pte resolves
777  * to and return the pointer for the page table entry.
778  */
779 static uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
780 {
781         uint64_t result;
782
783         /* page table offset */
784         result = pages_addr[addr >> PAGE_SHIFT];
785
786         /* in case cpu page size != gpu page size*/
787         result |= addr & (~PAGE_MASK);
788
789         result &= 0xFFFFFFFFFFFFF000ULL;
790
791         return result;
792 }
793
794 /**
795  * amdgpu_vm_cpu_set_ptes - helper to update page tables via CPU
796  *
797  * @params: see amdgpu_pte_update_params definition
798  * @bo: PD/PT to update
799  * @pe: kmap addr of the page entry
800  * @addr: dst addr to write into pe
801  * @count: number of page entries to update
802  * @incr: increase next addr by incr bytes
803  * @flags: hw access flags
804  *
805  * Write count number of PT/PD entries directly.
806  */
807 static void amdgpu_vm_cpu_set_ptes(struct amdgpu_pte_update_params *params,
808                                    struct amdgpu_bo *bo,
809                                    uint64_t pe, uint64_t addr,
810                                    unsigned count, uint32_t incr,
811                                    uint64_t flags)
812 {
813         unsigned int i;
814         uint64_t value;
815
816         pe += (unsigned long)amdgpu_bo_kptr(bo);
817
818         trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
819
820         for (i = 0; i < count; i++) {
821                 value = params->pages_addr ?
822                         amdgpu_vm_map_gart(params->pages_addr, addr) :
823                         addr;
824                 amdgpu_gmc_set_pte_pde(params->adev, (void *)(uintptr_t)pe,
825                                        i, value, flags);
826                 addr += incr;
827         }
828 }
829
830 static int amdgpu_vm_wait_pd(struct amdgpu_device *adev, struct amdgpu_vm *vm,
831                              void *owner)
832 {
833         struct amdgpu_sync sync;
834         int r;
835
836         amdgpu_sync_create(&sync);
837         amdgpu_sync_resv(adev, &sync, vm->root.base.bo->tbo.resv, owner, false);
838         r = amdgpu_sync_wait(&sync, true);
839         amdgpu_sync_free(&sync);
840
841         return r;
842 }
843
844 /*
845  * amdgpu_vm_update_pde - update a single level in the hierarchy
846  *
847  * @param: parameters for the update
848  * @vm: requested vm
849  * @parent: parent directory
850  * @entry: entry to update
851  *
852  * Makes sure the requested entry in parent is up to date.
853  */
854 static void amdgpu_vm_update_pde(struct amdgpu_pte_update_params *params,
855                                  struct amdgpu_vm *vm,
856                                  struct amdgpu_vm_pt *parent,
857                                  struct amdgpu_vm_pt *entry)
858 {
859         struct amdgpu_bo *bo = parent->base.bo, *pbo;
860         uint64_t pde, pt, flags;
861         unsigned level;
862
863         /* Don't update huge pages here */
864         if (entry->huge)
865                 return;
866
867         for (level = 0, pbo = bo->parent; pbo; ++level)
868                 pbo = pbo->parent;
869
870         level += params->adev->vm_manager.root_level;
871         pt = amdgpu_bo_gpu_offset(entry->base.bo);
872         flags = AMDGPU_PTE_VALID;
873         amdgpu_gmc_get_vm_pde(params->adev, level, &pt, &flags);
874         pde = (entry - parent->entries) * 8;
875         if (bo->shadow)
876                 params->func(params, bo->shadow, pde, pt, 1, 0, flags);
877         params->func(params, bo, pde, pt, 1, 0, flags);
878 }
879
880 /*
881  * amdgpu_vm_invalidate_level - mark all PD levels as invalid
882  *
883  * @parent: parent PD
884  *
885  * Mark all PD level as invalid after an error.
886  */
887 static void amdgpu_vm_invalidate_level(struct amdgpu_device *adev,
888                                        struct amdgpu_vm *vm,
889                                        struct amdgpu_vm_pt *parent,
890                                        unsigned level)
891 {
892         unsigned pt_idx, num_entries;
893
894         /*
895          * Recurse into the subdirectories. This recursion is harmless because
896          * we only have a maximum of 5 layers.
897          */
898         num_entries = amdgpu_vm_num_entries(adev, level);
899         for (pt_idx = 0; pt_idx < num_entries; ++pt_idx) {
900                 struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
901
902                 if (!entry->base.bo)
903                         continue;
904
905                 if (!entry->base.moved)
906                         list_move(&entry->base.vm_status, &vm->relocated);
907                 amdgpu_vm_invalidate_level(adev, vm, entry, level + 1);
908         }
909 }
910
911 /*
912  * amdgpu_vm_update_directories - make sure that all directories are valid
913  *
914  * @adev: amdgpu_device pointer
915  * @vm: requested vm
916  *
917  * Makes sure all directories are up to date.
918  * Returns 0 for success, error for failure.
919  */
920 int amdgpu_vm_update_directories(struct amdgpu_device *adev,
921                                  struct amdgpu_vm *vm)
922 {
923         struct amdgpu_pte_update_params params;
924         struct amdgpu_job *job;
925         unsigned ndw = 0;
926         int r = 0;
927
928         if (list_empty(&vm->relocated))
929                 return 0;
930
931 restart:
932         memset(&params, 0, sizeof(params));
933         params.adev = adev;
934
935         if (vm->use_cpu_for_update) {
936                 struct amdgpu_vm_bo_base *bo_base;
937
938                 list_for_each_entry(bo_base, &vm->relocated, vm_status) {
939                         r = amdgpu_bo_kmap(bo_base->bo, NULL);
940                         if (unlikely(r))
941                                 return r;
942                 }
943
944                 r = amdgpu_vm_wait_pd(adev, vm, AMDGPU_FENCE_OWNER_VM);
945                 if (unlikely(r))
946                         return r;
947
948                 params.func = amdgpu_vm_cpu_set_ptes;
949         } else {
950                 ndw = 512 * 8;
951                 r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
952                 if (r)
953                         return r;
954
955                 params.ib = &job->ibs[0];
956                 params.func = amdgpu_vm_do_set_ptes;
957         }
958
959         while (!list_empty(&vm->relocated)) {
960                 struct amdgpu_vm_bo_base *bo_base, *parent;
961                 struct amdgpu_vm_pt *pt, *entry;
962                 struct amdgpu_bo *bo;
963
964                 bo_base = list_first_entry(&vm->relocated,
965                                            struct amdgpu_vm_bo_base,
966                                            vm_status);
967                 bo_base->moved = false;
968                 list_del_init(&bo_base->vm_status);
969
970                 bo = bo_base->bo->parent;
971                 if (!bo)
972                         continue;
973
974                 parent = list_first_entry(&bo->va, struct amdgpu_vm_bo_base,
975                                           bo_list);
976                 pt = container_of(parent, struct amdgpu_vm_pt, base);
977                 entry = container_of(bo_base, struct amdgpu_vm_pt, base);
978
979                 amdgpu_vm_update_pde(&params, vm, pt, entry);
980
981                 if (!vm->use_cpu_for_update &&
982                     (ndw - params.ib->length_dw) < 32)
983                         break;
984         }
985
986         if (vm->use_cpu_for_update) {
987                 /* Flush HDP */
988                 mb();
989                 amdgpu_asic_flush_hdp(adev, NULL);
990         } else if (params.ib->length_dw == 0) {
991                 amdgpu_job_free(job);
992         } else {
993                 struct amdgpu_bo *root = vm->root.base.bo;
994                 struct amdgpu_ring *ring;
995                 struct dma_fence *fence;
996
997                 ring = container_of(vm->entity.sched, struct amdgpu_ring,
998                                     sched);
999
1000                 amdgpu_ring_pad_ib(ring, params.ib);
1001                 amdgpu_sync_resv(adev, &job->sync, root->tbo.resv,
1002                                  AMDGPU_FENCE_OWNER_VM, false);
1003                 WARN_ON(params.ib->length_dw > ndw);
1004                 r = amdgpu_job_submit(job, ring, &vm->entity,
1005                                       AMDGPU_FENCE_OWNER_VM, &fence);
1006                 if (r)
1007                         goto error;
1008
1009                 amdgpu_bo_fence(root, fence, true);
1010                 dma_fence_put(vm->last_update);
1011                 vm->last_update = fence;
1012         }
1013
1014         if (!list_empty(&vm->relocated))
1015                 goto restart;
1016
1017         return 0;
1018
1019 error:
1020         amdgpu_vm_invalidate_level(adev, vm, &vm->root,
1021                                    adev->vm_manager.root_level);
1022         amdgpu_job_free(job);
1023         return r;
1024 }
1025
1026 /**
1027  * amdgpu_vm_find_entry - find the entry for an address
1028  *
1029  * @p: see amdgpu_pte_update_params definition
1030  * @addr: virtual address in question
1031  * @entry: resulting entry or NULL
1032  * @parent: parent entry
1033  *
1034  * Find the vm_pt entry and it's parent for the given address.
1035  */
1036 void amdgpu_vm_get_entry(struct amdgpu_pte_update_params *p, uint64_t addr,
1037                          struct amdgpu_vm_pt **entry,
1038                          struct amdgpu_vm_pt **parent)
1039 {
1040         unsigned level = p->adev->vm_manager.root_level;
1041
1042         *parent = NULL;
1043         *entry = &p->vm->root;
1044         while ((*entry)->entries) {
1045                 unsigned shift = amdgpu_vm_level_shift(p->adev, level++);
1046
1047                 *parent = *entry;
1048                 *entry = &(*entry)->entries[addr >> shift];
1049                 addr &= (1ULL << shift) - 1;
1050         }
1051
1052         if (level != AMDGPU_VM_PTB)
1053                 *entry = NULL;
1054 }
1055
1056 /**
1057  * amdgpu_vm_handle_huge_pages - handle updating the PD with huge pages
1058  *
1059  * @p: see amdgpu_pte_update_params definition
1060  * @entry: vm_pt entry to check
1061  * @parent: parent entry
1062  * @nptes: number of PTEs updated with this operation
1063  * @dst: destination address where the PTEs should point to
1064  * @flags: access flags fro the PTEs
1065  *
1066  * Check if we can update the PD with a huge page.
1067  */
1068 static void amdgpu_vm_handle_huge_pages(struct amdgpu_pte_update_params *p,
1069                                         struct amdgpu_vm_pt *entry,
1070                                         struct amdgpu_vm_pt *parent,
1071                                         unsigned nptes, uint64_t dst,
1072                                         uint64_t flags)
1073 {
1074         uint64_t pde;
1075
1076         /* In the case of a mixed PT the PDE must point to it*/
1077         if (p->adev->asic_type >= CHIP_VEGA10 && !p->src &&
1078             nptes == AMDGPU_VM_PTE_COUNT(p->adev)) {
1079                 /* Set the huge page flag to stop scanning at this PDE */
1080                 flags |= AMDGPU_PDE_PTE;
1081         }
1082
1083         if (!(flags & AMDGPU_PDE_PTE)) {
1084                 if (entry->huge) {
1085                         /* Add the entry to the relocated list to update it. */
1086                         entry->huge = false;
1087                         list_move(&entry->base.vm_status, &p->vm->relocated);
1088                 }
1089                 return;
1090         }
1091
1092         entry->huge = true;
1093         amdgpu_gmc_get_vm_pde(p->adev, AMDGPU_VM_PDB0, &dst, &flags);
1094
1095         pde = (entry - parent->entries) * 8;
1096         if (parent->base.bo->shadow)
1097                 p->func(p, parent->base.bo->shadow, pde, dst, 1, 0, flags);
1098         p->func(p, parent->base.bo, pde, dst, 1, 0, flags);
1099 }
1100
1101 /**
1102  * amdgpu_vm_update_ptes - make sure that page tables are valid
1103  *
1104  * @params: see amdgpu_pte_update_params definition
1105  * @vm: requested vm
1106  * @start: start of GPU address range
1107  * @end: end of GPU address range
1108  * @dst: destination address to map to, the next dst inside the function
1109  * @flags: mapping flags
1110  *
1111  * Update the page tables in the range @start - @end.
1112  * Returns 0 for success, -EINVAL for failure.
1113  */
1114 static int amdgpu_vm_update_ptes(struct amdgpu_pte_update_params *params,
1115                                   uint64_t start, uint64_t end,
1116                                   uint64_t dst, uint64_t flags)
1117 {
1118         struct amdgpu_device *adev = params->adev;
1119         const uint64_t mask = AMDGPU_VM_PTE_COUNT(adev) - 1;
1120
1121         uint64_t addr, pe_start;
1122         struct amdgpu_bo *pt;
1123         unsigned nptes;
1124
1125         /* walk over the address space and update the page tables */
1126         for (addr = start; addr < end; addr += nptes,
1127              dst += nptes * AMDGPU_GPU_PAGE_SIZE) {
1128                 struct amdgpu_vm_pt *entry, *parent;
1129
1130                 amdgpu_vm_get_entry(params, addr, &entry, &parent);
1131                 if (!entry)
1132                         return -ENOENT;
1133
1134                 if ((addr & ~mask) == (end & ~mask))
1135                         nptes = end - addr;
1136                 else
1137                         nptes = AMDGPU_VM_PTE_COUNT(adev) - (addr & mask);
1138
1139                 amdgpu_vm_handle_huge_pages(params, entry, parent,
1140                                             nptes, dst, flags);
1141                 /* We don't need to update PTEs for huge pages */
1142                 if (entry->huge)
1143                         continue;
1144
1145                 pt = entry->base.bo;
1146                 pe_start = (addr & mask) * 8;
1147                 if (pt->shadow)
1148                         params->func(params, pt->shadow, pe_start, dst, nptes,
1149                                      AMDGPU_GPU_PAGE_SIZE, flags);
1150                 params->func(params, pt, pe_start, dst, nptes,
1151                              AMDGPU_GPU_PAGE_SIZE, flags);
1152         }
1153
1154         return 0;
1155 }
1156
1157 /*
1158  * amdgpu_vm_frag_ptes - add fragment information to PTEs
1159  *
1160  * @params: see amdgpu_pte_update_params definition
1161  * @vm: requested vm
1162  * @start: first PTE to handle
1163  * @end: last PTE to handle
1164  * @dst: addr those PTEs should point to
1165  * @flags: hw mapping flags
1166  * Returns 0 for success, -EINVAL for failure.
1167  */
1168 static int amdgpu_vm_frag_ptes(struct amdgpu_pte_update_params  *params,
1169                                 uint64_t start, uint64_t end,
1170                                 uint64_t dst, uint64_t flags)
1171 {
1172         /**
1173          * The MC L1 TLB supports variable sized pages, based on a fragment
1174          * field in the PTE. When this field is set to a non-zero value, page
1175          * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
1176          * flags are considered valid for all PTEs within the fragment range
1177          * and corresponding mappings are assumed to be physically contiguous.
1178          *
1179          * The L1 TLB can store a single PTE for the whole fragment,
1180          * significantly increasing the space available for translation
1181          * caching. This leads to large improvements in throughput when the
1182          * TLB is under pressure.
1183          *
1184          * The L2 TLB distributes small and large fragments into two
1185          * asymmetric partitions. The large fragment cache is significantly
1186          * larger. Thus, we try to use large fragments wherever possible.
1187          * Userspace can support this by aligning virtual base address and
1188          * allocation size to the fragment size.
1189          */
1190         unsigned max_frag = params->adev->vm_manager.fragment_size;
1191         int r;
1192
1193         /* system pages are non continuously */
1194         if (params->src || !(flags & AMDGPU_PTE_VALID))
1195                 return amdgpu_vm_update_ptes(params, start, end, dst, flags);
1196
1197         while (start != end) {
1198                 uint64_t frag_flags, frag_end;
1199                 unsigned frag;
1200
1201                 /* This intentionally wraps around if no bit is set */
1202                 frag = min((unsigned)ffs(start) - 1,
1203                            (unsigned)fls64(end - start) - 1);
1204                 if (frag >= max_frag) {
1205                         frag_flags = AMDGPU_PTE_FRAG(max_frag);
1206                         frag_end = end & ~((1ULL << max_frag) - 1);
1207                 } else {
1208                         frag_flags = AMDGPU_PTE_FRAG(frag);
1209                         frag_end = start + (1 << frag);
1210                 }
1211
1212                 r = amdgpu_vm_update_ptes(params, start, frag_end, dst,
1213                                           flags | frag_flags);
1214                 if (r)
1215                         return r;
1216
1217                 dst += (frag_end - start) * AMDGPU_GPU_PAGE_SIZE;
1218                 start = frag_end;
1219         }
1220
1221         return 0;
1222 }
1223
1224 /**
1225  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
1226  *
1227  * @adev: amdgpu_device pointer
1228  * @exclusive: fence we need to sync to
1229  * @pages_addr: DMA addresses to use for mapping
1230  * @vm: requested vm
1231  * @start: start of mapped range
1232  * @last: last mapped entry
1233  * @flags: flags for the entries
1234  * @addr: addr to set the area to
1235  * @fence: optional resulting fence
1236  *
1237  * Fill in the page table entries between @start and @last.
1238  * Returns 0 for success, -EINVAL for failure.
1239  */
1240 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
1241                                        struct dma_fence *exclusive,
1242                                        dma_addr_t *pages_addr,
1243                                        struct amdgpu_vm *vm,
1244                                        uint64_t start, uint64_t last,
1245                                        uint64_t flags, uint64_t addr,
1246                                        struct dma_fence **fence)
1247 {
1248         struct amdgpu_ring *ring;
1249         void *owner = AMDGPU_FENCE_OWNER_VM;
1250         unsigned nptes, ncmds, ndw;
1251         struct amdgpu_job *job;
1252         struct amdgpu_pte_update_params params;
1253         struct dma_fence *f = NULL;
1254         int r;
1255
1256         memset(&params, 0, sizeof(params));
1257         params.adev = adev;
1258         params.vm = vm;
1259
1260         /* sync to everything on unmapping */
1261         if (!(flags & AMDGPU_PTE_VALID))
1262                 owner = AMDGPU_FENCE_OWNER_UNDEFINED;
1263
1264         if (vm->use_cpu_for_update) {
1265                 /* params.src is used as flag to indicate system Memory */
1266                 if (pages_addr)
1267                         params.src = ~0;
1268
1269                 /* Wait for PT BOs to be free. PTs share the same resv. object
1270                  * as the root PD BO
1271                  */
1272                 r = amdgpu_vm_wait_pd(adev, vm, owner);
1273                 if (unlikely(r))
1274                         return r;
1275
1276                 params.func = amdgpu_vm_cpu_set_ptes;
1277                 params.pages_addr = pages_addr;
1278                 return amdgpu_vm_frag_ptes(&params, start, last + 1,
1279                                            addr, flags);
1280         }
1281
1282         ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
1283
1284         nptes = last - start + 1;
1285
1286         /*
1287          * reserve space for two commands every (1 << BLOCK_SIZE)
1288          *  entries or 2k dwords (whatever is smaller)
1289          *
1290          * The second command is for the shadow pagetables.
1291          */
1292         if (vm->root.base.bo->shadow)
1293                 ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1) * 2;
1294         else
1295                 ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1);
1296
1297         /* padding, etc. */
1298         ndw = 64;
1299
1300         if (pages_addr) {
1301                 /* copy commands needed */
1302                 ndw += ncmds * adev->vm_manager.vm_pte_funcs->copy_pte_num_dw;
1303
1304                 /* and also PTEs */
1305                 ndw += nptes * 2;
1306
1307                 params.func = amdgpu_vm_do_copy_ptes;
1308
1309         } else {
1310                 /* set page commands needed */
1311                 ndw += ncmds * 10;
1312
1313                 /* extra commands for begin/end fragments */
1314                 ndw += 2 * 10 * adev->vm_manager.fragment_size;
1315
1316                 params.func = amdgpu_vm_do_set_ptes;
1317         }
1318
1319         r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1320         if (r)
1321                 return r;
1322
1323         params.ib = &job->ibs[0];
1324
1325         if (pages_addr) {
1326                 uint64_t *pte;
1327                 unsigned i;
1328
1329                 /* Put the PTEs at the end of the IB. */
1330                 i = ndw - nptes * 2;
1331                 pte= (uint64_t *)&(job->ibs->ptr[i]);
1332                 params.src = job->ibs->gpu_addr + i * 4;
1333
1334                 for (i = 0; i < nptes; ++i) {
1335                         pte[i] = amdgpu_vm_map_gart(pages_addr, addr + i *
1336                                                     AMDGPU_GPU_PAGE_SIZE);
1337                         pte[i] |= flags;
1338                 }
1339                 addr = 0;
1340         }
1341
1342         r = amdgpu_sync_fence(adev, &job->sync, exclusive, false);
1343         if (r)
1344                 goto error_free;
1345
1346         r = amdgpu_sync_resv(adev, &job->sync, vm->root.base.bo->tbo.resv,
1347                              owner, false);
1348         if (r)
1349                 goto error_free;
1350
1351         r = reservation_object_reserve_shared(vm->root.base.bo->tbo.resv);
1352         if (r)
1353                 goto error_free;
1354
1355         r = amdgpu_vm_frag_ptes(&params, start, last + 1, addr, flags);
1356         if (r)
1357                 goto error_free;
1358
1359         amdgpu_ring_pad_ib(ring, params.ib);
1360         WARN_ON(params.ib->length_dw > ndw);
1361         r = amdgpu_job_submit(job, ring, &vm->entity,
1362                               AMDGPU_FENCE_OWNER_VM, &f);
1363         if (r)
1364                 goto error_free;
1365
1366         amdgpu_bo_fence(vm->root.base.bo, f, true);
1367         dma_fence_put(*fence);
1368         *fence = f;
1369         return 0;
1370
1371 error_free:
1372         amdgpu_job_free(job);
1373         return r;
1374 }
1375
1376 /**
1377  * amdgpu_vm_bo_split_mapping - split a mapping into smaller chunks
1378  *
1379  * @adev: amdgpu_device pointer
1380  * @exclusive: fence we need to sync to
1381  * @pages_addr: DMA addresses to use for mapping
1382  * @vm: requested vm
1383  * @mapping: mapped range and flags to use for the update
1384  * @flags: HW flags for the mapping
1385  * @nodes: array of drm_mm_nodes with the MC addresses
1386  * @fence: optional resulting fence
1387  *
1388  * Split the mapping into smaller chunks so that each update fits
1389  * into a SDMA IB.
1390  * Returns 0 for success, -EINVAL for failure.
1391  */
1392 static int amdgpu_vm_bo_split_mapping(struct amdgpu_device *adev,
1393                                       struct dma_fence *exclusive,
1394                                       dma_addr_t *pages_addr,
1395                                       struct amdgpu_vm *vm,
1396                                       struct amdgpu_bo_va_mapping *mapping,
1397                                       uint64_t flags,
1398                                       struct drm_mm_node *nodes,
1399                                       struct dma_fence **fence)
1400 {
1401         unsigned min_linear_pages = 1 << adev->vm_manager.fragment_size;
1402         uint64_t pfn, start = mapping->start;
1403         int r;
1404
1405         /* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1406          * but in case of something, we filter the flags in first place
1407          */
1408         if (!(mapping->flags & AMDGPU_PTE_READABLE))
1409                 flags &= ~AMDGPU_PTE_READABLE;
1410         if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1411                 flags &= ~AMDGPU_PTE_WRITEABLE;
1412
1413         flags &= ~AMDGPU_PTE_EXECUTABLE;
1414         flags |= mapping->flags & AMDGPU_PTE_EXECUTABLE;
1415
1416         flags &= ~AMDGPU_PTE_MTYPE_MASK;
1417         flags |= (mapping->flags & AMDGPU_PTE_MTYPE_MASK);
1418
1419         if ((mapping->flags & AMDGPU_PTE_PRT) &&
1420             (adev->asic_type >= CHIP_VEGA10)) {
1421                 flags |= AMDGPU_PTE_PRT;
1422                 flags &= ~AMDGPU_PTE_VALID;
1423         }
1424
1425         trace_amdgpu_vm_bo_update(mapping);
1426
1427         pfn = mapping->offset >> PAGE_SHIFT;
1428         if (nodes) {
1429                 while (pfn >= nodes->size) {
1430                         pfn -= nodes->size;
1431                         ++nodes;
1432                 }
1433         }
1434
1435         do {
1436                 dma_addr_t *dma_addr = NULL;
1437                 uint64_t max_entries;
1438                 uint64_t addr, last;
1439
1440                 if (nodes) {
1441                         addr = nodes->start << PAGE_SHIFT;
1442                         max_entries = (nodes->size - pfn) *
1443                                 (PAGE_SIZE / AMDGPU_GPU_PAGE_SIZE);
1444                 } else {
1445                         addr = 0;
1446                         max_entries = S64_MAX;
1447                 }
1448
1449                 if (pages_addr) {
1450                         uint64_t count;
1451
1452                         max_entries = min(max_entries, 16ull * 1024ull);
1453                         for (count = 1; count < max_entries; ++count) {
1454                                 uint64_t idx = pfn + count;
1455
1456                                 if (pages_addr[idx] !=
1457                                     (pages_addr[idx - 1] + PAGE_SIZE))
1458                                         break;
1459                         }
1460
1461                         if (count < min_linear_pages) {
1462                                 addr = pfn << PAGE_SHIFT;
1463                                 dma_addr = pages_addr;
1464                         } else {
1465                                 addr = pages_addr[pfn];
1466                                 max_entries = count;
1467                         }
1468
1469                 } else if (flags & AMDGPU_PTE_VALID) {
1470                         addr += adev->vm_manager.vram_base_offset;
1471                         addr += pfn << PAGE_SHIFT;
1472                 }
1473
1474                 last = min((uint64_t)mapping->last, start + max_entries - 1);
1475                 r = amdgpu_vm_bo_update_mapping(adev, exclusive, dma_addr, vm,
1476                                                 start, last, flags, addr,
1477                                                 fence);
1478                 if (r)
1479                         return r;
1480
1481                 pfn += last - start + 1;
1482                 if (nodes && nodes->size == pfn) {
1483                         pfn = 0;
1484                         ++nodes;
1485                 }
1486                 start = last + 1;
1487
1488         } while (unlikely(start != mapping->last + 1));
1489
1490         return 0;
1491 }
1492
1493 /**
1494  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1495  *
1496  * @adev: amdgpu_device pointer
1497  * @bo_va: requested BO and VM object
1498  * @clear: if true clear the entries
1499  *
1500  * Fill in the page table entries for @bo_va.
1501  * Returns 0 for success, -EINVAL for failure.
1502  */
1503 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
1504                         struct amdgpu_bo_va *bo_va,
1505                         bool clear)
1506 {
1507         struct amdgpu_bo *bo = bo_va->base.bo;
1508         struct amdgpu_vm *vm = bo_va->base.vm;
1509         struct amdgpu_bo_va_mapping *mapping;
1510         dma_addr_t *pages_addr = NULL;
1511         struct ttm_mem_reg *mem;
1512         struct drm_mm_node *nodes;
1513         struct dma_fence *exclusive, **last_update;
1514         uint64_t flags;
1515         int r;
1516
1517         if (clear || !bo_va->base.bo) {
1518                 mem = NULL;
1519                 nodes = NULL;
1520                 exclusive = NULL;
1521         } else {
1522                 struct ttm_dma_tt *ttm;
1523
1524                 mem = &bo_va->base.bo->tbo.mem;
1525                 nodes = mem->mm_node;
1526                 if (mem->mem_type == TTM_PL_TT) {
1527                         ttm = container_of(bo_va->base.bo->tbo.ttm,
1528                                            struct ttm_dma_tt, ttm);
1529                         pages_addr = ttm->dma_address;
1530                 }
1531                 exclusive = reservation_object_get_excl(bo->tbo.resv);
1532         }
1533
1534         if (bo)
1535                 flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
1536         else
1537                 flags = 0x0;
1538
1539         if (clear || (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv))
1540                 last_update = &vm->last_update;
1541         else
1542                 last_update = &bo_va->last_pt_update;
1543
1544         if (!clear && bo_va->base.moved) {
1545                 bo_va->base.moved = false;
1546                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1547
1548         } else if (bo_va->cleared != clear) {
1549                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1550         }
1551
1552         list_for_each_entry(mapping, &bo_va->invalids, list) {
1553                 r = amdgpu_vm_bo_split_mapping(adev, exclusive, pages_addr, vm,
1554                                                mapping, flags, nodes,
1555                                                last_update);
1556                 if (r)
1557                         return r;
1558         }
1559
1560         if (vm->use_cpu_for_update) {
1561                 /* Flush HDP */
1562                 mb();
1563                 amdgpu_asic_flush_hdp(adev, NULL);
1564         }
1565
1566         spin_lock(&vm->moved_lock);
1567         list_del_init(&bo_va->base.vm_status);
1568         spin_unlock(&vm->moved_lock);
1569
1570         /* If the BO is not in its preferred location add it back to
1571          * the evicted list so that it gets validated again on the
1572          * next command submission.
1573          */
1574         if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv &&
1575             !(bo->preferred_domains &
1576             amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type)))
1577                 list_add_tail(&bo_va->base.vm_status, &vm->evicted);
1578
1579         list_splice_init(&bo_va->invalids, &bo_va->valids);
1580         bo_va->cleared = clear;
1581
1582         if (trace_amdgpu_vm_bo_mapping_enabled()) {
1583                 list_for_each_entry(mapping, &bo_va->valids, list)
1584                         trace_amdgpu_vm_bo_mapping(mapping);
1585         }
1586
1587         return 0;
1588 }
1589
1590 /**
1591  * amdgpu_vm_update_prt_state - update the global PRT state
1592  */
1593 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1594 {
1595         unsigned long flags;
1596         bool enable;
1597
1598         spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1599         enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1600         adev->gmc.gmc_funcs->set_prt(adev, enable);
1601         spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1602 }
1603
1604 /**
1605  * amdgpu_vm_prt_get - add a PRT user
1606  */
1607 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1608 {
1609         if (!adev->gmc.gmc_funcs->set_prt)
1610                 return;
1611
1612         if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1613                 amdgpu_vm_update_prt_state(adev);
1614 }
1615
1616 /**
1617  * amdgpu_vm_prt_put - drop a PRT user
1618  */
1619 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1620 {
1621         if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1622                 amdgpu_vm_update_prt_state(adev);
1623 }
1624
1625 /**
1626  * amdgpu_vm_prt_cb - callback for updating the PRT status
1627  */
1628 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1629 {
1630         struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1631
1632         amdgpu_vm_prt_put(cb->adev);
1633         kfree(cb);
1634 }
1635
1636 /**
1637  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1638  */
1639 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1640                                  struct dma_fence *fence)
1641 {
1642         struct amdgpu_prt_cb *cb;
1643
1644         if (!adev->gmc.gmc_funcs->set_prt)
1645                 return;
1646
1647         cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
1648         if (!cb) {
1649                 /* Last resort when we are OOM */
1650                 if (fence)
1651                         dma_fence_wait(fence, false);
1652
1653                 amdgpu_vm_prt_put(adev);
1654         } else {
1655                 cb->adev = adev;
1656                 if (!fence || dma_fence_add_callback(fence, &cb->cb,
1657                                                      amdgpu_vm_prt_cb))
1658                         amdgpu_vm_prt_cb(fence, &cb->cb);
1659         }
1660 }
1661
1662 /**
1663  * amdgpu_vm_free_mapping - free a mapping
1664  *
1665  * @adev: amdgpu_device pointer
1666  * @vm: requested vm
1667  * @mapping: mapping to be freed
1668  * @fence: fence of the unmap operation
1669  *
1670  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1671  */
1672 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1673                                    struct amdgpu_vm *vm,
1674                                    struct amdgpu_bo_va_mapping *mapping,
1675                                    struct dma_fence *fence)
1676 {
1677         if (mapping->flags & AMDGPU_PTE_PRT)
1678                 amdgpu_vm_add_prt_cb(adev, fence);
1679         kfree(mapping);
1680 }
1681
1682 /**
1683  * amdgpu_vm_prt_fini - finish all prt mappings
1684  *
1685  * @adev: amdgpu_device pointer
1686  * @vm: requested vm
1687  *
1688  * Register a cleanup callback to disable PRT support after VM dies.
1689  */
1690 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1691 {
1692         struct reservation_object *resv = vm->root.base.bo->tbo.resv;
1693         struct dma_fence *excl, **shared;
1694         unsigned i, shared_count;
1695         int r;
1696
1697         r = reservation_object_get_fences_rcu(resv, &excl,
1698                                               &shared_count, &shared);
1699         if (r) {
1700                 /* Not enough memory to grab the fence list, as last resort
1701                  * block for all the fences to complete.
1702                  */
1703                 reservation_object_wait_timeout_rcu(resv, true, false,
1704                                                     MAX_SCHEDULE_TIMEOUT);
1705                 return;
1706         }
1707
1708         /* Add a callback for each fence in the reservation object */
1709         amdgpu_vm_prt_get(adev);
1710         amdgpu_vm_add_prt_cb(adev, excl);
1711
1712         for (i = 0; i < shared_count; ++i) {
1713                 amdgpu_vm_prt_get(adev);
1714                 amdgpu_vm_add_prt_cb(adev, shared[i]);
1715         }
1716
1717         kfree(shared);
1718 }
1719
1720 /**
1721  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1722  *
1723  * @adev: amdgpu_device pointer
1724  * @vm: requested vm
1725  * @fence: optional resulting fence (unchanged if no work needed to be done
1726  * or if an error occurred)
1727  *
1728  * Make sure all freed BOs are cleared in the PT.
1729  * Returns 0 for success.
1730  *
1731  * PTs have to be reserved and mutex must be locked!
1732  */
1733 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
1734                           struct amdgpu_vm *vm,
1735                           struct dma_fence **fence)
1736 {
1737         struct amdgpu_bo_va_mapping *mapping;
1738         uint64_t init_pte_value = 0;
1739         struct dma_fence *f = NULL;
1740         int r;
1741
1742         while (!list_empty(&vm->freed)) {
1743                 mapping = list_first_entry(&vm->freed,
1744                         struct amdgpu_bo_va_mapping, list);
1745                 list_del(&mapping->list);
1746
1747                 if (vm->pte_support_ats && mapping->start < AMDGPU_VA_HOLE_START)
1748                         init_pte_value = AMDGPU_PTE_DEFAULT_ATC;
1749
1750                 r = amdgpu_vm_bo_update_mapping(adev, NULL, NULL, vm,
1751                                                 mapping->start, mapping->last,
1752                                                 init_pte_value, 0, &f);
1753                 amdgpu_vm_free_mapping(adev, vm, mapping, f);
1754                 if (r) {
1755                         dma_fence_put(f);
1756                         return r;
1757                 }
1758         }
1759
1760         if (fence && f) {
1761                 dma_fence_put(*fence);
1762                 *fence = f;
1763         } else {
1764                 dma_fence_put(f);
1765         }
1766
1767         return 0;
1768
1769 }
1770
1771 /**
1772  * amdgpu_vm_handle_moved - handle moved BOs in the PT
1773  *
1774  * @adev: amdgpu_device pointer
1775  * @vm: requested vm
1776  * @sync: sync object to add fences to
1777  *
1778  * Make sure all BOs which are moved are updated in the PTs.
1779  * Returns 0 for success.
1780  *
1781  * PTs have to be reserved!
1782  */
1783 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
1784                            struct amdgpu_vm *vm)
1785 {
1786         struct amdgpu_bo_va *bo_va, *tmp;
1787         struct list_head moved;
1788         bool clear;
1789         int r;
1790
1791         INIT_LIST_HEAD(&moved);
1792         spin_lock(&vm->moved_lock);
1793         list_splice_init(&vm->moved, &moved);
1794         spin_unlock(&vm->moved_lock);
1795
1796         list_for_each_entry_safe(bo_va, tmp, &moved, base.vm_status) {
1797                 struct reservation_object *resv = bo_va->base.bo->tbo.resv;
1798
1799                 /* Per VM BOs never need to bo cleared in the page tables */
1800                 if (resv == vm->root.base.bo->tbo.resv)
1801                         clear = false;
1802                 /* Try to reserve the BO to avoid clearing its ptes */
1803                 else if (!amdgpu_vm_debug && reservation_object_trylock(resv))
1804                         clear = false;
1805                 /* Somebody else is using the BO right now */
1806                 else
1807                         clear = true;
1808
1809                 r = amdgpu_vm_bo_update(adev, bo_va, clear);
1810                 if (r) {
1811                         spin_lock(&vm->moved_lock);
1812                         list_splice(&moved, &vm->moved);
1813                         spin_unlock(&vm->moved_lock);
1814                         return r;
1815                 }
1816
1817                 if (!clear && resv != vm->root.base.bo->tbo.resv)
1818                         reservation_object_unlock(resv);
1819
1820         }
1821
1822         return 0;
1823 }
1824
1825 /**
1826  * amdgpu_vm_bo_add - add a bo to a specific vm
1827  *
1828  * @adev: amdgpu_device pointer
1829  * @vm: requested vm
1830  * @bo: amdgpu buffer object
1831  *
1832  * Add @bo into the requested vm.
1833  * Add @bo to the list of bos associated with the vm
1834  * Returns newly added bo_va or NULL for failure
1835  *
1836  * Object has to be reserved!
1837  */
1838 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
1839                                       struct amdgpu_vm *vm,
1840                                       struct amdgpu_bo *bo)
1841 {
1842         struct amdgpu_bo_va *bo_va;
1843
1844         bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
1845         if (bo_va == NULL) {
1846                 return NULL;
1847         }
1848         amdgpu_vm_bo_base_init(&bo_va->base, vm, bo);
1849
1850         bo_va->ref_count = 1;
1851         INIT_LIST_HEAD(&bo_va->valids);
1852         INIT_LIST_HEAD(&bo_va->invalids);
1853
1854         return bo_va;
1855 }
1856
1857
1858 /**
1859  * amdgpu_vm_bo_insert_mapping - insert a new mapping
1860  *
1861  * @adev: amdgpu_device pointer
1862  * @bo_va: bo_va to store the address
1863  * @mapping: the mapping to insert
1864  *
1865  * Insert a new mapping into all structures.
1866  */
1867 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
1868                                     struct amdgpu_bo_va *bo_va,
1869                                     struct amdgpu_bo_va_mapping *mapping)
1870 {
1871         struct amdgpu_vm *vm = bo_va->base.vm;
1872         struct amdgpu_bo *bo = bo_va->base.bo;
1873
1874         mapping->bo_va = bo_va;
1875         list_add(&mapping->list, &bo_va->invalids);
1876         amdgpu_vm_it_insert(mapping, &vm->va);
1877
1878         if (mapping->flags & AMDGPU_PTE_PRT)
1879                 amdgpu_vm_prt_get(adev);
1880
1881         if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv &&
1882             !bo_va->base.moved) {
1883                 spin_lock(&vm->moved_lock);
1884                 list_move(&bo_va->base.vm_status, &vm->moved);
1885                 spin_unlock(&vm->moved_lock);
1886         }
1887         trace_amdgpu_vm_bo_map(bo_va, mapping);
1888 }
1889
1890 /**
1891  * amdgpu_vm_bo_map - map bo inside a vm
1892  *
1893  * @adev: amdgpu_device pointer
1894  * @bo_va: bo_va to store the address
1895  * @saddr: where to map the BO
1896  * @offset: requested offset in the BO
1897  * @flags: attributes of pages (read/write/valid/etc.)
1898  *
1899  * Add a mapping of the BO at the specefied addr into the VM.
1900  * Returns 0 for success, error for failure.
1901  *
1902  * Object has to be reserved and unreserved outside!
1903  */
1904 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1905                      struct amdgpu_bo_va *bo_va,
1906                      uint64_t saddr, uint64_t offset,
1907                      uint64_t size, uint64_t flags)
1908 {
1909         struct amdgpu_bo_va_mapping *mapping, *tmp;
1910         struct amdgpu_bo *bo = bo_va->base.bo;
1911         struct amdgpu_vm *vm = bo_va->base.vm;
1912         uint64_t eaddr;
1913
1914         /* validate the parameters */
1915         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1916             size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1917                 return -EINVAL;
1918
1919         /* make sure object fit at this offset */
1920         eaddr = saddr + size - 1;
1921         if (saddr >= eaddr ||
1922             (bo && offset + size > amdgpu_bo_size(bo)))
1923                 return -EINVAL;
1924
1925         saddr /= AMDGPU_GPU_PAGE_SIZE;
1926         eaddr /= AMDGPU_GPU_PAGE_SIZE;
1927
1928         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
1929         if (tmp) {
1930                 /* bo and tmp overlap, invalid addr */
1931                 dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1932                         "0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
1933                         tmp->start, tmp->last + 1);
1934                 return -EINVAL;
1935         }
1936
1937         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1938         if (!mapping)
1939                 return -ENOMEM;
1940
1941         mapping->start = saddr;
1942         mapping->last = eaddr;
1943         mapping->offset = offset;
1944         mapping->flags = flags;
1945
1946         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1947
1948         return 0;
1949 }
1950
1951 /**
1952  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
1953  *
1954  * @adev: amdgpu_device pointer
1955  * @bo_va: bo_va to store the address
1956  * @saddr: where to map the BO
1957  * @offset: requested offset in the BO
1958  * @flags: attributes of pages (read/write/valid/etc.)
1959  *
1960  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
1961  * mappings as we do so.
1962  * Returns 0 for success, error for failure.
1963  *
1964  * Object has to be reserved and unreserved outside!
1965  */
1966 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
1967                              struct amdgpu_bo_va *bo_va,
1968                              uint64_t saddr, uint64_t offset,
1969                              uint64_t size, uint64_t flags)
1970 {
1971         struct amdgpu_bo_va_mapping *mapping;
1972         struct amdgpu_bo *bo = bo_va->base.bo;
1973         uint64_t eaddr;
1974         int r;
1975
1976         /* validate the parameters */
1977         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1978             size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1979                 return -EINVAL;
1980
1981         /* make sure object fit at this offset */
1982         eaddr = saddr + size - 1;
1983         if (saddr >= eaddr ||
1984             (bo && offset + size > amdgpu_bo_size(bo)))
1985                 return -EINVAL;
1986
1987         /* Allocate all the needed memory */
1988         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1989         if (!mapping)
1990                 return -ENOMEM;
1991
1992         r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
1993         if (r) {
1994                 kfree(mapping);
1995                 return r;
1996         }
1997
1998         saddr /= AMDGPU_GPU_PAGE_SIZE;
1999         eaddr /= AMDGPU_GPU_PAGE_SIZE;
2000
2001         mapping->start = saddr;
2002         mapping->last = eaddr;
2003         mapping->offset = offset;
2004         mapping->flags = flags;
2005
2006         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2007
2008         return 0;
2009 }
2010
2011 /**
2012  * amdgpu_vm_bo_unmap - remove bo mapping from vm
2013  *
2014  * @adev: amdgpu_device pointer
2015  * @bo_va: bo_va to remove the address from
2016  * @saddr: where to the BO is mapped
2017  *
2018  * Remove a mapping of the BO at the specefied addr from the VM.
2019  * Returns 0 for success, error for failure.
2020  *
2021  * Object has to be reserved and unreserved outside!
2022  */
2023 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
2024                        struct amdgpu_bo_va *bo_va,
2025                        uint64_t saddr)
2026 {
2027         struct amdgpu_bo_va_mapping *mapping;
2028         struct amdgpu_vm *vm = bo_va->base.vm;
2029         bool valid = true;
2030
2031         saddr /= AMDGPU_GPU_PAGE_SIZE;
2032
2033         list_for_each_entry(mapping, &bo_va->valids, list) {
2034                 if (mapping->start == saddr)
2035                         break;
2036         }
2037
2038         if (&mapping->list == &bo_va->valids) {
2039                 valid = false;
2040
2041                 list_for_each_entry(mapping, &bo_va->invalids, list) {
2042                         if (mapping->start == saddr)
2043                                 break;
2044                 }
2045
2046                 if (&mapping->list == &bo_va->invalids)
2047                         return -ENOENT;
2048         }
2049
2050         list_del(&mapping->list);
2051         amdgpu_vm_it_remove(mapping, &vm->va);
2052         mapping->bo_va = NULL;
2053         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2054
2055         if (valid)
2056                 list_add(&mapping->list, &vm->freed);
2057         else
2058                 amdgpu_vm_free_mapping(adev, vm, mapping,
2059                                        bo_va->last_pt_update);
2060
2061         return 0;
2062 }
2063
2064 /**
2065  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
2066  *
2067  * @adev: amdgpu_device pointer
2068  * @vm: VM structure to use
2069  * @saddr: start of the range
2070  * @size: size of the range
2071  *
2072  * Remove all mappings in a range, split them as appropriate.
2073  * Returns 0 for success, error for failure.
2074  */
2075 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
2076                                 struct amdgpu_vm *vm,
2077                                 uint64_t saddr, uint64_t size)
2078 {
2079         struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
2080         LIST_HEAD(removed);
2081         uint64_t eaddr;
2082
2083         eaddr = saddr + size - 1;
2084         saddr /= AMDGPU_GPU_PAGE_SIZE;
2085         eaddr /= AMDGPU_GPU_PAGE_SIZE;
2086
2087         /* Allocate all the needed memory */
2088         before = kzalloc(sizeof(*before), GFP_KERNEL);
2089         if (!before)
2090                 return -ENOMEM;
2091         INIT_LIST_HEAD(&before->list);
2092
2093         after = kzalloc(sizeof(*after), GFP_KERNEL);
2094         if (!after) {
2095                 kfree(before);
2096                 return -ENOMEM;
2097         }
2098         INIT_LIST_HEAD(&after->list);
2099
2100         /* Now gather all removed mappings */
2101         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2102         while (tmp) {
2103                 /* Remember mapping split at the start */
2104                 if (tmp->start < saddr) {
2105                         before->start = tmp->start;
2106                         before->last = saddr - 1;
2107                         before->offset = tmp->offset;
2108                         before->flags = tmp->flags;
2109                         list_add(&before->list, &tmp->list);
2110                 }
2111
2112                 /* Remember mapping split at the end */
2113                 if (tmp->last > eaddr) {
2114                         after->start = eaddr + 1;
2115                         after->last = tmp->last;
2116                         after->offset = tmp->offset;
2117                         after->offset += after->start - tmp->start;
2118                         after->flags = tmp->flags;
2119                         list_add(&after->list, &tmp->list);
2120                 }
2121
2122                 list_del(&tmp->list);
2123                 list_add(&tmp->list, &removed);
2124
2125                 tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
2126         }
2127
2128         /* And free them up */
2129         list_for_each_entry_safe(tmp, next, &removed, list) {
2130                 amdgpu_vm_it_remove(tmp, &vm->va);
2131                 list_del(&tmp->list);
2132
2133                 if (tmp->start < saddr)
2134                     tmp->start = saddr;
2135                 if (tmp->last > eaddr)
2136                     tmp->last = eaddr;
2137
2138                 tmp->bo_va = NULL;
2139                 list_add(&tmp->list, &vm->freed);
2140                 trace_amdgpu_vm_bo_unmap(NULL, tmp);
2141         }
2142
2143         /* Insert partial mapping before the range */
2144         if (!list_empty(&before->list)) {
2145                 amdgpu_vm_it_insert(before, &vm->va);
2146                 if (before->flags & AMDGPU_PTE_PRT)
2147                         amdgpu_vm_prt_get(adev);
2148         } else {
2149                 kfree(before);
2150         }
2151
2152         /* Insert partial mapping after the range */
2153         if (!list_empty(&after->list)) {
2154                 amdgpu_vm_it_insert(after, &vm->va);
2155                 if (after->flags & AMDGPU_PTE_PRT)
2156                         amdgpu_vm_prt_get(adev);
2157         } else {
2158                 kfree(after);
2159         }
2160
2161         return 0;
2162 }
2163
2164 /**
2165  * amdgpu_vm_bo_lookup_mapping - find mapping by address
2166  *
2167  * @vm: the requested VM
2168  *
2169  * Find a mapping by it's address.
2170  */
2171 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
2172                                                          uint64_t addr)
2173 {
2174         return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
2175 }
2176
2177 /**
2178  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
2179  *
2180  * @adev: amdgpu_device pointer
2181  * @bo_va: requested bo_va
2182  *
2183  * Remove @bo_va->bo from the requested vm.
2184  *
2185  * Object have to be reserved!
2186  */
2187 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
2188                       struct amdgpu_bo_va *bo_va)
2189 {
2190         struct amdgpu_bo_va_mapping *mapping, *next;
2191         struct amdgpu_vm *vm = bo_va->base.vm;
2192
2193         list_del(&bo_va->base.bo_list);
2194
2195         spin_lock(&vm->moved_lock);
2196         list_del(&bo_va->base.vm_status);
2197         spin_unlock(&vm->moved_lock);
2198
2199         list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
2200                 list_del(&mapping->list);
2201                 amdgpu_vm_it_remove(mapping, &vm->va);
2202                 mapping->bo_va = NULL;
2203                 trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2204                 list_add(&mapping->list, &vm->freed);
2205         }
2206         list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
2207                 list_del(&mapping->list);
2208                 amdgpu_vm_it_remove(mapping, &vm->va);
2209                 amdgpu_vm_free_mapping(adev, vm, mapping,
2210                                        bo_va->last_pt_update);
2211         }
2212
2213         dma_fence_put(bo_va->last_pt_update);
2214         kfree(bo_va);
2215 }
2216
2217 /**
2218  * amdgpu_vm_bo_invalidate - mark the bo as invalid
2219  *
2220  * @adev: amdgpu_device pointer
2221  * @vm: requested vm
2222  * @bo: amdgpu buffer object
2223  *
2224  * Mark @bo as invalid.
2225  */
2226 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
2227                              struct amdgpu_bo *bo, bool evicted)
2228 {
2229         struct amdgpu_vm_bo_base *bo_base;
2230
2231         /* shadow bo doesn't have bo base, its validation needs its parent */
2232         if (bo->parent && bo->parent->shadow == bo)
2233                 bo = bo->parent;
2234
2235         list_for_each_entry(bo_base, &bo->va, bo_list) {
2236                 struct amdgpu_vm *vm = bo_base->vm;
2237                 bool was_moved = bo_base->moved;
2238
2239                 bo_base->moved = true;
2240                 if (evicted && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
2241                         if (bo->tbo.type == ttm_bo_type_kernel)
2242                                 list_move(&bo_base->vm_status, &vm->evicted);
2243                         else
2244                                 list_move_tail(&bo_base->vm_status,
2245                                                &vm->evicted);
2246                         continue;
2247                 }
2248
2249                 if (was_moved)
2250                         continue;
2251
2252                 if (bo->tbo.type == ttm_bo_type_kernel) {
2253                         list_move(&bo_base->vm_status, &vm->relocated);
2254                 } else {
2255                         spin_lock(&bo_base->vm->moved_lock);
2256                         list_move(&bo_base->vm_status, &vm->moved);
2257                         spin_unlock(&bo_base->vm->moved_lock);
2258                 }
2259         }
2260 }
2261
2262 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
2263 {
2264         /* Total bits covered by PD + PTs */
2265         unsigned bits = ilog2(vm_size) + 18;
2266
2267         /* Make sure the PD is 4K in size up to 8GB address space.
2268            Above that split equal between PD and PTs */
2269         if (vm_size <= 8)
2270                 return (bits - 9);
2271         else
2272                 return ((bits + 3) / 2);
2273 }
2274
2275 /**
2276  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
2277  *
2278  * @adev: amdgpu_device pointer
2279  * @vm_size: the default vm size if it's set auto
2280  */
2281 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t vm_size,
2282                            uint32_t fragment_size_default, unsigned max_level,
2283                            unsigned max_bits)
2284 {
2285         uint64_t tmp;
2286
2287         /* adjust vm size first */
2288         if (amdgpu_vm_size != -1) {
2289                 unsigned max_size = 1 << (max_bits - 30);
2290
2291                 vm_size = amdgpu_vm_size;
2292                 if (vm_size > max_size) {
2293                         dev_warn(adev->dev, "VM size (%d) too large, max is %u GB\n",
2294                                  amdgpu_vm_size, max_size);
2295                         vm_size = max_size;
2296                 }
2297         }
2298
2299         adev->vm_manager.max_pfn = (uint64_t)vm_size << 18;
2300
2301         tmp = roundup_pow_of_two(adev->vm_manager.max_pfn);
2302         if (amdgpu_vm_block_size != -1)
2303                 tmp >>= amdgpu_vm_block_size - 9;
2304         tmp = DIV_ROUND_UP(fls64(tmp) - 1, 9) - 1;
2305         adev->vm_manager.num_level = min(max_level, (unsigned)tmp);
2306         switch (adev->vm_manager.num_level) {
2307         case 3:
2308                 adev->vm_manager.root_level = AMDGPU_VM_PDB2;
2309                 break;
2310         case 2:
2311                 adev->vm_manager.root_level = AMDGPU_VM_PDB1;
2312                 break;
2313         case 1:
2314                 adev->vm_manager.root_level = AMDGPU_VM_PDB0;
2315                 break;
2316         default:
2317                 dev_err(adev->dev, "VMPT only supports 2~4+1 levels\n");
2318         }
2319         /* block size depends on vm size and hw setup*/
2320         if (amdgpu_vm_block_size != -1)
2321                 adev->vm_manager.block_size =
2322                         min((unsigned)amdgpu_vm_block_size, max_bits
2323                             - AMDGPU_GPU_PAGE_SHIFT
2324                             - 9 * adev->vm_manager.num_level);
2325         else if (adev->vm_manager.num_level > 1)
2326                 adev->vm_manager.block_size = 9;
2327         else
2328                 adev->vm_manager.block_size = amdgpu_vm_get_block_size(tmp);
2329
2330         if (amdgpu_vm_fragment_size == -1)
2331                 adev->vm_manager.fragment_size = fragment_size_default;
2332         else
2333                 adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
2334
2335         DRM_INFO("vm size is %u GB, %u levels, block size is %u-bit, fragment size is %u-bit\n",
2336                  vm_size, adev->vm_manager.num_level + 1,
2337                  adev->vm_manager.block_size,
2338                  adev->vm_manager.fragment_size);
2339 }
2340
2341 /**
2342  * amdgpu_vm_init - initialize a vm instance
2343  *
2344  * @adev: amdgpu_device pointer
2345  * @vm: requested vm
2346  * @vm_context: Indicates if it GFX or Compute context
2347  *
2348  * Init @vm fields.
2349  */
2350 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
2351                    int vm_context, unsigned int pasid)
2352 {
2353         struct amdgpu_bo_param bp;
2354         struct amdgpu_bo *root;
2355         const unsigned align = min(AMDGPU_VM_PTB_ALIGN_SIZE,
2356                 AMDGPU_VM_PTE_COUNT(adev) * 8);
2357         unsigned ring_instance;
2358         struct amdgpu_ring *ring;
2359         struct drm_sched_rq *rq;
2360         unsigned long size;
2361         uint64_t flags;
2362         int r, i;
2363
2364         vm->va = RB_ROOT_CACHED;
2365         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2366                 vm->reserved_vmid[i] = NULL;
2367         INIT_LIST_HEAD(&vm->evicted);
2368         INIT_LIST_HEAD(&vm->relocated);
2369         spin_lock_init(&vm->moved_lock);
2370         INIT_LIST_HEAD(&vm->moved);
2371         INIT_LIST_HEAD(&vm->freed);
2372
2373         /* create scheduler entity for page table updates */
2374
2375         ring_instance = atomic_inc_return(&adev->vm_manager.vm_pte_next_ring);
2376         ring_instance %= adev->vm_manager.vm_pte_num_rings;
2377         ring = adev->vm_manager.vm_pte_rings[ring_instance];
2378         rq = &ring->sched.sched_rq[DRM_SCHED_PRIORITY_KERNEL];
2379         r = drm_sched_entity_init(&ring->sched, &vm->entity,
2380                                   rq, NULL);
2381         if (r)
2382                 return r;
2383
2384         vm->pte_support_ats = false;
2385
2386         if (vm_context == AMDGPU_VM_CONTEXT_COMPUTE) {
2387                 vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2388                                                 AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2389
2390                 if (adev->asic_type == CHIP_RAVEN)
2391                         vm->pte_support_ats = true;
2392         } else {
2393                 vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2394                                                 AMDGPU_VM_USE_CPU_FOR_GFX);
2395         }
2396         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2397                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2398         WARN_ONCE((vm->use_cpu_for_update & !amdgpu_vm_is_large_bar(adev)),
2399                   "CPU update of VM recommended only for large BAR system\n");
2400         vm->last_update = NULL;
2401
2402         flags = AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
2403         if (vm->use_cpu_for_update)
2404                 flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
2405         else
2406                 flags |= AMDGPU_GEM_CREATE_SHADOW;
2407
2408         size = amdgpu_vm_bo_size(adev, adev->vm_manager.root_level);
2409         memset(&bp, 0, sizeof(bp));
2410         bp.size = size;
2411         bp.byte_align = align;
2412         bp.domain = AMDGPU_GEM_DOMAIN_VRAM;
2413         bp.flags = flags;
2414         bp.type = ttm_bo_type_kernel;
2415         bp.resv = NULL;
2416         r = amdgpu_bo_create(adev, &bp, &root);
2417         if (r)
2418                 goto error_free_sched_entity;
2419
2420         r = amdgpu_bo_reserve(root, true);
2421         if (r)
2422                 goto error_free_root;
2423
2424         r = amdgpu_vm_clear_bo(adev, vm, root,
2425                                adev->vm_manager.root_level,
2426                                vm->pte_support_ats);
2427         if (r)
2428                 goto error_unreserve;
2429
2430         amdgpu_vm_bo_base_init(&vm->root.base, vm, root);
2431         amdgpu_bo_unreserve(vm->root.base.bo);
2432
2433         if (pasid) {
2434                 unsigned long flags;
2435
2436                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2437                 r = idr_alloc(&adev->vm_manager.pasid_idr, vm, pasid, pasid + 1,
2438                               GFP_ATOMIC);
2439                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2440                 if (r < 0)
2441                         goto error_free_root;
2442
2443                 vm->pasid = pasid;
2444         }
2445
2446         INIT_KFIFO(vm->faults);
2447         vm->fault_credit = 16;
2448
2449         return 0;
2450
2451 error_unreserve:
2452         amdgpu_bo_unreserve(vm->root.base.bo);
2453
2454 error_free_root:
2455         amdgpu_bo_unref(&vm->root.base.bo->shadow);
2456         amdgpu_bo_unref(&vm->root.base.bo);
2457         vm->root.base.bo = NULL;
2458
2459 error_free_sched_entity:
2460         drm_sched_entity_fini(&ring->sched, &vm->entity);
2461
2462         return r;
2463 }
2464
2465 /**
2466  * amdgpu_vm_make_compute - Turn a GFX VM into a compute VM
2467  *
2468  * This only works on GFX VMs that don't have any BOs added and no
2469  * page tables allocated yet.
2470  *
2471  * Changes the following VM parameters:
2472  * - use_cpu_for_update
2473  * - pte_supports_ats
2474  * - pasid (old PASID is released, because compute manages its own PASIDs)
2475  *
2476  * Reinitializes the page directory to reflect the changed ATS
2477  * setting. May leave behind an unused shadow BO for the page
2478  * directory when switching from SDMA updates to CPU updates.
2479  *
2480  * Returns 0 for success, -errno for errors.
2481  */
2482 int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2483 {
2484         bool pte_support_ats = (adev->asic_type == CHIP_RAVEN);
2485         int r;
2486
2487         r = amdgpu_bo_reserve(vm->root.base.bo, true);
2488         if (r)
2489                 return r;
2490
2491         /* Sanity checks */
2492         if (!RB_EMPTY_ROOT(&vm->va.rb_root) || vm->root.entries) {
2493                 r = -EINVAL;
2494                 goto error;
2495         }
2496
2497         /* Check if PD needs to be reinitialized and do it before
2498          * changing any other state, in case it fails.
2499          */
2500         if (pte_support_ats != vm->pte_support_ats) {
2501                 r = amdgpu_vm_clear_bo(adev, vm, vm->root.base.bo,
2502                                adev->vm_manager.root_level,
2503                                pte_support_ats);
2504                 if (r)
2505                         goto error;
2506         }
2507
2508         /* Update VM state */
2509         vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2510                                     AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2511         vm->pte_support_ats = pte_support_ats;
2512         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2513                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2514         WARN_ONCE((vm->use_cpu_for_update & !amdgpu_vm_is_large_bar(adev)),
2515                   "CPU update of VM recommended only for large BAR system\n");
2516
2517         if (vm->pasid) {
2518                 unsigned long flags;
2519
2520                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2521                 idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2522                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2523
2524                 vm->pasid = 0;
2525         }
2526
2527 error:
2528         amdgpu_bo_unreserve(vm->root.base.bo);
2529         return r;
2530 }
2531
2532 /**
2533  * amdgpu_vm_free_levels - free PD/PT levels
2534  *
2535  * @adev: amdgpu device structure
2536  * @parent: PD/PT starting level to free
2537  * @level: level of parent structure
2538  *
2539  * Free the page directory or page table level and all sub levels.
2540  */
2541 static void amdgpu_vm_free_levels(struct amdgpu_device *adev,
2542                                   struct amdgpu_vm_pt *parent,
2543                                   unsigned level)
2544 {
2545         unsigned i, num_entries = amdgpu_vm_num_entries(adev, level);
2546
2547         if (parent->base.bo) {
2548                 list_del(&parent->base.bo_list);
2549                 list_del(&parent->base.vm_status);
2550                 amdgpu_bo_unref(&parent->base.bo->shadow);
2551                 amdgpu_bo_unref(&parent->base.bo);
2552         }
2553
2554         if (parent->entries)
2555                 for (i = 0; i < num_entries; i++)
2556                         amdgpu_vm_free_levels(adev, &parent->entries[i],
2557                                               level + 1);
2558
2559         kvfree(parent->entries);
2560 }
2561
2562 /**
2563  * amdgpu_vm_fini - tear down a vm instance
2564  *
2565  * @adev: amdgpu_device pointer
2566  * @vm: requested vm
2567  *
2568  * Tear down @vm.
2569  * Unbind the VM and remove all bos from the vm bo list
2570  */
2571 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2572 {
2573         struct amdgpu_bo_va_mapping *mapping, *tmp;
2574         bool prt_fini_needed = !!adev->gmc.gmc_funcs->set_prt;
2575         struct amdgpu_bo *root;
2576         u64 fault;
2577         int i, r;
2578
2579         amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
2580
2581         /* Clear pending page faults from IH when the VM is destroyed */
2582         while (kfifo_get(&vm->faults, &fault))
2583                 amdgpu_ih_clear_fault(adev, fault);
2584
2585         if (vm->pasid) {
2586                 unsigned long flags;
2587
2588                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2589                 idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2590                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2591         }
2592
2593         drm_sched_entity_fini(vm->entity.sched, &vm->entity);
2594
2595         if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
2596                 dev_err(adev->dev, "still active bo inside vm\n");
2597         }
2598         rbtree_postorder_for_each_entry_safe(mapping, tmp,
2599                                              &vm->va.rb_root, rb) {
2600                 list_del(&mapping->list);
2601                 amdgpu_vm_it_remove(mapping, &vm->va);
2602                 kfree(mapping);
2603         }
2604         list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2605                 if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
2606                         amdgpu_vm_prt_fini(adev, vm);
2607                         prt_fini_needed = false;
2608                 }
2609
2610                 list_del(&mapping->list);
2611                 amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2612         }
2613
2614         root = amdgpu_bo_ref(vm->root.base.bo);
2615         r = amdgpu_bo_reserve(root, true);
2616         if (r) {
2617                 dev_err(adev->dev, "Leaking page tables because BO reservation failed\n");
2618         } else {
2619                 amdgpu_vm_free_levels(adev, &vm->root,
2620                                       adev->vm_manager.root_level);
2621                 amdgpu_bo_unreserve(root);
2622         }
2623         amdgpu_bo_unref(&root);
2624         dma_fence_put(vm->last_update);
2625         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2626                 amdgpu_vmid_free_reserved(adev, vm, i);
2627 }
2628
2629 /**
2630  * amdgpu_vm_pasid_fault_credit - Check fault credit for given PASID
2631  *
2632  * @adev: amdgpu_device pointer
2633  * @pasid: PASID do identify the VM
2634  *
2635  * This function is expected to be called in interrupt context. Returns
2636  * true if there was fault credit, false otherwise
2637  */
2638 bool amdgpu_vm_pasid_fault_credit(struct amdgpu_device *adev,
2639                                   unsigned int pasid)
2640 {
2641         struct amdgpu_vm *vm;
2642
2643         spin_lock(&adev->vm_manager.pasid_lock);
2644         vm = idr_find(&adev->vm_manager.pasid_idr, pasid);
2645         if (!vm) {
2646                 /* VM not found, can't track fault credit */
2647                 spin_unlock(&adev->vm_manager.pasid_lock);
2648                 return true;
2649         }
2650
2651         /* No lock needed. only accessed by IRQ handler */
2652         if (!vm->fault_credit) {
2653                 /* Too many faults in this VM */
2654                 spin_unlock(&adev->vm_manager.pasid_lock);
2655                 return false;
2656         }
2657
2658         vm->fault_credit--;
2659         spin_unlock(&adev->vm_manager.pasid_lock);
2660         return true;
2661 }
2662
2663 /**
2664  * amdgpu_vm_manager_init - init the VM manager
2665  *
2666  * @adev: amdgpu_device pointer
2667  *
2668  * Initialize the VM manager structures
2669  */
2670 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
2671 {
2672         unsigned i;
2673
2674         amdgpu_vmid_mgr_init(adev);
2675
2676         adev->vm_manager.fence_context =
2677                 dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2678         for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
2679                 adev->vm_manager.seqno[i] = 0;
2680
2681         atomic_set(&adev->vm_manager.vm_pte_next_ring, 0);
2682         spin_lock_init(&adev->vm_manager.prt_lock);
2683         atomic_set(&adev->vm_manager.num_prt_users, 0);
2684
2685         /* If not overridden by the user, by default, only in large BAR systems
2686          * Compute VM tables will be updated by CPU
2687          */
2688 #ifdef CONFIG_X86_64
2689         if (amdgpu_vm_update_mode == -1) {
2690                 if (amdgpu_vm_is_large_bar(adev))
2691                         adev->vm_manager.vm_update_mode =
2692                                 AMDGPU_VM_USE_CPU_FOR_COMPUTE;
2693                 else
2694                         adev->vm_manager.vm_update_mode = 0;
2695         } else
2696                 adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
2697 #else
2698         adev->vm_manager.vm_update_mode = 0;
2699 #endif
2700
2701         idr_init(&adev->vm_manager.pasid_idr);
2702         spin_lock_init(&adev->vm_manager.pasid_lock);
2703 }
2704
2705 /**
2706  * amdgpu_vm_manager_fini - cleanup VM manager
2707  *
2708  * @adev: amdgpu_device pointer
2709  *
2710  * Cleanup the VM manager and free resources.
2711  */
2712 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
2713 {
2714         WARN_ON(!idr_is_empty(&adev->vm_manager.pasid_idr));
2715         idr_destroy(&adev->vm_manager.pasid_idr);
2716
2717         amdgpu_vmid_mgr_fini(adev);
2718 }
2719
2720 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
2721 {
2722         union drm_amdgpu_vm *args = data;
2723         struct amdgpu_device *adev = dev->dev_private;
2724         struct amdgpu_fpriv *fpriv = filp->driver_priv;
2725         int r;
2726
2727         switch (args->in.op) {
2728         case AMDGPU_VM_OP_RESERVE_VMID:
2729                 /* current, we only have requirement to reserve vmid from gfxhub */
2730                 r = amdgpu_vmid_alloc_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
2731                 if (r)
2732                         return r;
2733                 break;
2734         case AMDGPU_VM_OP_UNRESERVE_VMID:
2735                 amdgpu_vmid_free_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
2736                 break;
2737         default:
2738                 return -EINVAL;
2739         }
2740
2741         return 0;
2742 }
This page took 0.198912 seconds and 4 git commands to generate.