]> Git Repo - linux.git/blob - drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c
drm/amdgpu: kmap PDs/PTs in amdgpu_vm_update_directories
[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 (list_empty(&entry->base.vm_status))
906                         list_add(&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                 list_del_init(&bo_base->vm_status);
968
969                 bo = bo_base->bo->parent;
970                 if (!bo)
971                         continue;
972
973                 parent = list_first_entry(&bo->va, struct amdgpu_vm_bo_base,
974                                           bo_list);
975                 pt = container_of(parent, struct amdgpu_vm_pt, base);
976                 entry = container_of(bo_base, struct amdgpu_vm_pt, base);
977
978                 amdgpu_vm_update_pde(&params, vm, pt, entry);
979
980                 if (!vm->use_cpu_for_update &&
981                     (ndw - params.ib->length_dw) < 32)
982                         break;
983         }
984
985         if (vm->use_cpu_for_update) {
986                 /* Flush HDP */
987                 mb();
988                 amdgpu_asic_flush_hdp(adev, NULL);
989         } else if (params.ib->length_dw == 0) {
990                 amdgpu_job_free(job);
991         } else {
992                 struct amdgpu_bo *root = vm->root.base.bo;
993                 struct amdgpu_ring *ring;
994                 struct dma_fence *fence;
995
996                 ring = container_of(vm->entity.sched, struct amdgpu_ring,
997                                     sched);
998
999                 amdgpu_ring_pad_ib(ring, params.ib);
1000                 amdgpu_sync_resv(adev, &job->sync, root->tbo.resv,
1001                                  AMDGPU_FENCE_OWNER_VM, false);
1002                 WARN_ON(params.ib->length_dw > ndw);
1003                 r = amdgpu_job_submit(job, ring, &vm->entity,
1004                                       AMDGPU_FENCE_OWNER_VM, &fence);
1005                 if (r)
1006                         goto error;
1007
1008                 amdgpu_bo_fence(root, fence, true);
1009                 dma_fence_put(vm->last_update);
1010                 vm->last_update = fence;
1011         }
1012
1013         if (!list_empty(&vm->relocated))
1014                 goto restart;
1015
1016         return 0;
1017
1018 error:
1019         amdgpu_vm_invalidate_level(adev, vm, &vm->root,
1020                                    adev->vm_manager.root_level);
1021         amdgpu_job_free(job);
1022         return r;
1023 }
1024
1025 /**
1026  * amdgpu_vm_find_entry - find the entry for an address
1027  *
1028  * @p: see amdgpu_pte_update_params definition
1029  * @addr: virtual address in question
1030  * @entry: resulting entry or NULL
1031  * @parent: parent entry
1032  *
1033  * Find the vm_pt entry and it's parent for the given address.
1034  */
1035 void amdgpu_vm_get_entry(struct amdgpu_pte_update_params *p, uint64_t addr,
1036                          struct amdgpu_vm_pt **entry,
1037                          struct amdgpu_vm_pt **parent)
1038 {
1039         unsigned level = p->adev->vm_manager.root_level;
1040
1041         *parent = NULL;
1042         *entry = &p->vm->root;
1043         while ((*entry)->entries) {
1044                 unsigned shift = amdgpu_vm_level_shift(p->adev, level++);
1045
1046                 *parent = *entry;
1047                 *entry = &(*entry)->entries[addr >> shift];
1048                 addr &= (1ULL << shift) - 1;
1049         }
1050
1051         if (level != AMDGPU_VM_PTB)
1052                 *entry = NULL;
1053 }
1054
1055 /**
1056  * amdgpu_vm_handle_huge_pages - handle updating the PD with huge pages
1057  *
1058  * @p: see amdgpu_pte_update_params definition
1059  * @entry: vm_pt entry to check
1060  * @parent: parent entry
1061  * @nptes: number of PTEs updated with this operation
1062  * @dst: destination address where the PTEs should point to
1063  * @flags: access flags fro the PTEs
1064  *
1065  * Check if we can update the PD with a huge page.
1066  */
1067 static void amdgpu_vm_handle_huge_pages(struct amdgpu_pte_update_params *p,
1068                                         struct amdgpu_vm_pt *entry,
1069                                         struct amdgpu_vm_pt *parent,
1070                                         unsigned nptes, uint64_t dst,
1071                                         uint64_t flags)
1072 {
1073         uint64_t pde;
1074
1075         /* In the case of a mixed PT the PDE must point to it*/
1076         if (p->adev->asic_type >= CHIP_VEGA10 && !p->src &&
1077             nptes == AMDGPU_VM_PTE_COUNT(p->adev)) {
1078                 /* Set the huge page flag to stop scanning at this PDE */
1079                 flags |= AMDGPU_PDE_PTE;
1080         }
1081
1082         if (!(flags & AMDGPU_PDE_PTE)) {
1083                 if (entry->huge) {
1084                         /* Add the entry to the relocated list to update it. */
1085                         entry->huge = false;
1086                         list_move(&entry->base.vm_status, &p->vm->relocated);
1087                 }
1088                 return;
1089         }
1090
1091         entry->huge = true;
1092         amdgpu_gmc_get_vm_pde(p->adev, AMDGPU_VM_PDB0, &dst, &flags);
1093
1094         pde = (entry - parent->entries) * 8;
1095         if (parent->base.bo->shadow)
1096                 p->func(p, parent->base.bo->shadow, pde, dst, 1, 0, flags);
1097         p->func(p, parent->base.bo, pde, dst, 1, 0, flags);
1098 }
1099
1100 /**
1101  * amdgpu_vm_update_ptes - make sure that page tables are valid
1102  *
1103  * @params: see amdgpu_pte_update_params definition
1104  * @vm: requested vm
1105  * @start: start of GPU address range
1106  * @end: end of GPU address range
1107  * @dst: destination address to map to, the next dst inside the function
1108  * @flags: mapping flags
1109  *
1110  * Update the page tables in the range @start - @end.
1111  * Returns 0 for success, -EINVAL for failure.
1112  */
1113 static int amdgpu_vm_update_ptes(struct amdgpu_pte_update_params *params,
1114                                   uint64_t start, uint64_t end,
1115                                   uint64_t dst, uint64_t flags)
1116 {
1117         struct amdgpu_device *adev = params->adev;
1118         const uint64_t mask = AMDGPU_VM_PTE_COUNT(adev) - 1;
1119
1120         uint64_t addr, pe_start;
1121         struct amdgpu_bo *pt;
1122         unsigned nptes;
1123
1124         /* walk over the address space and update the page tables */
1125         for (addr = start; addr < end; addr += nptes,
1126              dst += nptes * AMDGPU_GPU_PAGE_SIZE) {
1127                 struct amdgpu_vm_pt *entry, *parent;
1128
1129                 amdgpu_vm_get_entry(params, addr, &entry, &parent);
1130                 if (!entry)
1131                         return -ENOENT;
1132
1133                 if ((addr & ~mask) == (end & ~mask))
1134                         nptes = end - addr;
1135                 else
1136                         nptes = AMDGPU_VM_PTE_COUNT(adev) - (addr & mask);
1137
1138                 amdgpu_vm_handle_huge_pages(params, entry, parent,
1139                                             nptes, dst, flags);
1140                 /* We don't need to update PTEs for huge pages */
1141                 if (entry->huge)
1142                         continue;
1143
1144                 pt = entry->base.bo;
1145                 pe_start = (addr & mask) * 8;
1146                 if (pt->shadow)
1147                         params->func(params, pt->shadow, pe_start, dst, nptes,
1148                                      AMDGPU_GPU_PAGE_SIZE, flags);
1149                 params->func(params, pt, pe_start, dst, nptes,
1150                              AMDGPU_GPU_PAGE_SIZE, flags);
1151         }
1152
1153         return 0;
1154 }
1155
1156 /*
1157  * amdgpu_vm_frag_ptes - add fragment information to PTEs
1158  *
1159  * @params: see amdgpu_pte_update_params definition
1160  * @vm: requested vm
1161  * @start: first PTE to handle
1162  * @end: last PTE to handle
1163  * @dst: addr those PTEs should point to
1164  * @flags: hw mapping flags
1165  * Returns 0 for success, -EINVAL for failure.
1166  */
1167 static int amdgpu_vm_frag_ptes(struct amdgpu_pte_update_params  *params,
1168                                 uint64_t start, uint64_t end,
1169                                 uint64_t dst, uint64_t flags)
1170 {
1171         /**
1172          * The MC L1 TLB supports variable sized pages, based on a fragment
1173          * field in the PTE. When this field is set to a non-zero value, page
1174          * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
1175          * flags are considered valid for all PTEs within the fragment range
1176          * and corresponding mappings are assumed to be physically contiguous.
1177          *
1178          * The L1 TLB can store a single PTE for the whole fragment,
1179          * significantly increasing the space available for translation
1180          * caching. This leads to large improvements in throughput when the
1181          * TLB is under pressure.
1182          *
1183          * The L2 TLB distributes small and large fragments into two
1184          * asymmetric partitions. The large fragment cache is significantly
1185          * larger. Thus, we try to use large fragments wherever possible.
1186          * Userspace can support this by aligning virtual base address and
1187          * allocation size to the fragment size.
1188          */
1189         unsigned max_frag = params->adev->vm_manager.fragment_size;
1190         int r;
1191
1192         /* system pages are non continuously */
1193         if (params->src || !(flags & AMDGPU_PTE_VALID))
1194                 return amdgpu_vm_update_ptes(params, start, end, dst, flags);
1195
1196         while (start != end) {
1197                 uint64_t frag_flags, frag_end;
1198                 unsigned frag;
1199
1200                 /* This intentionally wraps around if no bit is set */
1201                 frag = min((unsigned)ffs(start) - 1,
1202                            (unsigned)fls64(end - start) - 1);
1203                 if (frag >= max_frag) {
1204                         frag_flags = AMDGPU_PTE_FRAG(max_frag);
1205                         frag_end = end & ~((1ULL << max_frag) - 1);
1206                 } else {
1207                         frag_flags = AMDGPU_PTE_FRAG(frag);
1208                         frag_end = start + (1 << frag);
1209                 }
1210
1211                 r = amdgpu_vm_update_ptes(params, start, frag_end, dst,
1212                                           flags | frag_flags);
1213                 if (r)
1214                         return r;
1215
1216                 dst += (frag_end - start) * AMDGPU_GPU_PAGE_SIZE;
1217                 start = frag_end;
1218         }
1219
1220         return 0;
1221 }
1222
1223 /**
1224  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
1225  *
1226  * @adev: amdgpu_device pointer
1227  * @exclusive: fence we need to sync to
1228  * @pages_addr: DMA addresses to use for mapping
1229  * @vm: requested vm
1230  * @start: start of mapped range
1231  * @last: last mapped entry
1232  * @flags: flags for the entries
1233  * @addr: addr to set the area to
1234  * @fence: optional resulting fence
1235  *
1236  * Fill in the page table entries between @start and @last.
1237  * Returns 0 for success, -EINVAL for failure.
1238  */
1239 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
1240                                        struct dma_fence *exclusive,
1241                                        dma_addr_t *pages_addr,
1242                                        struct amdgpu_vm *vm,
1243                                        uint64_t start, uint64_t last,
1244                                        uint64_t flags, uint64_t addr,
1245                                        struct dma_fence **fence)
1246 {
1247         struct amdgpu_ring *ring;
1248         void *owner = AMDGPU_FENCE_OWNER_VM;
1249         unsigned nptes, ncmds, ndw;
1250         struct amdgpu_job *job;
1251         struct amdgpu_pte_update_params params;
1252         struct dma_fence *f = NULL;
1253         int r;
1254
1255         memset(&params, 0, sizeof(params));
1256         params.adev = adev;
1257         params.vm = vm;
1258
1259         /* sync to everything on unmapping */
1260         if (!(flags & AMDGPU_PTE_VALID))
1261                 owner = AMDGPU_FENCE_OWNER_UNDEFINED;
1262
1263         if (vm->use_cpu_for_update) {
1264                 /* params.src is used as flag to indicate system Memory */
1265                 if (pages_addr)
1266                         params.src = ~0;
1267
1268                 /* Wait for PT BOs to be free. PTs share the same resv. object
1269                  * as the root PD BO
1270                  */
1271                 r = amdgpu_vm_wait_pd(adev, vm, owner);
1272                 if (unlikely(r))
1273                         return r;
1274
1275                 params.func = amdgpu_vm_cpu_set_ptes;
1276                 params.pages_addr = pages_addr;
1277                 return amdgpu_vm_frag_ptes(&params, start, last + 1,
1278                                            addr, flags);
1279         }
1280
1281         ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
1282
1283         nptes = last - start + 1;
1284
1285         /*
1286          * reserve space for two commands every (1 << BLOCK_SIZE)
1287          *  entries or 2k dwords (whatever is smaller)
1288          *
1289          * The second command is for the shadow pagetables.
1290          */
1291         if (vm->root.base.bo->shadow)
1292                 ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1) * 2;
1293         else
1294                 ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1);
1295
1296         /* padding, etc. */
1297         ndw = 64;
1298
1299         if (pages_addr) {
1300                 /* copy commands needed */
1301                 ndw += ncmds * adev->vm_manager.vm_pte_funcs->copy_pte_num_dw;
1302
1303                 /* and also PTEs */
1304                 ndw += nptes * 2;
1305
1306                 params.func = amdgpu_vm_do_copy_ptes;
1307
1308         } else {
1309                 /* set page commands needed */
1310                 ndw += ncmds * 10;
1311
1312                 /* extra commands for begin/end fragments */
1313                 ndw += 2 * 10 * adev->vm_manager.fragment_size;
1314
1315                 params.func = amdgpu_vm_do_set_ptes;
1316         }
1317
1318         r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1319         if (r)
1320                 return r;
1321
1322         params.ib = &job->ibs[0];
1323
1324         if (pages_addr) {
1325                 uint64_t *pte;
1326                 unsigned i;
1327
1328                 /* Put the PTEs at the end of the IB. */
1329                 i = ndw - nptes * 2;
1330                 pte= (uint64_t *)&(job->ibs->ptr[i]);
1331                 params.src = job->ibs->gpu_addr + i * 4;
1332
1333                 for (i = 0; i < nptes; ++i) {
1334                         pte[i] = amdgpu_vm_map_gart(pages_addr, addr + i *
1335                                                     AMDGPU_GPU_PAGE_SIZE);
1336                         pte[i] |= flags;
1337                 }
1338                 addr = 0;
1339         }
1340
1341         r = amdgpu_sync_fence(adev, &job->sync, exclusive, false);
1342         if (r)
1343                 goto error_free;
1344
1345         r = amdgpu_sync_resv(adev, &job->sync, vm->root.base.bo->tbo.resv,
1346                              owner, false);
1347         if (r)
1348                 goto error_free;
1349
1350         r = reservation_object_reserve_shared(vm->root.base.bo->tbo.resv);
1351         if (r)
1352                 goto error_free;
1353
1354         r = amdgpu_vm_frag_ptes(&params, start, last + 1, addr, flags);
1355         if (r)
1356                 goto error_free;
1357
1358         amdgpu_ring_pad_ib(ring, params.ib);
1359         WARN_ON(params.ib->length_dw > ndw);
1360         r = amdgpu_job_submit(job, ring, &vm->entity,
1361                               AMDGPU_FENCE_OWNER_VM, &f);
1362         if (r)
1363                 goto error_free;
1364
1365         amdgpu_bo_fence(vm->root.base.bo, f, true);
1366         dma_fence_put(*fence);
1367         *fence = f;
1368         return 0;
1369
1370 error_free:
1371         amdgpu_job_free(job);
1372         return r;
1373 }
1374
1375 /**
1376  * amdgpu_vm_bo_split_mapping - split a mapping into smaller chunks
1377  *
1378  * @adev: amdgpu_device pointer
1379  * @exclusive: fence we need to sync to
1380  * @pages_addr: DMA addresses to use for mapping
1381  * @vm: requested vm
1382  * @mapping: mapped range and flags to use for the update
1383  * @flags: HW flags for the mapping
1384  * @nodes: array of drm_mm_nodes with the MC addresses
1385  * @fence: optional resulting fence
1386  *
1387  * Split the mapping into smaller chunks so that each update fits
1388  * into a SDMA IB.
1389  * Returns 0 for success, -EINVAL for failure.
1390  */
1391 static int amdgpu_vm_bo_split_mapping(struct amdgpu_device *adev,
1392                                       struct dma_fence *exclusive,
1393                                       dma_addr_t *pages_addr,
1394                                       struct amdgpu_vm *vm,
1395                                       struct amdgpu_bo_va_mapping *mapping,
1396                                       uint64_t flags,
1397                                       struct drm_mm_node *nodes,
1398                                       struct dma_fence **fence)
1399 {
1400         unsigned min_linear_pages = 1 << adev->vm_manager.fragment_size;
1401         uint64_t pfn, start = mapping->start;
1402         int r;
1403
1404         /* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1405          * but in case of something, we filter the flags in first place
1406          */
1407         if (!(mapping->flags & AMDGPU_PTE_READABLE))
1408                 flags &= ~AMDGPU_PTE_READABLE;
1409         if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1410                 flags &= ~AMDGPU_PTE_WRITEABLE;
1411
1412         flags &= ~AMDGPU_PTE_EXECUTABLE;
1413         flags |= mapping->flags & AMDGPU_PTE_EXECUTABLE;
1414
1415         flags &= ~AMDGPU_PTE_MTYPE_MASK;
1416         flags |= (mapping->flags & AMDGPU_PTE_MTYPE_MASK);
1417
1418         if ((mapping->flags & AMDGPU_PTE_PRT) &&
1419             (adev->asic_type >= CHIP_VEGA10)) {
1420                 flags |= AMDGPU_PTE_PRT;
1421                 flags &= ~AMDGPU_PTE_VALID;
1422         }
1423
1424         trace_amdgpu_vm_bo_update(mapping);
1425
1426         pfn = mapping->offset >> PAGE_SHIFT;
1427         if (nodes) {
1428                 while (pfn >= nodes->size) {
1429                         pfn -= nodes->size;
1430                         ++nodes;
1431                 }
1432         }
1433
1434         do {
1435                 dma_addr_t *dma_addr = NULL;
1436                 uint64_t max_entries;
1437                 uint64_t addr, last;
1438
1439                 if (nodes) {
1440                         addr = nodes->start << PAGE_SHIFT;
1441                         max_entries = (nodes->size - pfn) *
1442                                 (PAGE_SIZE / AMDGPU_GPU_PAGE_SIZE);
1443                 } else {
1444                         addr = 0;
1445                         max_entries = S64_MAX;
1446                 }
1447
1448                 if (pages_addr) {
1449                         uint64_t count;
1450
1451                         max_entries = min(max_entries, 16ull * 1024ull);
1452                         for (count = 1; count < max_entries; ++count) {
1453                                 uint64_t idx = pfn + count;
1454
1455                                 if (pages_addr[idx] !=
1456                                     (pages_addr[idx - 1] + PAGE_SIZE))
1457                                         break;
1458                         }
1459
1460                         if (count < min_linear_pages) {
1461                                 addr = pfn << PAGE_SHIFT;
1462                                 dma_addr = pages_addr;
1463                         } else {
1464                                 addr = pages_addr[pfn];
1465                                 max_entries = count;
1466                         }
1467
1468                 } else if (flags & AMDGPU_PTE_VALID) {
1469                         addr += adev->vm_manager.vram_base_offset;
1470                         addr += pfn << PAGE_SHIFT;
1471                 }
1472
1473                 last = min((uint64_t)mapping->last, start + max_entries - 1);
1474                 r = amdgpu_vm_bo_update_mapping(adev, exclusive, dma_addr, vm,
1475                                                 start, last, flags, addr,
1476                                                 fence);
1477                 if (r)
1478                         return r;
1479
1480                 pfn += last - start + 1;
1481                 if (nodes && nodes->size == pfn) {
1482                         pfn = 0;
1483                         ++nodes;
1484                 }
1485                 start = last + 1;
1486
1487         } while (unlikely(start != mapping->last + 1));
1488
1489         return 0;
1490 }
1491
1492 /**
1493  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1494  *
1495  * @adev: amdgpu_device pointer
1496  * @bo_va: requested BO and VM object
1497  * @clear: if true clear the entries
1498  *
1499  * Fill in the page table entries for @bo_va.
1500  * Returns 0 for success, -EINVAL for failure.
1501  */
1502 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
1503                         struct amdgpu_bo_va *bo_va,
1504                         bool clear)
1505 {
1506         struct amdgpu_bo *bo = bo_va->base.bo;
1507         struct amdgpu_vm *vm = bo_va->base.vm;
1508         struct amdgpu_bo_va_mapping *mapping;
1509         dma_addr_t *pages_addr = NULL;
1510         struct ttm_mem_reg *mem;
1511         struct drm_mm_node *nodes;
1512         struct dma_fence *exclusive, **last_update;
1513         uint64_t flags;
1514         int r;
1515
1516         if (clear || !bo_va->base.bo) {
1517                 mem = NULL;
1518                 nodes = NULL;
1519                 exclusive = NULL;
1520         } else {
1521                 struct ttm_dma_tt *ttm;
1522
1523                 mem = &bo_va->base.bo->tbo.mem;
1524                 nodes = mem->mm_node;
1525                 if (mem->mem_type == TTM_PL_TT) {
1526                         ttm = container_of(bo_va->base.bo->tbo.ttm,
1527                                            struct ttm_dma_tt, ttm);
1528                         pages_addr = ttm->dma_address;
1529                 }
1530                 exclusive = reservation_object_get_excl(bo->tbo.resv);
1531         }
1532
1533         if (bo)
1534                 flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
1535         else
1536                 flags = 0x0;
1537
1538         if (clear || (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv))
1539                 last_update = &vm->last_update;
1540         else
1541                 last_update = &bo_va->last_pt_update;
1542
1543         if (!clear && bo_va->base.moved) {
1544                 bo_va->base.moved = false;
1545                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1546
1547         } else if (bo_va->cleared != clear) {
1548                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1549         }
1550
1551         list_for_each_entry(mapping, &bo_va->invalids, list) {
1552                 r = amdgpu_vm_bo_split_mapping(adev, exclusive, pages_addr, vm,
1553                                                mapping, flags, nodes,
1554                                                last_update);
1555                 if (r)
1556                         return r;
1557         }
1558
1559         if (vm->use_cpu_for_update) {
1560                 /* Flush HDP */
1561                 mb();
1562                 amdgpu_asic_flush_hdp(adev, NULL);
1563         }
1564
1565         spin_lock(&vm->moved_lock);
1566         list_del_init(&bo_va->base.vm_status);
1567         spin_unlock(&vm->moved_lock);
1568
1569         /* If the BO is not in its preferred location add it back to
1570          * the evicted list so that it gets validated again on the
1571          * next command submission.
1572          */
1573         if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv &&
1574             !(bo->preferred_domains &
1575             amdgpu_mem_type_to_domain(bo->tbo.mem.mem_type)))
1576                 list_add_tail(&bo_va->base.vm_status, &vm->evicted);
1577
1578         list_splice_init(&bo_va->invalids, &bo_va->valids);
1579         bo_va->cleared = clear;
1580
1581         if (trace_amdgpu_vm_bo_mapping_enabled()) {
1582                 list_for_each_entry(mapping, &bo_va->valids, list)
1583                         trace_amdgpu_vm_bo_mapping(mapping);
1584         }
1585
1586         return 0;
1587 }
1588
1589 /**
1590  * amdgpu_vm_update_prt_state - update the global PRT state
1591  */
1592 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1593 {
1594         unsigned long flags;
1595         bool enable;
1596
1597         spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1598         enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1599         adev->gmc.gmc_funcs->set_prt(adev, enable);
1600         spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1601 }
1602
1603 /**
1604  * amdgpu_vm_prt_get - add a PRT user
1605  */
1606 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1607 {
1608         if (!adev->gmc.gmc_funcs->set_prt)
1609                 return;
1610
1611         if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1612                 amdgpu_vm_update_prt_state(adev);
1613 }
1614
1615 /**
1616  * amdgpu_vm_prt_put - drop a PRT user
1617  */
1618 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1619 {
1620         if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1621                 amdgpu_vm_update_prt_state(adev);
1622 }
1623
1624 /**
1625  * amdgpu_vm_prt_cb - callback for updating the PRT status
1626  */
1627 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1628 {
1629         struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1630
1631         amdgpu_vm_prt_put(cb->adev);
1632         kfree(cb);
1633 }
1634
1635 /**
1636  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1637  */
1638 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1639                                  struct dma_fence *fence)
1640 {
1641         struct amdgpu_prt_cb *cb;
1642
1643         if (!adev->gmc.gmc_funcs->set_prt)
1644                 return;
1645
1646         cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
1647         if (!cb) {
1648                 /* Last resort when we are OOM */
1649                 if (fence)
1650                         dma_fence_wait(fence, false);
1651
1652                 amdgpu_vm_prt_put(adev);
1653         } else {
1654                 cb->adev = adev;
1655                 if (!fence || dma_fence_add_callback(fence, &cb->cb,
1656                                                      amdgpu_vm_prt_cb))
1657                         amdgpu_vm_prt_cb(fence, &cb->cb);
1658         }
1659 }
1660
1661 /**
1662  * amdgpu_vm_free_mapping - free a mapping
1663  *
1664  * @adev: amdgpu_device pointer
1665  * @vm: requested vm
1666  * @mapping: mapping to be freed
1667  * @fence: fence of the unmap operation
1668  *
1669  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1670  */
1671 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1672                                    struct amdgpu_vm *vm,
1673                                    struct amdgpu_bo_va_mapping *mapping,
1674                                    struct dma_fence *fence)
1675 {
1676         if (mapping->flags & AMDGPU_PTE_PRT)
1677                 amdgpu_vm_add_prt_cb(adev, fence);
1678         kfree(mapping);
1679 }
1680
1681 /**
1682  * amdgpu_vm_prt_fini - finish all prt mappings
1683  *
1684  * @adev: amdgpu_device pointer
1685  * @vm: requested vm
1686  *
1687  * Register a cleanup callback to disable PRT support after VM dies.
1688  */
1689 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1690 {
1691         struct reservation_object *resv = vm->root.base.bo->tbo.resv;
1692         struct dma_fence *excl, **shared;
1693         unsigned i, shared_count;
1694         int r;
1695
1696         r = reservation_object_get_fences_rcu(resv, &excl,
1697                                               &shared_count, &shared);
1698         if (r) {
1699                 /* Not enough memory to grab the fence list, as last resort
1700                  * block for all the fences to complete.
1701                  */
1702                 reservation_object_wait_timeout_rcu(resv, true, false,
1703                                                     MAX_SCHEDULE_TIMEOUT);
1704                 return;
1705         }
1706
1707         /* Add a callback for each fence in the reservation object */
1708         amdgpu_vm_prt_get(adev);
1709         amdgpu_vm_add_prt_cb(adev, excl);
1710
1711         for (i = 0; i < shared_count; ++i) {
1712                 amdgpu_vm_prt_get(adev);
1713                 amdgpu_vm_add_prt_cb(adev, shared[i]);
1714         }
1715
1716         kfree(shared);
1717 }
1718
1719 /**
1720  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1721  *
1722  * @adev: amdgpu_device pointer
1723  * @vm: requested vm
1724  * @fence: optional resulting fence (unchanged if no work needed to be done
1725  * or if an error occurred)
1726  *
1727  * Make sure all freed BOs are cleared in the PT.
1728  * Returns 0 for success.
1729  *
1730  * PTs have to be reserved and mutex must be locked!
1731  */
1732 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
1733                           struct amdgpu_vm *vm,
1734                           struct dma_fence **fence)
1735 {
1736         struct amdgpu_bo_va_mapping *mapping;
1737         uint64_t init_pte_value = 0;
1738         struct dma_fence *f = NULL;
1739         int r;
1740
1741         while (!list_empty(&vm->freed)) {
1742                 mapping = list_first_entry(&vm->freed,
1743                         struct amdgpu_bo_va_mapping, list);
1744                 list_del(&mapping->list);
1745
1746                 if (vm->pte_support_ats && mapping->start < AMDGPU_VA_HOLE_START)
1747                         init_pte_value = AMDGPU_PTE_DEFAULT_ATC;
1748
1749                 r = amdgpu_vm_bo_update_mapping(adev, NULL, NULL, vm,
1750                                                 mapping->start, mapping->last,
1751                                                 init_pte_value, 0, &f);
1752                 amdgpu_vm_free_mapping(adev, vm, mapping, f);
1753                 if (r) {
1754                         dma_fence_put(f);
1755                         return r;
1756                 }
1757         }
1758
1759         if (fence && f) {
1760                 dma_fence_put(*fence);
1761                 *fence = f;
1762         } else {
1763                 dma_fence_put(f);
1764         }
1765
1766         return 0;
1767
1768 }
1769
1770 /**
1771  * amdgpu_vm_handle_moved - handle moved BOs in the PT
1772  *
1773  * @adev: amdgpu_device pointer
1774  * @vm: requested vm
1775  * @sync: sync object to add fences to
1776  *
1777  * Make sure all BOs which are moved are updated in the PTs.
1778  * Returns 0 for success.
1779  *
1780  * PTs have to be reserved!
1781  */
1782 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
1783                            struct amdgpu_vm *vm)
1784 {
1785         struct amdgpu_bo_va *bo_va, *tmp;
1786         struct list_head moved;
1787         bool clear;
1788         int r;
1789
1790         INIT_LIST_HEAD(&moved);
1791         spin_lock(&vm->moved_lock);
1792         list_splice_init(&vm->moved, &moved);
1793         spin_unlock(&vm->moved_lock);
1794
1795         list_for_each_entry_safe(bo_va, tmp, &moved, base.vm_status) {
1796                 struct reservation_object *resv = bo_va->base.bo->tbo.resv;
1797
1798                 /* Per VM BOs never need to bo cleared in the page tables */
1799                 if (resv == vm->root.base.bo->tbo.resv)
1800                         clear = false;
1801                 /* Try to reserve the BO to avoid clearing its ptes */
1802                 else if (!amdgpu_vm_debug && reservation_object_trylock(resv))
1803                         clear = false;
1804                 /* Somebody else is using the BO right now */
1805                 else
1806                         clear = true;
1807
1808                 r = amdgpu_vm_bo_update(adev, bo_va, clear);
1809                 if (r) {
1810                         spin_lock(&vm->moved_lock);
1811                         list_splice(&moved, &vm->moved);
1812                         spin_unlock(&vm->moved_lock);
1813                         return r;
1814                 }
1815
1816                 if (!clear && resv != vm->root.base.bo->tbo.resv)
1817                         reservation_object_unlock(resv);
1818
1819         }
1820
1821         return 0;
1822 }
1823
1824 /**
1825  * amdgpu_vm_bo_add - add a bo to a specific vm
1826  *
1827  * @adev: amdgpu_device pointer
1828  * @vm: requested vm
1829  * @bo: amdgpu buffer object
1830  *
1831  * Add @bo into the requested vm.
1832  * Add @bo to the list of bos associated with the vm
1833  * Returns newly added bo_va or NULL for failure
1834  *
1835  * Object has to be reserved!
1836  */
1837 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
1838                                       struct amdgpu_vm *vm,
1839                                       struct amdgpu_bo *bo)
1840 {
1841         struct amdgpu_bo_va *bo_va;
1842
1843         bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
1844         if (bo_va == NULL) {
1845                 return NULL;
1846         }
1847         amdgpu_vm_bo_base_init(&bo_va->base, vm, bo);
1848
1849         bo_va->ref_count = 1;
1850         INIT_LIST_HEAD(&bo_va->valids);
1851         INIT_LIST_HEAD(&bo_va->invalids);
1852
1853         return bo_va;
1854 }
1855
1856
1857 /**
1858  * amdgpu_vm_bo_insert_mapping - insert a new mapping
1859  *
1860  * @adev: amdgpu_device pointer
1861  * @bo_va: bo_va to store the address
1862  * @mapping: the mapping to insert
1863  *
1864  * Insert a new mapping into all structures.
1865  */
1866 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
1867                                     struct amdgpu_bo_va *bo_va,
1868                                     struct amdgpu_bo_va_mapping *mapping)
1869 {
1870         struct amdgpu_vm *vm = bo_va->base.vm;
1871         struct amdgpu_bo *bo = bo_va->base.bo;
1872
1873         mapping->bo_va = bo_va;
1874         list_add(&mapping->list, &bo_va->invalids);
1875         amdgpu_vm_it_insert(mapping, &vm->va);
1876
1877         if (mapping->flags & AMDGPU_PTE_PRT)
1878                 amdgpu_vm_prt_get(adev);
1879
1880         if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
1881                 spin_lock(&vm->moved_lock);
1882                 if (list_empty(&bo_va->base.vm_status))
1883                         list_add(&bo_va->base.vm_status, &vm->moved);
1884                 spin_unlock(&vm->moved_lock);
1885         }
1886         trace_amdgpu_vm_bo_map(bo_va, mapping);
1887 }
1888
1889 /**
1890  * amdgpu_vm_bo_map - map bo inside a vm
1891  *
1892  * @adev: amdgpu_device pointer
1893  * @bo_va: bo_va to store the address
1894  * @saddr: where to map the BO
1895  * @offset: requested offset in the BO
1896  * @flags: attributes of pages (read/write/valid/etc.)
1897  *
1898  * Add a mapping of the BO at the specefied addr into the VM.
1899  * Returns 0 for success, error for failure.
1900  *
1901  * Object has to be reserved and unreserved outside!
1902  */
1903 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1904                      struct amdgpu_bo_va *bo_va,
1905                      uint64_t saddr, uint64_t offset,
1906                      uint64_t size, uint64_t flags)
1907 {
1908         struct amdgpu_bo_va_mapping *mapping, *tmp;
1909         struct amdgpu_bo *bo = bo_va->base.bo;
1910         struct amdgpu_vm *vm = bo_va->base.vm;
1911         uint64_t eaddr;
1912
1913         /* validate the parameters */
1914         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1915             size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1916                 return -EINVAL;
1917
1918         /* make sure object fit at this offset */
1919         eaddr = saddr + size - 1;
1920         if (saddr >= eaddr ||
1921             (bo && offset + size > amdgpu_bo_size(bo)))
1922                 return -EINVAL;
1923
1924         saddr /= AMDGPU_GPU_PAGE_SIZE;
1925         eaddr /= AMDGPU_GPU_PAGE_SIZE;
1926
1927         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
1928         if (tmp) {
1929                 /* bo and tmp overlap, invalid addr */
1930                 dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1931                         "0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
1932                         tmp->start, tmp->last + 1);
1933                 return -EINVAL;
1934         }
1935
1936         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1937         if (!mapping)
1938                 return -ENOMEM;
1939
1940         mapping->start = saddr;
1941         mapping->last = eaddr;
1942         mapping->offset = offset;
1943         mapping->flags = flags;
1944
1945         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1946
1947         return 0;
1948 }
1949
1950 /**
1951  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
1952  *
1953  * @adev: amdgpu_device pointer
1954  * @bo_va: bo_va to store the address
1955  * @saddr: where to map the BO
1956  * @offset: requested offset in the BO
1957  * @flags: attributes of pages (read/write/valid/etc.)
1958  *
1959  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
1960  * mappings as we do so.
1961  * Returns 0 for success, error for failure.
1962  *
1963  * Object has to be reserved and unreserved outside!
1964  */
1965 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
1966                              struct amdgpu_bo_va *bo_va,
1967                              uint64_t saddr, uint64_t offset,
1968                              uint64_t size, uint64_t flags)
1969 {
1970         struct amdgpu_bo_va_mapping *mapping;
1971         struct amdgpu_bo *bo = bo_va->base.bo;
1972         uint64_t eaddr;
1973         int r;
1974
1975         /* validate the parameters */
1976         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1977             size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1978                 return -EINVAL;
1979
1980         /* make sure object fit at this offset */
1981         eaddr = saddr + size - 1;
1982         if (saddr >= eaddr ||
1983             (bo && offset + size > amdgpu_bo_size(bo)))
1984                 return -EINVAL;
1985
1986         /* Allocate all the needed memory */
1987         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1988         if (!mapping)
1989                 return -ENOMEM;
1990
1991         r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
1992         if (r) {
1993                 kfree(mapping);
1994                 return r;
1995         }
1996
1997         saddr /= AMDGPU_GPU_PAGE_SIZE;
1998         eaddr /= AMDGPU_GPU_PAGE_SIZE;
1999
2000         mapping->start = saddr;
2001         mapping->last = eaddr;
2002         mapping->offset = offset;
2003         mapping->flags = flags;
2004
2005         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2006
2007         return 0;
2008 }
2009
2010 /**
2011  * amdgpu_vm_bo_unmap - remove bo mapping from vm
2012  *
2013  * @adev: amdgpu_device pointer
2014  * @bo_va: bo_va to remove the address from
2015  * @saddr: where to the BO is mapped
2016  *
2017  * Remove a mapping of the BO at the specefied addr from the VM.
2018  * Returns 0 for success, error for failure.
2019  *
2020  * Object has to be reserved and unreserved outside!
2021  */
2022 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
2023                        struct amdgpu_bo_va *bo_va,
2024                        uint64_t saddr)
2025 {
2026         struct amdgpu_bo_va_mapping *mapping;
2027         struct amdgpu_vm *vm = bo_va->base.vm;
2028         bool valid = true;
2029
2030         saddr /= AMDGPU_GPU_PAGE_SIZE;
2031
2032         list_for_each_entry(mapping, &bo_va->valids, list) {
2033                 if (mapping->start == saddr)
2034                         break;
2035         }
2036
2037         if (&mapping->list == &bo_va->valids) {
2038                 valid = false;
2039
2040                 list_for_each_entry(mapping, &bo_va->invalids, list) {
2041                         if (mapping->start == saddr)
2042                                 break;
2043                 }
2044
2045                 if (&mapping->list == &bo_va->invalids)
2046                         return -ENOENT;
2047         }
2048
2049         list_del(&mapping->list);
2050         amdgpu_vm_it_remove(mapping, &vm->va);
2051         mapping->bo_va = NULL;
2052         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2053
2054         if (valid)
2055                 list_add(&mapping->list, &vm->freed);
2056         else
2057                 amdgpu_vm_free_mapping(adev, vm, mapping,
2058                                        bo_va->last_pt_update);
2059
2060         return 0;
2061 }
2062
2063 /**
2064  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
2065  *
2066  * @adev: amdgpu_device pointer
2067  * @vm: VM structure to use
2068  * @saddr: start of the range
2069  * @size: size of the range
2070  *
2071  * Remove all mappings in a range, split them as appropriate.
2072  * Returns 0 for success, error for failure.
2073  */
2074 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
2075                                 struct amdgpu_vm *vm,
2076                                 uint64_t saddr, uint64_t size)
2077 {
2078         struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
2079         LIST_HEAD(removed);
2080         uint64_t eaddr;
2081
2082         eaddr = saddr + size - 1;
2083         saddr /= AMDGPU_GPU_PAGE_SIZE;
2084         eaddr /= AMDGPU_GPU_PAGE_SIZE;
2085
2086         /* Allocate all the needed memory */
2087         before = kzalloc(sizeof(*before), GFP_KERNEL);
2088         if (!before)
2089                 return -ENOMEM;
2090         INIT_LIST_HEAD(&before->list);
2091
2092         after = kzalloc(sizeof(*after), GFP_KERNEL);
2093         if (!after) {
2094                 kfree(before);
2095                 return -ENOMEM;
2096         }
2097         INIT_LIST_HEAD(&after->list);
2098
2099         /* Now gather all removed mappings */
2100         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2101         while (tmp) {
2102                 /* Remember mapping split at the start */
2103                 if (tmp->start < saddr) {
2104                         before->start = tmp->start;
2105                         before->last = saddr - 1;
2106                         before->offset = tmp->offset;
2107                         before->flags = tmp->flags;
2108                         list_add(&before->list, &tmp->list);
2109                 }
2110
2111                 /* Remember mapping split at the end */
2112                 if (tmp->last > eaddr) {
2113                         after->start = eaddr + 1;
2114                         after->last = tmp->last;
2115                         after->offset = tmp->offset;
2116                         after->offset += after->start - tmp->start;
2117                         after->flags = tmp->flags;
2118                         list_add(&after->list, &tmp->list);
2119                 }
2120
2121                 list_del(&tmp->list);
2122                 list_add(&tmp->list, &removed);
2123
2124                 tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
2125         }
2126
2127         /* And free them up */
2128         list_for_each_entry_safe(tmp, next, &removed, list) {
2129                 amdgpu_vm_it_remove(tmp, &vm->va);
2130                 list_del(&tmp->list);
2131
2132                 if (tmp->start < saddr)
2133                     tmp->start = saddr;
2134                 if (tmp->last > eaddr)
2135                     tmp->last = eaddr;
2136
2137                 tmp->bo_va = NULL;
2138                 list_add(&tmp->list, &vm->freed);
2139                 trace_amdgpu_vm_bo_unmap(NULL, tmp);
2140         }
2141
2142         /* Insert partial mapping before the range */
2143         if (!list_empty(&before->list)) {
2144                 amdgpu_vm_it_insert(before, &vm->va);
2145                 if (before->flags & AMDGPU_PTE_PRT)
2146                         amdgpu_vm_prt_get(adev);
2147         } else {
2148                 kfree(before);
2149         }
2150
2151         /* Insert partial mapping after the range */
2152         if (!list_empty(&after->list)) {
2153                 amdgpu_vm_it_insert(after, &vm->va);
2154                 if (after->flags & AMDGPU_PTE_PRT)
2155                         amdgpu_vm_prt_get(adev);
2156         } else {
2157                 kfree(after);
2158         }
2159
2160         return 0;
2161 }
2162
2163 /**
2164  * amdgpu_vm_bo_lookup_mapping - find mapping by address
2165  *
2166  * @vm: the requested VM
2167  *
2168  * Find a mapping by it's address.
2169  */
2170 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
2171                                                          uint64_t addr)
2172 {
2173         return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
2174 }
2175
2176 /**
2177  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
2178  *
2179  * @adev: amdgpu_device pointer
2180  * @bo_va: requested bo_va
2181  *
2182  * Remove @bo_va->bo from the requested vm.
2183  *
2184  * Object have to be reserved!
2185  */
2186 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
2187                       struct amdgpu_bo_va *bo_va)
2188 {
2189         struct amdgpu_bo_va_mapping *mapping, *next;
2190         struct amdgpu_vm *vm = bo_va->base.vm;
2191
2192         list_del(&bo_va->base.bo_list);
2193
2194         spin_lock(&vm->moved_lock);
2195         list_del(&bo_va->base.vm_status);
2196         spin_unlock(&vm->moved_lock);
2197
2198         list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
2199                 list_del(&mapping->list);
2200                 amdgpu_vm_it_remove(mapping, &vm->va);
2201                 mapping->bo_va = NULL;
2202                 trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2203                 list_add(&mapping->list, &vm->freed);
2204         }
2205         list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
2206                 list_del(&mapping->list);
2207                 amdgpu_vm_it_remove(mapping, &vm->va);
2208                 amdgpu_vm_free_mapping(adev, vm, mapping,
2209                                        bo_va->last_pt_update);
2210         }
2211
2212         dma_fence_put(bo_va->last_pt_update);
2213         kfree(bo_va);
2214 }
2215
2216 /**
2217  * amdgpu_vm_bo_invalidate - mark the bo as invalid
2218  *
2219  * @adev: amdgpu_device pointer
2220  * @vm: requested vm
2221  * @bo: amdgpu buffer object
2222  *
2223  * Mark @bo as invalid.
2224  */
2225 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
2226                              struct amdgpu_bo *bo, bool evicted)
2227 {
2228         struct amdgpu_vm_bo_base *bo_base;
2229
2230         /* shadow bo doesn't have bo base, its validation needs its parent */
2231         if (bo->parent && bo->parent->shadow == bo)
2232                 bo = bo->parent;
2233
2234         list_for_each_entry(bo_base, &bo->va, bo_list) {
2235                 struct amdgpu_vm *vm = bo_base->vm;
2236
2237                 bo_base->moved = true;
2238                 if (evicted && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
2239                         if (bo->tbo.type == ttm_bo_type_kernel)
2240                                 list_move(&bo_base->vm_status, &vm->evicted);
2241                         else
2242                                 list_move_tail(&bo_base->vm_status,
2243                                                &vm->evicted);
2244                         continue;
2245                 }
2246
2247                 if (bo->tbo.type == ttm_bo_type_kernel) {
2248                         if (list_empty(&bo_base->vm_status))
2249                                 list_add(&bo_base->vm_status, &vm->relocated);
2250                         continue;
2251                 }
2252
2253                 spin_lock(&bo_base->vm->moved_lock);
2254                 if (list_empty(&bo_base->vm_status))
2255                         list_add(&bo_base->vm_status, &vm->moved);
2256                 spin_unlock(&bo_base->vm->moved_lock);
2257         }
2258 }
2259
2260 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
2261 {
2262         /* Total bits covered by PD + PTs */
2263         unsigned bits = ilog2(vm_size) + 18;
2264
2265         /* Make sure the PD is 4K in size up to 8GB address space.
2266            Above that split equal between PD and PTs */
2267         if (vm_size <= 8)
2268                 return (bits - 9);
2269         else
2270                 return ((bits + 3) / 2);
2271 }
2272
2273 /**
2274  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
2275  *
2276  * @adev: amdgpu_device pointer
2277  * @vm_size: the default vm size if it's set auto
2278  */
2279 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t vm_size,
2280                            uint32_t fragment_size_default, unsigned max_level,
2281                            unsigned max_bits)
2282 {
2283         uint64_t tmp;
2284
2285         /* adjust vm size first */
2286         if (amdgpu_vm_size != -1) {
2287                 unsigned max_size = 1 << (max_bits - 30);
2288
2289                 vm_size = amdgpu_vm_size;
2290                 if (vm_size > max_size) {
2291                         dev_warn(adev->dev, "VM size (%d) too large, max is %u GB\n",
2292                                  amdgpu_vm_size, max_size);
2293                         vm_size = max_size;
2294                 }
2295         }
2296
2297         adev->vm_manager.max_pfn = (uint64_t)vm_size << 18;
2298
2299         tmp = roundup_pow_of_two(adev->vm_manager.max_pfn);
2300         if (amdgpu_vm_block_size != -1)
2301                 tmp >>= amdgpu_vm_block_size - 9;
2302         tmp = DIV_ROUND_UP(fls64(tmp) - 1, 9) - 1;
2303         adev->vm_manager.num_level = min(max_level, (unsigned)tmp);
2304         switch (adev->vm_manager.num_level) {
2305         case 3:
2306                 adev->vm_manager.root_level = AMDGPU_VM_PDB2;
2307                 break;
2308         case 2:
2309                 adev->vm_manager.root_level = AMDGPU_VM_PDB1;
2310                 break;
2311         case 1:
2312                 adev->vm_manager.root_level = AMDGPU_VM_PDB0;
2313                 break;
2314         default:
2315                 dev_err(adev->dev, "VMPT only supports 2~4+1 levels\n");
2316         }
2317         /* block size depends on vm size and hw setup*/
2318         if (amdgpu_vm_block_size != -1)
2319                 adev->vm_manager.block_size =
2320                         min((unsigned)amdgpu_vm_block_size, max_bits
2321                             - AMDGPU_GPU_PAGE_SHIFT
2322                             - 9 * adev->vm_manager.num_level);
2323         else if (adev->vm_manager.num_level > 1)
2324                 adev->vm_manager.block_size = 9;
2325         else
2326                 adev->vm_manager.block_size = amdgpu_vm_get_block_size(tmp);
2327
2328         if (amdgpu_vm_fragment_size == -1)
2329                 adev->vm_manager.fragment_size = fragment_size_default;
2330         else
2331                 adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
2332
2333         DRM_INFO("vm size is %u GB, %u levels, block size is %u-bit, fragment size is %u-bit\n",
2334                  vm_size, adev->vm_manager.num_level + 1,
2335                  adev->vm_manager.block_size,
2336                  adev->vm_manager.fragment_size);
2337 }
2338
2339 /**
2340  * amdgpu_vm_init - initialize a vm instance
2341  *
2342  * @adev: amdgpu_device pointer
2343  * @vm: requested vm
2344  * @vm_context: Indicates if it GFX or Compute context
2345  *
2346  * Init @vm fields.
2347  */
2348 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
2349                    int vm_context, unsigned int pasid)
2350 {
2351         struct amdgpu_bo_param bp;
2352         struct amdgpu_bo *root;
2353         const unsigned align = min(AMDGPU_VM_PTB_ALIGN_SIZE,
2354                 AMDGPU_VM_PTE_COUNT(adev) * 8);
2355         unsigned ring_instance;
2356         struct amdgpu_ring *ring;
2357         struct drm_sched_rq *rq;
2358         unsigned long size;
2359         uint64_t flags;
2360         int r, i;
2361
2362         vm->va = RB_ROOT_CACHED;
2363         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2364                 vm->reserved_vmid[i] = NULL;
2365         INIT_LIST_HEAD(&vm->evicted);
2366         INIT_LIST_HEAD(&vm->relocated);
2367         spin_lock_init(&vm->moved_lock);
2368         INIT_LIST_HEAD(&vm->moved);
2369         INIT_LIST_HEAD(&vm->freed);
2370
2371         /* create scheduler entity for page table updates */
2372
2373         ring_instance = atomic_inc_return(&adev->vm_manager.vm_pte_next_ring);
2374         ring_instance %= adev->vm_manager.vm_pte_num_rings;
2375         ring = adev->vm_manager.vm_pte_rings[ring_instance];
2376         rq = &ring->sched.sched_rq[DRM_SCHED_PRIORITY_KERNEL];
2377         r = drm_sched_entity_init(&ring->sched, &vm->entity,
2378                                   rq, NULL);
2379         if (r)
2380                 return r;
2381
2382         vm->pte_support_ats = false;
2383
2384         if (vm_context == AMDGPU_VM_CONTEXT_COMPUTE) {
2385                 vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2386                                                 AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2387
2388                 if (adev->asic_type == CHIP_RAVEN)
2389                         vm->pte_support_ats = true;
2390         } else {
2391                 vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2392                                                 AMDGPU_VM_USE_CPU_FOR_GFX);
2393         }
2394         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2395                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2396         WARN_ONCE((vm->use_cpu_for_update & !amdgpu_vm_is_large_bar(adev)),
2397                   "CPU update of VM recommended only for large BAR system\n");
2398         vm->last_update = NULL;
2399
2400         flags = AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS;
2401         if (vm->use_cpu_for_update)
2402                 flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
2403         else
2404                 flags |= AMDGPU_GEM_CREATE_SHADOW;
2405
2406         size = amdgpu_vm_bo_size(adev, adev->vm_manager.root_level);
2407         memset(&bp, 0, sizeof(bp));
2408         bp.size = size;
2409         bp.byte_align = align;
2410         bp.domain = AMDGPU_GEM_DOMAIN_VRAM;
2411         bp.flags = flags;
2412         bp.type = ttm_bo_type_kernel;
2413         bp.resv = NULL;
2414         r = amdgpu_bo_create(adev, &bp, &root);
2415         if (r)
2416                 goto error_free_sched_entity;
2417
2418         r = amdgpu_bo_reserve(root, true);
2419         if (r)
2420                 goto error_free_root;
2421
2422         r = amdgpu_vm_clear_bo(adev, vm, root,
2423                                adev->vm_manager.root_level,
2424                                vm->pte_support_ats);
2425         if (r)
2426                 goto error_unreserve;
2427
2428         amdgpu_vm_bo_base_init(&vm->root.base, vm, root);
2429         amdgpu_bo_unreserve(vm->root.base.bo);
2430
2431         if (pasid) {
2432                 unsigned long flags;
2433
2434                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2435                 r = idr_alloc(&adev->vm_manager.pasid_idr, vm, pasid, pasid + 1,
2436                               GFP_ATOMIC);
2437                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2438                 if (r < 0)
2439                         goto error_free_root;
2440
2441                 vm->pasid = pasid;
2442         }
2443
2444         INIT_KFIFO(vm->faults);
2445         vm->fault_credit = 16;
2446
2447         return 0;
2448
2449 error_unreserve:
2450         amdgpu_bo_unreserve(vm->root.base.bo);
2451
2452 error_free_root:
2453         amdgpu_bo_unref(&vm->root.base.bo->shadow);
2454         amdgpu_bo_unref(&vm->root.base.bo);
2455         vm->root.base.bo = NULL;
2456
2457 error_free_sched_entity:
2458         drm_sched_entity_fini(&ring->sched, &vm->entity);
2459
2460         return r;
2461 }
2462
2463 /**
2464  * amdgpu_vm_make_compute - Turn a GFX VM into a compute VM
2465  *
2466  * This only works on GFX VMs that don't have any BOs added and no
2467  * page tables allocated yet.
2468  *
2469  * Changes the following VM parameters:
2470  * - use_cpu_for_update
2471  * - pte_supports_ats
2472  * - pasid (old PASID is released, because compute manages its own PASIDs)
2473  *
2474  * Reinitializes the page directory to reflect the changed ATS
2475  * setting. May leave behind an unused shadow BO for the page
2476  * directory when switching from SDMA updates to CPU updates.
2477  *
2478  * Returns 0 for success, -errno for errors.
2479  */
2480 int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2481 {
2482         bool pte_support_ats = (adev->asic_type == CHIP_RAVEN);
2483         int r;
2484
2485         r = amdgpu_bo_reserve(vm->root.base.bo, true);
2486         if (r)
2487                 return r;
2488
2489         /* Sanity checks */
2490         if (!RB_EMPTY_ROOT(&vm->va.rb_root) || vm->root.entries) {
2491                 r = -EINVAL;
2492                 goto error;
2493         }
2494
2495         /* Check if PD needs to be reinitialized and do it before
2496          * changing any other state, in case it fails.
2497          */
2498         if (pte_support_ats != vm->pte_support_ats) {
2499                 r = amdgpu_vm_clear_bo(adev, vm, vm->root.base.bo,
2500                                adev->vm_manager.root_level,
2501                                pte_support_ats);
2502                 if (r)
2503                         goto error;
2504         }
2505
2506         /* Update VM state */
2507         vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2508                                     AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2509         vm->pte_support_ats = pte_support_ats;
2510         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2511                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2512         WARN_ONCE((vm->use_cpu_for_update & !amdgpu_vm_is_large_bar(adev)),
2513                   "CPU update of VM recommended only for large BAR system\n");
2514
2515         if (vm->pasid) {
2516                 unsigned long flags;
2517
2518                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2519                 idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2520                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2521
2522                 vm->pasid = 0;
2523         }
2524
2525 error:
2526         amdgpu_bo_unreserve(vm->root.base.bo);
2527         return r;
2528 }
2529
2530 /**
2531  * amdgpu_vm_free_levels - free PD/PT levels
2532  *
2533  * @adev: amdgpu device structure
2534  * @parent: PD/PT starting level to free
2535  * @level: level of parent structure
2536  *
2537  * Free the page directory or page table level and all sub levels.
2538  */
2539 static void amdgpu_vm_free_levels(struct amdgpu_device *adev,
2540                                   struct amdgpu_vm_pt *parent,
2541                                   unsigned level)
2542 {
2543         unsigned i, num_entries = amdgpu_vm_num_entries(adev, level);
2544
2545         if (parent->base.bo) {
2546                 list_del(&parent->base.bo_list);
2547                 list_del(&parent->base.vm_status);
2548                 amdgpu_bo_unref(&parent->base.bo->shadow);
2549                 amdgpu_bo_unref(&parent->base.bo);
2550         }
2551
2552         if (parent->entries)
2553                 for (i = 0; i < num_entries; i++)
2554                         amdgpu_vm_free_levels(adev, &parent->entries[i],
2555                                               level + 1);
2556
2557         kvfree(parent->entries);
2558 }
2559
2560 /**
2561  * amdgpu_vm_fini - tear down a vm instance
2562  *
2563  * @adev: amdgpu_device pointer
2564  * @vm: requested vm
2565  *
2566  * Tear down @vm.
2567  * Unbind the VM and remove all bos from the vm bo list
2568  */
2569 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2570 {
2571         struct amdgpu_bo_va_mapping *mapping, *tmp;
2572         bool prt_fini_needed = !!adev->gmc.gmc_funcs->set_prt;
2573         struct amdgpu_bo *root;
2574         u64 fault;
2575         int i, r;
2576
2577         amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
2578
2579         /* Clear pending page faults from IH when the VM is destroyed */
2580         while (kfifo_get(&vm->faults, &fault))
2581                 amdgpu_ih_clear_fault(adev, fault);
2582
2583         if (vm->pasid) {
2584                 unsigned long flags;
2585
2586                 spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2587                 idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2588                 spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2589         }
2590
2591         drm_sched_entity_fini(vm->entity.sched, &vm->entity);
2592
2593         if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
2594                 dev_err(adev->dev, "still active bo inside vm\n");
2595         }
2596         rbtree_postorder_for_each_entry_safe(mapping, tmp,
2597                                              &vm->va.rb_root, rb) {
2598                 list_del(&mapping->list);
2599                 amdgpu_vm_it_remove(mapping, &vm->va);
2600                 kfree(mapping);
2601         }
2602         list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2603                 if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
2604                         amdgpu_vm_prt_fini(adev, vm);
2605                         prt_fini_needed = false;
2606                 }
2607
2608                 list_del(&mapping->list);
2609                 amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2610         }
2611
2612         root = amdgpu_bo_ref(vm->root.base.bo);
2613         r = amdgpu_bo_reserve(root, true);
2614         if (r) {
2615                 dev_err(adev->dev, "Leaking page tables because BO reservation failed\n");
2616         } else {
2617                 amdgpu_vm_free_levels(adev, &vm->root,
2618                                       adev->vm_manager.root_level);
2619                 amdgpu_bo_unreserve(root);
2620         }
2621         amdgpu_bo_unref(&root);
2622         dma_fence_put(vm->last_update);
2623         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2624                 amdgpu_vmid_free_reserved(adev, vm, i);
2625 }
2626
2627 /**
2628  * amdgpu_vm_pasid_fault_credit - Check fault credit for given PASID
2629  *
2630  * @adev: amdgpu_device pointer
2631  * @pasid: PASID do identify the VM
2632  *
2633  * This function is expected to be called in interrupt context. Returns
2634  * true if there was fault credit, false otherwise
2635  */
2636 bool amdgpu_vm_pasid_fault_credit(struct amdgpu_device *adev,
2637                                   unsigned int pasid)
2638 {
2639         struct amdgpu_vm *vm;
2640
2641         spin_lock(&adev->vm_manager.pasid_lock);
2642         vm = idr_find(&adev->vm_manager.pasid_idr, pasid);
2643         if (!vm) {
2644                 /* VM not found, can't track fault credit */
2645                 spin_unlock(&adev->vm_manager.pasid_lock);
2646                 return true;
2647         }
2648
2649         /* No lock needed. only accessed by IRQ handler */
2650         if (!vm->fault_credit) {
2651                 /* Too many faults in this VM */
2652                 spin_unlock(&adev->vm_manager.pasid_lock);
2653                 return false;
2654         }
2655
2656         vm->fault_credit--;
2657         spin_unlock(&adev->vm_manager.pasid_lock);
2658         return true;
2659 }
2660
2661 /**
2662  * amdgpu_vm_manager_init - init the VM manager
2663  *
2664  * @adev: amdgpu_device pointer
2665  *
2666  * Initialize the VM manager structures
2667  */
2668 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
2669 {
2670         unsigned i;
2671
2672         amdgpu_vmid_mgr_init(adev);
2673
2674         adev->vm_manager.fence_context =
2675                 dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2676         for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
2677                 adev->vm_manager.seqno[i] = 0;
2678
2679         atomic_set(&adev->vm_manager.vm_pte_next_ring, 0);
2680         spin_lock_init(&adev->vm_manager.prt_lock);
2681         atomic_set(&adev->vm_manager.num_prt_users, 0);
2682
2683         /* If not overridden by the user, by default, only in large BAR systems
2684          * Compute VM tables will be updated by CPU
2685          */
2686 #ifdef CONFIG_X86_64
2687         if (amdgpu_vm_update_mode == -1) {
2688                 if (amdgpu_vm_is_large_bar(adev))
2689                         adev->vm_manager.vm_update_mode =
2690                                 AMDGPU_VM_USE_CPU_FOR_COMPUTE;
2691                 else
2692                         adev->vm_manager.vm_update_mode = 0;
2693         } else
2694                 adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
2695 #else
2696         adev->vm_manager.vm_update_mode = 0;
2697 #endif
2698
2699         idr_init(&adev->vm_manager.pasid_idr);
2700         spin_lock_init(&adev->vm_manager.pasid_lock);
2701 }
2702
2703 /**
2704  * amdgpu_vm_manager_fini - cleanup VM manager
2705  *
2706  * @adev: amdgpu_device pointer
2707  *
2708  * Cleanup the VM manager and free resources.
2709  */
2710 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
2711 {
2712         WARN_ON(!idr_is_empty(&adev->vm_manager.pasid_idr));
2713         idr_destroy(&adev->vm_manager.pasid_idr);
2714
2715         amdgpu_vmid_mgr_fini(adev);
2716 }
2717
2718 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
2719 {
2720         union drm_amdgpu_vm *args = data;
2721         struct amdgpu_device *adev = dev->dev_private;
2722         struct amdgpu_fpriv *fpriv = filp->driver_priv;
2723         int r;
2724
2725         switch (args->in.op) {
2726         case AMDGPU_VM_OP_RESERVE_VMID:
2727                 /* current, we only have requirement to reserve vmid from gfxhub */
2728                 r = amdgpu_vmid_alloc_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
2729                 if (r)
2730                         return r;
2731                 break;
2732         case AMDGPU_VM_OP_UNRESERVE_VMID:
2733                 amdgpu_vmid_free_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB);
2734                 break;
2735         default:
2736                 return -EINVAL;
2737         }
2738
2739         return 0;
2740 }
This page took 0.195868 seconds and 4 git commands to generate.