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