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