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