]> git.kernelconcepts.de Git - karo-tx-linux.git/blob - drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c
60fc9a508c0b926c4ab3822cbf3df6931f1218dd
[karo-tx-linux.git] / drivers / gpu / drm / amd / amdgpu / amdgpu_vm.c
1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  */
28 #include <linux/fence-array.h>
29 #include <drm/drmP.h>
30 #include <drm/amdgpu_drm.h>
31 #include "amdgpu.h"
32 #include "amdgpu_trace.h"
33
34 /*
35  * GPUVM
36  * GPUVM is similar to the legacy gart on older asics, however
37  * rather than there being a single global gart table
38  * for the entire GPU, there are multiple VM page tables active
39  * at any given time.  The VM page tables can contain a mix
40  * vram pages and system memory pages and system memory pages
41  * can be mapped as snooped (cached system pages) or unsnooped
42  * (uncached system pages).
43  * Each VM has an ID associated with it and there is a page table
44  * associated with each VMID.  When execting a command buffer,
45  * the kernel tells the the ring what VMID to use for that command
46  * buffer.  VMIDs are allocated dynamically as commands are submitted.
47  * The userspace drivers maintain their own address space and the kernel
48  * sets up their pages tables accordingly when they submit their
49  * command buffers and a VMID is assigned.
50  * Cayman/Trinity support up to 8 active VMs at any given time;
51  * SI supports 16.
52  */
53
54 /* Special value that no flush is necessary */
55 #define AMDGPU_VM_NO_FLUSH (~0ll)
56
57 /* Local structure. Encapsulate some VM table update parameters to reduce
58  * the number of function parameters
59  */
60 struct amdgpu_vm_update_params {
61         /* address where to copy page table entries from */
62         uint64_t src;
63         /* DMA addresses to use for mapping */
64         dma_addr_t *pages_addr;
65         /* indirect buffer to fill with commands */
66         struct amdgpu_ib *ib;
67 };
68
69 /**
70  * amdgpu_vm_num_pde - return the number of page directory entries
71  *
72  * @adev: amdgpu_device pointer
73  *
74  * Calculate the number of page directory entries.
75  */
76 static unsigned amdgpu_vm_num_pdes(struct amdgpu_device *adev)
77 {
78         return adev->vm_manager.max_pfn >> amdgpu_vm_block_size;
79 }
80
81 /**
82  * amdgpu_vm_directory_size - returns the size of the page directory in bytes
83  *
84  * @adev: amdgpu_device pointer
85  *
86  * Calculate the size of the page directory in bytes.
87  */
88 static unsigned amdgpu_vm_directory_size(struct amdgpu_device *adev)
89 {
90         return AMDGPU_GPU_PAGE_ALIGN(amdgpu_vm_num_pdes(adev) * 8);
91 }
92
93 /**
94  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
95  *
96  * @vm: vm providing the BOs
97  * @validated: head of validation list
98  * @entry: entry to add
99  *
100  * Add the page directory to the list of BOs to
101  * validate for command submission.
102  */
103 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
104                          struct list_head *validated,
105                          struct amdgpu_bo_list_entry *entry)
106 {
107         entry->robj = vm->page_directory;
108         entry->priority = 0;
109         entry->tv.bo = &vm->page_directory->tbo;
110         entry->tv.shared = true;
111         entry->user_pages = NULL;
112         list_add(&entry->tv.head, validated);
113 }
114
115 /**
116  * amdgpu_vm_get_bos - add the vm BOs to a duplicates list
117  *
118  * @adev: amdgpu device pointer
119  * @vm: vm providing the BOs
120  * @duplicates: head of duplicates list
121  *
122  * Add the page directory to the BO duplicates list
123  * for command submission.
124  */
125 void amdgpu_vm_get_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
126                           struct list_head *duplicates)
127 {
128         uint64_t num_evictions;
129         unsigned i;
130
131         /* We only need to validate the page tables
132          * if they aren't already valid.
133          */
134         num_evictions = atomic64_read(&adev->num_evictions);
135         if (num_evictions == vm->last_eviction_counter)
136                 return;
137
138         /* add the vm page table to the list */
139         for (i = 0; i <= vm->max_pde_used; ++i) {
140                 struct amdgpu_bo_list_entry *entry = &vm->page_tables[i].entry;
141
142                 if (!entry->robj)
143                         continue;
144
145                 list_add(&entry->tv.head, duplicates);
146         }
147
148 }
149
150 /**
151  * amdgpu_vm_move_pt_bos_in_lru - move the PT BOs to the LRU tail
152  *
153  * @adev: amdgpu device instance
154  * @vm: vm providing the BOs
155  *
156  * Move the PT BOs to the tail of the LRU.
157  */
158 void amdgpu_vm_move_pt_bos_in_lru(struct amdgpu_device *adev,
159                                   struct amdgpu_vm *vm)
160 {
161         struct ttm_bo_global *glob = adev->mman.bdev.glob;
162         unsigned i;
163
164         spin_lock(&glob->lru_lock);
165         for (i = 0; i <= vm->max_pde_used; ++i) {
166                 struct amdgpu_bo_list_entry *entry = &vm->page_tables[i].entry;
167
168                 if (!entry->robj)
169                         continue;
170
171                 ttm_bo_move_to_lru_tail(&entry->robj->tbo);
172         }
173         spin_unlock(&glob->lru_lock);
174 }
175
176 static bool amdgpu_vm_is_gpu_reset(struct amdgpu_device *adev,
177                               struct amdgpu_vm_id *id)
178 {
179         return id->current_gpu_reset_count !=
180                 atomic_read(&adev->gpu_reset_counter) ? true : false;
181 }
182
183 /**
184  * amdgpu_vm_grab_id - allocate the next free VMID
185  *
186  * @vm: vm to allocate id for
187  * @ring: ring we want to submit job to
188  * @sync: sync object where we add dependencies
189  * @fence: fence protecting ID from reuse
190  *
191  * Allocate an id for the vm, adding fences to the sync obj as necessary.
192  */
193 int amdgpu_vm_grab_id(struct amdgpu_vm *vm, struct amdgpu_ring *ring,
194                       struct amdgpu_sync *sync, struct fence *fence,
195                       struct amdgpu_job *job)
196 {
197         struct amdgpu_device *adev = ring->adev;
198         struct fence *updates = sync->last_vm_update;
199         struct amdgpu_vm_id *id, *idle;
200         struct fence **fences;
201         unsigned i;
202         int r = 0;
203
204         fences = kmalloc_array(sizeof(void *), adev->vm_manager.num_ids,
205                                GFP_KERNEL);
206         if (!fences)
207                 return -ENOMEM;
208
209         mutex_lock(&adev->vm_manager.lock);
210
211         /* Check if we have an idle VMID */
212         i = 0;
213         list_for_each_entry(idle, &adev->vm_manager.ids_lru, list) {
214                 fences[i] = amdgpu_sync_peek_fence(&idle->active, ring);
215                 if (!fences[i])
216                         break;
217                 ++i;
218         }
219
220         /* If we can't find a idle VMID to use, wait till one becomes available */
221         if (&idle->list == &adev->vm_manager.ids_lru) {
222                 u64 fence_context = adev->vm_manager.fence_context + ring->idx;
223                 unsigned seqno = ++adev->vm_manager.seqno[ring->idx];
224                 struct fence_array *array;
225                 unsigned j;
226
227                 for (j = 0; j < i; ++j)
228                         fence_get(fences[j]);
229
230                 array = fence_array_create(i, fences, fence_context,
231                                            seqno, true);
232                 if (!array) {
233                         for (j = 0; j < i; ++j)
234                                 fence_put(fences[j]);
235                         kfree(fences);
236                         r = -ENOMEM;
237                         goto error;
238                 }
239
240
241                 r = amdgpu_sync_fence(ring->adev, sync, &array->base);
242                 fence_put(&array->base);
243                 if (r)
244                         goto error;
245
246                 mutex_unlock(&adev->vm_manager.lock);
247                 return 0;
248
249         }
250         kfree(fences);
251
252         job->vm_needs_flush = true;
253         /* Check if we can use a VMID already assigned to this VM */
254         i = ring->idx;
255         do {
256                 struct fence *flushed;
257                 bool same_ring = ring->idx == i;
258
259                 id = vm->ids[i++];
260                 if (i == AMDGPU_MAX_RINGS)
261                         i = 0;
262
263                 /* Check all the prerequisites to using this VMID */
264                 if (!id)
265                         continue;
266                 if (amdgpu_vm_is_gpu_reset(adev, id))
267                         continue;
268
269                 if (atomic64_read(&id->owner) != vm->client_id)
270                         continue;
271
272                 if (job->vm_pd_addr != id->pd_gpu_addr)
273                         continue;
274
275                 if (!same_ring &&
276                     (!id->last_flush || !fence_is_signaled(id->last_flush)))
277                         continue;
278
279                 flushed  = id->flushed_updates;
280                 if (updates &&
281                     (!flushed || fence_is_later(updates, flushed)))
282                         continue;
283
284                 /* Good we can use this VMID. Remember this submission as
285                  * user of the VMID.
286                  */
287                 r = amdgpu_sync_fence(ring->adev, &id->active, fence);
288                 if (r)
289                         goto error;
290
291                 id->current_gpu_reset_count = atomic_read(&adev->gpu_reset_counter);
292                 list_move_tail(&id->list, &adev->vm_manager.ids_lru);
293                 vm->ids[ring->idx] = id;
294
295                 job->vm_id = id - adev->vm_manager.ids;
296                 job->vm_needs_flush = false;
297                 trace_amdgpu_vm_grab_id(vm, ring->idx, job->vm_id, job->vm_pd_addr);
298
299                 mutex_unlock(&adev->vm_manager.lock);
300                 return 0;
301
302         } while (i != ring->idx);
303
304         /* Still no ID to use? Then use the idle one found earlier */
305         id = idle;
306
307         /* Remember this submission as user of the VMID */
308         r = amdgpu_sync_fence(ring->adev, &id->active, fence);
309         if (r)
310                 goto error;
311
312         fence_put(id->first);
313         id->first = fence_get(fence);
314
315         fence_put(id->last_flush);
316         id->last_flush = NULL;
317
318         fence_put(id->flushed_updates);
319         id->flushed_updates = fence_get(updates);
320
321         id->pd_gpu_addr = job->vm_pd_addr;
322         id->current_gpu_reset_count = atomic_read(&adev->gpu_reset_counter);
323         list_move_tail(&id->list, &adev->vm_manager.ids_lru);
324         atomic64_set(&id->owner, vm->client_id);
325         vm->ids[ring->idx] = id;
326
327         job->vm_id = id - adev->vm_manager.ids;
328         trace_amdgpu_vm_grab_id(vm, ring->idx, job->vm_id, job->vm_pd_addr);
329
330 error:
331         mutex_unlock(&adev->vm_manager.lock);
332         return r;
333 }
334
335 static bool amdgpu_vm_ring_has_compute_vm_bug(struct amdgpu_ring *ring)
336 {
337         struct amdgpu_device *adev = ring->adev;
338         const struct amdgpu_ip_block_version *ip_block;
339
340         if (ring->type != AMDGPU_RING_TYPE_COMPUTE)
341                 /* only compute rings */
342                 return false;
343
344         ip_block = amdgpu_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
345         if (!ip_block)
346                 return false;
347
348         if (ip_block->major <= 7) {
349                 /* gfx7 has no workaround */
350                 return true;
351         } else if (ip_block->major == 8) {
352                 if (adev->gfx.mec_fw_version >= 673)
353                         /* gfx8 is fixed in MEC firmware 673 */
354                         return false;
355                 else
356                         return true;
357         }
358         return false;
359 }
360
361 /**
362  * amdgpu_vm_flush - hardware flush the vm
363  *
364  * @ring: ring to use for flush
365  * @vm_id: vmid number to use
366  * @pd_addr: address of the page directory
367  *
368  * Emit a VM flush when it is necessary.
369  */
370 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job)
371 {
372         struct amdgpu_device *adev = ring->adev;
373         struct amdgpu_vm_id *id = &adev->vm_manager.ids[job->vm_id];
374         bool gds_switch_needed = ring->funcs->emit_gds_switch && (
375                 id->gds_base != job->gds_base ||
376                 id->gds_size != job->gds_size ||
377                 id->gws_base != job->gws_base ||
378                 id->gws_size != job->gws_size ||
379                 id->oa_base != job->oa_base ||
380                 id->oa_size != job->oa_size);
381         int r;
382
383         if (ring->funcs->emit_pipeline_sync && (
384             job->vm_needs_flush || gds_switch_needed ||
385             amdgpu_vm_ring_has_compute_vm_bug(ring)))
386                 amdgpu_ring_emit_pipeline_sync(ring);
387
388         if (ring->funcs->emit_vm_flush && job->vm_needs_flush) {
389                 struct fence *fence;
390
391                 trace_amdgpu_vm_flush(job->vm_pd_addr, ring->idx, job->vm_id);
392                 amdgpu_ring_emit_vm_flush(ring, job->vm_id, job->vm_pd_addr);
393
394                 r = amdgpu_fence_emit(ring, &fence);
395                 if (r)
396                         return r;
397
398                 mutex_lock(&adev->vm_manager.lock);
399                 fence_put(id->last_flush);
400                 id->last_flush = fence;
401                 mutex_unlock(&adev->vm_manager.lock);
402         }
403
404         if (gds_switch_needed) {
405                 id->gds_base = job->gds_base;
406                 id->gds_size = job->gds_size;
407                 id->gws_base = job->gws_base;
408                 id->gws_size = job->gws_size;
409                 id->oa_base = job->oa_base;
410                 id->oa_size = job->oa_size;
411                 amdgpu_ring_emit_gds_switch(ring, job->vm_id,
412                                             job->gds_base, job->gds_size,
413                                             job->gws_base, job->gws_size,
414                                             job->oa_base, job->oa_size);
415         }
416
417         return 0;
418 }
419
420 /**
421  * amdgpu_vm_reset_id - reset VMID to zero
422  *
423  * @adev: amdgpu device structure
424  * @vm_id: vmid number to use
425  *
426  * Reset saved GDW, GWS and OA to force switch on next flush.
427  */
428 void amdgpu_vm_reset_id(struct amdgpu_device *adev, unsigned vm_id)
429 {
430         struct amdgpu_vm_id *id = &adev->vm_manager.ids[vm_id];
431
432         id->gds_base = 0;
433         id->gds_size = 0;
434         id->gws_base = 0;
435         id->gws_size = 0;
436         id->oa_base = 0;
437         id->oa_size = 0;
438 }
439
440 /**
441  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
442  *
443  * @vm: requested vm
444  * @bo: requested buffer object
445  *
446  * Find @bo inside the requested vm.
447  * Search inside the @bos vm list for the requested vm
448  * Returns the found bo_va or NULL if none is found
449  *
450  * Object has to be reserved!
451  */
452 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
453                                        struct amdgpu_bo *bo)
454 {
455         struct amdgpu_bo_va *bo_va;
456
457         list_for_each_entry(bo_va, &bo->va, bo_list) {
458                 if (bo_va->vm == vm) {
459                         return bo_va;
460                 }
461         }
462         return NULL;
463 }
464
465 /**
466  * amdgpu_vm_update_pages - helper to call the right asic function
467  *
468  * @adev: amdgpu_device pointer
469  * @vm_update_params: see amdgpu_vm_update_params definition
470  * @pe: addr of the page entry
471  * @addr: dst addr to write into pe
472  * @count: number of page entries to update
473  * @incr: increase next addr by incr bytes
474  * @flags: hw access flags
475  *
476  * Traces the parameters and calls the right asic functions
477  * to setup the page table using the DMA.
478  */
479 static void amdgpu_vm_update_pages(struct amdgpu_device *adev,
480                                    struct amdgpu_vm_update_params
481                                         *vm_update_params,
482                                    uint64_t pe, uint64_t addr,
483                                    unsigned count, uint32_t incr,
484                                    uint32_t flags)
485 {
486         trace_amdgpu_vm_set_page(pe, addr, count, incr, flags);
487
488         if (vm_update_params->src) {
489                 amdgpu_vm_copy_pte(adev, vm_update_params->ib,
490                         pe, (vm_update_params->src + (addr >> 12) * 8), count);
491
492         } else if (vm_update_params->pages_addr) {
493                 amdgpu_vm_write_pte(adev, vm_update_params->ib,
494                         vm_update_params->pages_addr,
495                         pe, addr, count, incr, flags);
496
497         } else if (count < 3) {
498                 amdgpu_vm_write_pte(adev, vm_update_params->ib, NULL, pe, addr,
499                                     count, incr, flags);
500
501         } else {
502                 amdgpu_vm_set_pte_pde(adev, vm_update_params->ib, pe, addr,
503                                       count, incr, flags);
504         }
505 }
506
507 /**
508  * amdgpu_vm_clear_bo - initially clear the page dir/table
509  *
510  * @adev: amdgpu_device pointer
511  * @bo: bo to clear
512  *
513  * need to reserve bo first before calling it.
514  */
515 static int amdgpu_vm_clear_bo(struct amdgpu_device *adev,
516                               struct amdgpu_vm *vm,
517                               struct amdgpu_bo *bo)
518 {
519         struct amdgpu_ring *ring;
520         struct fence *fence = NULL;
521         struct amdgpu_job *job;
522         struct amdgpu_vm_update_params vm_update_params;
523         unsigned entries;
524         uint64_t addr;
525         int r;
526
527         memset(&vm_update_params, 0, sizeof(vm_update_params));
528         ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
529
530         r = reservation_object_reserve_shared(bo->tbo.resv);
531         if (r)
532                 return r;
533
534         r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
535         if (r)
536                 goto error;
537
538         addr = amdgpu_bo_gpu_offset(bo);
539         entries = amdgpu_bo_size(bo) / 8;
540
541         r = amdgpu_job_alloc_with_ib(adev, 64, &job);
542         if (r)
543                 goto error;
544
545         vm_update_params.ib = &job->ibs[0];
546         amdgpu_vm_update_pages(adev, &vm_update_params, addr, 0, entries,
547                                0, 0);
548         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
549
550         WARN_ON(job->ibs[0].length_dw > 64);
551         r = amdgpu_job_submit(job, ring, &vm->entity,
552                               AMDGPU_FENCE_OWNER_VM, &fence);
553         if (r)
554                 goto error_free;
555
556         amdgpu_bo_fence(bo, fence, true);
557         fence_put(fence);
558         return 0;
559
560 error_free:
561         amdgpu_job_free(job);
562
563 error:
564         return r;
565 }
566
567 /**
568  * amdgpu_vm_map_gart - Resolve gart mapping of addr
569  *
570  * @pages_addr: optional DMA address to use for lookup
571  * @addr: the unmapped addr
572  *
573  * Look up the physical address of the page that the pte resolves
574  * to and return the pointer for the page table entry.
575  */
576 uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
577 {
578         uint64_t result;
579
580         if (pages_addr) {
581                 /* page table offset */
582                 result = pages_addr[addr >> PAGE_SHIFT];
583
584                 /* in case cpu page size != gpu page size*/
585                 result |= addr & (~PAGE_MASK);
586
587         } else {
588                 /* No mapping required */
589                 result = addr;
590         }
591
592         result &= 0xFFFFFFFFFFFFF000ULL;
593
594         return result;
595 }
596
597 /**
598  * amdgpu_vm_update_pdes - make sure that page directory is valid
599  *
600  * @adev: amdgpu_device pointer
601  * @vm: requested vm
602  * @start: start of GPU address range
603  * @end: end of GPU address range
604  *
605  * Allocates new page tables if necessary
606  * and updates the page directory.
607  * Returns 0 for success, error for failure.
608  */
609 int amdgpu_vm_update_page_directory(struct amdgpu_device *adev,
610                                     struct amdgpu_vm *vm)
611 {
612         struct amdgpu_ring *ring;
613         struct amdgpu_bo *pd = vm->page_directory;
614         uint64_t pd_addr = amdgpu_bo_gpu_offset(pd);
615         uint32_t incr = AMDGPU_VM_PTE_COUNT * 8;
616         uint64_t last_pde = ~0, last_pt = ~0;
617         unsigned count = 0, pt_idx, ndw;
618         struct amdgpu_job *job;
619         struct amdgpu_vm_update_params vm_update_params;
620         struct fence *fence = NULL;
621
622         int r;
623
624         memset(&vm_update_params, 0, sizeof(vm_update_params));
625         ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
626
627         /* padding, etc. */
628         ndw = 64;
629
630         /* assume the worst case */
631         ndw += vm->max_pde_used * 6;
632
633         r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
634         if (r)
635                 return r;
636
637         vm_update_params.ib = &job->ibs[0];
638
639         /* walk over the address space and update the page directory */
640         for (pt_idx = 0; pt_idx <= vm->max_pde_used; ++pt_idx) {
641                 struct amdgpu_bo *bo = vm->page_tables[pt_idx].entry.robj;
642                 uint64_t pde, pt;
643
644                 if (bo == NULL)
645                         continue;
646
647                 pt = amdgpu_bo_gpu_offset(bo);
648                 if (vm->page_tables[pt_idx].addr == pt)
649                         continue;
650                 vm->page_tables[pt_idx].addr = pt;
651
652                 pde = pd_addr + pt_idx * 8;
653                 if (((last_pde + 8 * count) != pde) ||
654                     ((last_pt + incr * count) != pt)) {
655
656                         if (count) {
657                                 amdgpu_vm_update_pages(adev, &vm_update_params,
658                                                        last_pde, last_pt,
659                                                        count, incr,
660                                                        AMDGPU_PTE_VALID);
661                         }
662
663                         count = 1;
664                         last_pde = pde;
665                         last_pt = pt;
666                 } else {
667                         ++count;
668                 }
669         }
670
671         if (count)
672                 amdgpu_vm_update_pages(adev, &vm_update_params,
673                                         last_pde, last_pt,
674                                         count, incr, AMDGPU_PTE_VALID);
675
676         if (vm_update_params.ib->length_dw != 0) {
677                 amdgpu_ring_pad_ib(ring, vm_update_params.ib);
678                 amdgpu_sync_resv(adev, &job->sync, pd->tbo.resv,
679                                  AMDGPU_FENCE_OWNER_VM);
680                 WARN_ON(vm_update_params.ib->length_dw > ndw);
681                 r = amdgpu_job_submit(job, ring, &vm->entity,
682                                       AMDGPU_FENCE_OWNER_VM, &fence);
683                 if (r)
684                         goto error_free;
685
686                 amdgpu_bo_fence(pd, fence, true);
687                 fence_put(vm->page_directory_fence);
688                 vm->page_directory_fence = fence_get(fence);
689                 fence_put(fence);
690
691         } else {
692                 amdgpu_job_free(job);
693         }
694
695         return 0;
696
697 error_free:
698         amdgpu_job_free(job);
699         return r;
700 }
701
702 /**
703  * amdgpu_vm_frag_ptes - add fragment information to PTEs
704  *
705  * @adev: amdgpu_device pointer
706  * @vm_update_params: see amdgpu_vm_update_params definition
707  * @pe_start: first PTE to handle
708  * @pe_end: last PTE to handle
709  * @addr: addr those PTEs should point to
710  * @flags: hw mapping flags
711  */
712 static void amdgpu_vm_frag_ptes(struct amdgpu_device *adev,
713                                 struct amdgpu_vm_update_params
714                                         *vm_update_params,
715                                 uint64_t pe_start, uint64_t pe_end,
716                                 uint64_t addr, uint32_t flags)
717 {
718         /**
719          * The MC L1 TLB supports variable sized pages, based on a fragment
720          * field in the PTE. When this field is set to a non-zero value, page
721          * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
722          * flags are considered valid for all PTEs within the fragment range
723          * and corresponding mappings are assumed to be physically contiguous.
724          *
725          * The L1 TLB can store a single PTE for the whole fragment,
726          * significantly increasing the space available for translation
727          * caching. This leads to large improvements in throughput when the
728          * TLB is under pressure.
729          *
730          * The L2 TLB distributes small and large fragments into two
731          * asymmetric partitions. The large fragment cache is significantly
732          * larger. Thus, we try to use large fragments wherever possible.
733          * Userspace can support this by aligning virtual base address and
734          * allocation size to the fragment size.
735          */
736
737         /* SI and newer are optimized for 64KB */
738         uint64_t frag_flags = AMDGPU_PTE_FRAG_64KB;
739         uint64_t frag_align = 0x80;
740
741         uint64_t frag_start = ALIGN(pe_start, frag_align);
742         uint64_t frag_end = pe_end & ~(frag_align - 1);
743
744         unsigned count;
745
746         /* Abort early if there isn't anything to do */
747         if (pe_start == pe_end)
748                 return;
749
750         /* system pages are non continuously */
751         if (vm_update_params->src || vm_update_params->pages_addr ||
752                 !(flags & AMDGPU_PTE_VALID) || (frag_start >= frag_end)) {
753
754                 count = (pe_end - pe_start) / 8;
755                 amdgpu_vm_update_pages(adev, vm_update_params, pe_start,
756                                        addr, count, AMDGPU_GPU_PAGE_SIZE,
757                                        flags);
758                 return;
759         }
760
761         /* handle the 4K area at the beginning */
762         if (pe_start != frag_start) {
763                 count = (frag_start - pe_start) / 8;
764                 amdgpu_vm_update_pages(adev, vm_update_params, pe_start, addr,
765                                        count, AMDGPU_GPU_PAGE_SIZE, flags);
766                 addr += AMDGPU_GPU_PAGE_SIZE * count;
767         }
768
769         /* handle the area in the middle */
770         count = (frag_end - frag_start) / 8;
771         amdgpu_vm_update_pages(adev, vm_update_params, frag_start, addr, count,
772                                AMDGPU_GPU_PAGE_SIZE, flags | frag_flags);
773
774         /* handle the 4K area at the end */
775         if (frag_end != pe_end) {
776                 addr += AMDGPU_GPU_PAGE_SIZE * count;
777                 count = (pe_end - frag_end) / 8;
778                 amdgpu_vm_update_pages(adev, vm_update_params, frag_end, addr,
779                                        count, AMDGPU_GPU_PAGE_SIZE, flags);
780         }
781 }
782
783 /**
784  * amdgpu_vm_update_ptes - make sure that page tables are valid
785  *
786  * @adev: amdgpu_device pointer
787  * @vm_update_params: see amdgpu_vm_update_params definition
788  * @vm: requested vm
789  * @start: start of GPU address range
790  * @end: end of GPU address range
791  * @dst: destination address to map to, the next dst inside the function
792  * @flags: mapping flags
793  *
794  * Update the page tables in the range @start - @end.
795  */
796 static void amdgpu_vm_update_ptes(struct amdgpu_device *adev,
797                                   struct amdgpu_vm_update_params
798                                         *vm_update_params,
799                                   struct amdgpu_vm *vm,
800                                   uint64_t start, uint64_t end,
801                                   uint64_t dst, uint32_t flags)
802 {
803         const uint64_t mask = AMDGPU_VM_PTE_COUNT - 1;
804
805         uint64_t cur_pe_start, cur_pe_end, cur_dst;
806         uint64_t addr; /* next GPU address to be updated */
807         uint64_t pt_idx;
808         struct amdgpu_bo *pt;
809         unsigned nptes; /* next number of ptes to be updated */
810         uint64_t next_pe_start;
811
812         /* initialize the variables */
813         addr = start;
814         pt_idx = addr >> amdgpu_vm_block_size;
815         pt = vm->page_tables[pt_idx].entry.robj;
816
817         if ((addr & ~mask) == (end & ~mask))
818                 nptes = end - addr;
819         else
820                 nptes = AMDGPU_VM_PTE_COUNT - (addr & mask);
821
822         cur_pe_start = amdgpu_bo_gpu_offset(pt);
823         cur_pe_start += (addr & mask) * 8;
824         cur_pe_end = cur_pe_start + 8 * nptes;
825         cur_dst = dst;
826
827         /* for next ptb*/
828         addr += nptes;
829         dst += nptes * AMDGPU_GPU_PAGE_SIZE;
830
831         /* walk over the address space and update the page tables */
832         while (addr < end) {
833                 pt_idx = addr >> amdgpu_vm_block_size;
834                 pt = vm->page_tables[pt_idx].entry.robj;
835
836                 if ((addr & ~mask) == (end & ~mask))
837                         nptes = end - addr;
838                 else
839                         nptes = AMDGPU_VM_PTE_COUNT - (addr & mask);
840
841                 next_pe_start = amdgpu_bo_gpu_offset(pt);
842                 next_pe_start += (addr & mask) * 8;
843
844                 if (cur_pe_end == next_pe_start) {
845                         /* The next ptb is consecutive to current ptb.
846                          * Don't call amdgpu_vm_frag_ptes now.
847                          * Will update two ptbs together in future.
848                         */
849                         cur_pe_end += 8 * nptes;
850                 } else {
851                         amdgpu_vm_frag_ptes(adev, vm_update_params,
852                                             cur_pe_start, cur_pe_end,
853                                             cur_dst, flags);
854
855                         cur_pe_start = next_pe_start;
856                         cur_pe_end = next_pe_start + 8 * nptes;
857                         cur_dst = dst;
858                 }
859
860                 /* for next ptb*/
861                 addr += nptes;
862                 dst += nptes * AMDGPU_GPU_PAGE_SIZE;
863         }
864
865         amdgpu_vm_frag_ptes(adev, vm_update_params, cur_pe_start,
866                             cur_pe_end, cur_dst, flags);
867 }
868
869 /**
870  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
871  *
872  * @adev: amdgpu_device pointer
873  * @exclusive: fence we need to sync to
874  * @src: address where to copy page table entries from
875  * @pages_addr: DMA addresses to use for mapping
876  * @vm: requested vm
877  * @start: start of mapped range
878  * @last: last mapped entry
879  * @flags: flags for the entries
880  * @addr: addr to set the area to
881  * @fence: optional resulting fence
882  *
883  * Fill in the page table entries between @start and @last.
884  * Returns 0 for success, -EINVAL for failure.
885  */
886 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
887                                        struct fence *exclusive,
888                                        uint64_t src,
889                                        dma_addr_t *pages_addr,
890                                        struct amdgpu_vm *vm,
891                                        uint64_t start, uint64_t last,
892                                        uint32_t flags, uint64_t addr,
893                                        struct fence **fence)
894 {
895         struct amdgpu_ring *ring;
896         void *owner = AMDGPU_FENCE_OWNER_VM;
897         unsigned nptes, ncmds, ndw;
898         struct amdgpu_job *job;
899         struct amdgpu_vm_update_params vm_update_params;
900         struct fence *f = NULL;
901         int r;
902
903         ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
904         memset(&vm_update_params, 0, sizeof(vm_update_params));
905         vm_update_params.src = src;
906         vm_update_params.pages_addr = pages_addr;
907
908         /* sync to everything on unmapping */
909         if (!(flags & AMDGPU_PTE_VALID))
910                 owner = AMDGPU_FENCE_OWNER_UNDEFINED;
911
912         nptes = last - start + 1;
913
914         /*
915          * reserve space for one command every (1 << BLOCK_SIZE)
916          *  entries or 2k dwords (whatever is smaller)
917          */
918         ncmds = (nptes >> min(amdgpu_vm_block_size, 11)) + 1;
919
920         /* padding, etc. */
921         ndw = 64;
922
923         if (vm_update_params.src) {
924                 /* only copy commands needed */
925                 ndw += ncmds * 7;
926
927         } else if (vm_update_params.pages_addr) {
928                 /* header for write data commands */
929                 ndw += ncmds * 4;
930
931                 /* body of write data command */
932                 ndw += nptes * 2;
933
934         } else {
935                 /* set page commands needed */
936                 ndw += ncmds * 10;
937
938                 /* two extra commands for begin/end of fragment */
939                 ndw += 2 * 10;
940         }
941
942         r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
943         if (r)
944                 return r;
945
946         vm_update_params.ib = &job->ibs[0];
947
948         r = amdgpu_sync_fence(adev, &job->sync, exclusive);
949         if (r)
950                 goto error_free;
951
952         r = amdgpu_sync_resv(adev, &job->sync, vm->page_directory->tbo.resv,
953                              owner);
954         if (r)
955                 goto error_free;
956
957         r = reservation_object_reserve_shared(vm->page_directory->tbo.resv);
958         if (r)
959                 goto error_free;
960
961         amdgpu_vm_update_ptes(adev, &vm_update_params, vm, start,
962                               last + 1, addr, flags);
963
964         amdgpu_ring_pad_ib(ring, vm_update_params.ib);
965         WARN_ON(vm_update_params.ib->length_dw > ndw);
966         r = amdgpu_job_submit(job, ring, &vm->entity,
967                               AMDGPU_FENCE_OWNER_VM, &f);
968         if (r)
969                 goto error_free;
970
971         amdgpu_bo_fence(vm->page_directory, f, true);
972         if (fence) {
973                 fence_put(*fence);
974                 *fence = fence_get(f);
975         }
976         fence_put(f);
977         return 0;
978
979 error_free:
980         amdgpu_job_free(job);
981         return r;
982 }
983
984 /**
985  * amdgpu_vm_bo_split_mapping - split a mapping into smaller chunks
986  *
987  * @adev: amdgpu_device pointer
988  * @exclusive: fence we need to sync to
989  * @gtt_flags: flags as they are used for GTT
990  * @pages_addr: DMA addresses to use for mapping
991  * @vm: requested vm
992  * @mapping: mapped range and flags to use for the update
993  * @addr: addr to set the area to
994  * @flags: HW flags for the mapping
995  * @fence: optional resulting fence
996  *
997  * Split the mapping into smaller chunks so that each update fits
998  * into a SDMA IB.
999  * Returns 0 for success, -EINVAL for failure.
1000  */
1001 static int amdgpu_vm_bo_split_mapping(struct amdgpu_device *adev,
1002                                       struct fence *exclusive,
1003                                       uint32_t gtt_flags,
1004                                       dma_addr_t *pages_addr,
1005                                       struct amdgpu_vm *vm,
1006                                       struct amdgpu_bo_va_mapping *mapping,
1007                                       uint32_t flags, uint64_t addr,
1008                                       struct fence **fence)
1009 {
1010         const uint64_t max_size = 64ULL * 1024ULL * 1024ULL / AMDGPU_GPU_PAGE_SIZE;
1011
1012         uint64_t src = 0, start = mapping->it.start;
1013         int r;
1014
1015         /* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1016          * but in case of something, we filter the flags in first place
1017          */
1018         if (!(mapping->flags & AMDGPU_PTE_READABLE))
1019                 flags &= ~AMDGPU_PTE_READABLE;
1020         if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1021                 flags &= ~AMDGPU_PTE_WRITEABLE;
1022
1023         trace_amdgpu_vm_bo_update(mapping);
1024
1025         if (pages_addr) {
1026                 if (flags == gtt_flags)
1027                         src = adev->gart.table_addr + (addr >> 12) * 8;
1028                 addr = 0;
1029         }
1030         addr += mapping->offset;
1031
1032         if (!pages_addr || src)
1033                 return amdgpu_vm_bo_update_mapping(adev, exclusive,
1034                                                    src, pages_addr, vm,
1035                                                    start, mapping->it.last,
1036                                                    flags, addr, fence);
1037
1038         while (start != mapping->it.last + 1) {
1039                 uint64_t last;
1040
1041                 last = min((uint64_t)mapping->it.last, start + max_size - 1);
1042                 r = amdgpu_vm_bo_update_mapping(adev, exclusive,
1043                                                 src, pages_addr, vm,
1044                                                 start, last, flags, addr,
1045                                                 fence);
1046                 if (r)
1047                         return r;
1048
1049                 start = last + 1;
1050                 addr += max_size * AMDGPU_GPU_PAGE_SIZE;
1051         }
1052
1053         return 0;
1054 }
1055
1056 /**
1057  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1058  *
1059  * @adev: amdgpu_device pointer
1060  * @bo_va: requested BO and VM object
1061  * @mem: ttm mem
1062  *
1063  * Fill in the page table entries for @bo_va.
1064  * Returns 0 for success, -EINVAL for failure.
1065  *
1066  * Object have to be reserved and mutex must be locked!
1067  */
1068 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
1069                         struct amdgpu_bo_va *bo_va,
1070                         struct ttm_mem_reg *mem)
1071 {
1072         struct amdgpu_vm *vm = bo_va->vm;
1073         struct amdgpu_bo_va_mapping *mapping;
1074         dma_addr_t *pages_addr = NULL;
1075         uint32_t gtt_flags, flags;
1076         struct fence *exclusive;
1077         uint64_t addr;
1078         int r;
1079
1080         if (mem) {
1081                 struct ttm_dma_tt *ttm;
1082
1083                 addr = (u64)mem->start << PAGE_SHIFT;
1084                 switch (mem->mem_type) {
1085                 case TTM_PL_TT:
1086                         ttm = container_of(bo_va->bo->tbo.ttm, struct
1087                                            ttm_dma_tt, ttm);
1088                         pages_addr = ttm->dma_address;
1089                         break;
1090
1091                 case TTM_PL_VRAM:
1092                         addr += adev->vm_manager.vram_base_offset;
1093                         break;
1094
1095                 default:
1096                         break;
1097                 }
1098
1099                 exclusive = reservation_object_get_excl(bo_va->bo->tbo.resv);
1100         } else {
1101                 addr = 0;
1102                 exclusive = NULL;
1103         }
1104
1105         flags = amdgpu_ttm_tt_pte_flags(adev, bo_va->bo->tbo.ttm, mem);
1106         gtt_flags = (adev == bo_va->bo->adev) ? flags : 0;
1107
1108         spin_lock(&vm->status_lock);
1109         if (!list_empty(&bo_va->vm_status))
1110                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1111         spin_unlock(&vm->status_lock);
1112
1113         list_for_each_entry(mapping, &bo_va->invalids, list) {
1114                 r = amdgpu_vm_bo_split_mapping(adev, exclusive,
1115                                                gtt_flags, pages_addr, vm,
1116                                                mapping, flags, addr,
1117                                                &bo_va->last_pt_update);
1118                 if (r)
1119                         return r;
1120         }
1121
1122         if (trace_amdgpu_vm_bo_mapping_enabled()) {
1123                 list_for_each_entry(mapping, &bo_va->valids, list)
1124                         trace_amdgpu_vm_bo_mapping(mapping);
1125
1126                 list_for_each_entry(mapping, &bo_va->invalids, list)
1127                         trace_amdgpu_vm_bo_mapping(mapping);
1128         }
1129
1130         spin_lock(&vm->status_lock);
1131         list_splice_init(&bo_va->invalids, &bo_va->valids);
1132         list_del_init(&bo_va->vm_status);
1133         if (!mem)
1134                 list_add(&bo_va->vm_status, &vm->cleared);
1135         spin_unlock(&vm->status_lock);
1136
1137         return 0;
1138 }
1139
1140 /**
1141  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1142  *
1143  * @adev: amdgpu_device pointer
1144  * @vm: requested vm
1145  *
1146  * Make sure all freed BOs are cleared in the PT.
1147  * Returns 0 for success.
1148  *
1149  * PTs have to be reserved and mutex must be locked!
1150  */
1151 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
1152                           struct amdgpu_vm *vm)
1153 {
1154         struct amdgpu_bo_va_mapping *mapping;
1155         int r;
1156
1157         while (!list_empty(&vm->freed)) {
1158                 mapping = list_first_entry(&vm->freed,
1159                         struct amdgpu_bo_va_mapping, list);
1160                 list_del(&mapping->list);
1161
1162                 r = amdgpu_vm_bo_split_mapping(adev, NULL, 0, NULL, vm, mapping,
1163                                                0, 0, NULL);
1164                 kfree(mapping);
1165                 if (r)
1166                         return r;
1167
1168         }
1169         return 0;
1170
1171 }
1172
1173 /**
1174  * amdgpu_vm_clear_invalids - clear invalidated BOs in the PT
1175  *
1176  * @adev: amdgpu_device pointer
1177  * @vm: requested vm
1178  *
1179  * Make sure all invalidated BOs are cleared in the PT.
1180  * Returns 0 for success.
1181  *
1182  * PTs have to be reserved and mutex must be locked!
1183  */
1184 int amdgpu_vm_clear_invalids(struct amdgpu_device *adev,
1185                              struct amdgpu_vm *vm, struct amdgpu_sync *sync)
1186 {
1187         struct amdgpu_bo_va *bo_va = NULL;
1188         int r = 0;
1189
1190         spin_lock(&vm->status_lock);
1191         while (!list_empty(&vm->invalidated)) {
1192                 bo_va = list_first_entry(&vm->invalidated,
1193                         struct amdgpu_bo_va, vm_status);
1194                 spin_unlock(&vm->status_lock);
1195
1196                 r = amdgpu_vm_bo_update(adev, bo_va, NULL);
1197                 if (r)
1198                         return r;
1199
1200                 spin_lock(&vm->status_lock);
1201         }
1202         spin_unlock(&vm->status_lock);
1203
1204         if (bo_va)
1205                 r = amdgpu_sync_fence(adev, sync, bo_va->last_pt_update);
1206
1207         return r;
1208 }
1209
1210 /**
1211  * amdgpu_vm_bo_add - add a bo to a specific vm
1212  *
1213  * @adev: amdgpu_device pointer
1214  * @vm: requested vm
1215  * @bo: amdgpu buffer object
1216  *
1217  * Add @bo into the requested vm.
1218  * Add @bo to the list of bos associated with the vm
1219  * Returns newly added bo_va or NULL for failure
1220  *
1221  * Object has to be reserved!
1222  */
1223 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
1224                                       struct amdgpu_vm *vm,
1225                                       struct amdgpu_bo *bo)
1226 {
1227         struct amdgpu_bo_va *bo_va;
1228
1229         bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
1230         if (bo_va == NULL) {
1231                 return NULL;
1232         }
1233         bo_va->vm = vm;
1234         bo_va->bo = bo;
1235         bo_va->ref_count = 1;
1236         INIT_LIST_HEAD(&bo_va->bo_list);
1237         INIT_LIST_HEAD(&bo_va->valids);
1238         INIT_LIST_HEAD(&bo_va->invalids);
1239         INIT_LIST_HEAD(&bo_va->vm_status);
1240
1241         list_add_tail(&bo_va->bo_list, &bo->va);
1242
1243         return bo_va;
1244 }
1245
1246 /**
1247  * amdgpu_vm_bo_map - map bo inside a vm
1248  *
1249  * @adev: amdgpu_device pointer
1250  * @bo_va: bo_va to store the address
1251  * @saddr: where to map the BO
1252  * @offset: requested offset in the BO
1253  * @flags: attributes of pages (read/write/valid/etc.)
1254  *
1255  * Add a mapping of the BO at the specefied addr into the VM.
1256  * Returns 0 for success, error for failure.
1257  *
1258  * Object has to be reserved and unreserved outside!
1259  */
1260 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1261                      struct amdgpu_bo_va *bo_va,
1262                      uint64_t saddr, uint64_t offset,
1263                      uint64_t size, uint32_t flags)
1264 {
1265         struct amdgpu_bo_va_mapping *mapping;
1266         struct amdgpu_vm *vm = bo_va->vm;
1267         struct interval_tree_node *it;
1268         unsigned last_pfn, pt_idx;
1269         uint64_t eaddr;
1270         int r;
1271
1272         /* validate the parameters */
1273         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1274             size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1275                 return -EINVAL;
1276
1277         /* make sure object fit at this offset */
1278         eaddr = saddr + size - 1;
1279         if ((saddr >= eaddr) || (offset + size > amdgpu_bo_size(bo_va->bo)))
1280                 return -EINVAL;
1281
1282         last_pfn = eaddr / AMDGPU_GPU_PAGE_SIZE;
1283         if (last_pfn >= adev->vm_manager.max_pfn) {
1284                 dev_err(adev->dev, "va above limit (0x%08X >= 0x%08X)\n",
1285                         last_pfn, adev->vm_manager.max_pfn);
1286                 return -EINVAL;
1287         }
1288
1289         saddr /= AMDGPU_GPU_PAGE_SIZE;
1290         eaddr /= AMDGPU_GPU_PAGE_SIZE;
1291
1292         it = interval_tree_iter_first(&vm->va, saddr, eaddr);
1293         if (it) {
1294                 struct amdgpu_bo_va_mapping *tmp;
1295                 tmp = container_of(it, struct amdgpu_bo_va_mapping, it);
1296                 /* bo and tmp overlap, invalid addr */
1297                 dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1298                         "0x%010lx-0x%010lx\n", bo_va->bo, saddr, eaddr,
1299                         tmp->it.start, tmp->it.last + 1);
1300                 r = -EINVAL;
1301                 goto error;
1302         }
1303
1304         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1305         if (!mapping) {
1306                 r = -ENOMEM;
1307                 goto error;
1308         }
1309
1310         INIT_LIST_HEAD(&mapping->list);
1311         mapping->it.start = saddr;
1312         mapping->it.last = eaddr;
1313         mapping->offset = offset;
1314         mapping->flags = flags;
1315
1316         list_add(&mapping->list, &bo_va->invalids);
1317         interval_tree_insert(&mapping->it, &vm->va);
1318
1319         /* Make sure the page tables are allocated */
1320         saddr >>= amdgpu_vm_block_size;
1321         eaddr >>= amdgpu_vm_block_size;
1322
1323         BUG_ON(eaddr >= amdgpu_vm_num_pdes(adev));
1324
1325         if (eaddr > vm->max_pde_used)
1326                 vm->max_pde_used = eaddr;
1327
1328         /* walk over the address space and allocate the page tables */
1329         for (pt_idx = saddr; pt_idx <= eaddr; ++pt_idx) {
1330                 struct reservation_object *resv = vm->page_directory->tbo.resv;
1331                 struct amdgpu_bo_list_entry *entry;
1332                 struct amdgpu_bo *pt;
1333
1334                 entry = &vm->page_tables[pt_idx].entry;
1335                 if (entry->robj)
1336                         continue;
1337
1338                 r = amdgpu_bo_create(adev, AMDGPU_VM_PTE_COUNT * 8,
1339                                      AMDGPU_GPU_PAGE_SIZE, true,
1340                                      AMDGPU_GEM_DOMAIN_VRAM,
1341                                      AMDGPU_GEM_CREATE_NO_CPU_ACCESS,
1342                                      NULL, resv, &pt);
1343                 if (r)
1344                         goto error_free;
1345
1346                 /* Keep a reference to the page table to avoid freeing
1347                  * them up in the wrong order.
1348                  */
1349                 pt->parent = amdgpu_bo_ref(vm->page_directory);
1350
1351                 r = amdgpu_vm_clear_bo(adev, vm, pt);
1352                 if (r) {
1353                         amdgpu_bo_unref(&pt);
1354                         goto error_free;
1355                 }
1356
1357                 entry->robj = pt;
1358                 entry->priority = 0;
1359                 entry->tv.bo = &entry->robj->tbo;
1360                 entry->tv.shared = true;
1361                 entry->user_pages = NULL;
1362                 vm->page_tables[pt_idx].addr = 0;
1363         }
1364
1365         return 0;
1366
1367 error_free:
1368         list_del(&mapping->list);
1369         interval_tree_remove(&mapping->it, &vm->va);
1370         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1371         kfree(mapping);
1372
1373 error:
1374         return r;
1375 }
1376
1377 /**
1378  * amdgpu_vm_bo_unmap - remove bo mapping from vm
1379  *
1380  * @adev: amdgpu_device pointer
1381  * @bo_va: bo_va to remove the address from
1382  * @saddr: where to the BO is mapped
1383  *
1384  * Remove a mapping of the BO at the specefied addr from the VM.
1385  * Returns 0 for success, error for failure.
1386  *
1387  * Object has to be reserved and unreserved outside!
1388  */
1389 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
1390                        struct amdgpu_bo_va *bo_va,
1391                        uint64_t saddr)
1392 {
1393         struct amdgpu_bo_va_mapping *mapping;
1394         struct amdgpu_vm *vm = bo_va->vm;
1395         bool valid = true;
1396
1397         saddr /= AMDGPU_GPU_PAGE_SIZE;
1398
1399         list_for_each_entry(mapping, &bo_va->valids, list) {
1400                 if (mapping->it.start == saddr)
1401                         break;
1402         }
1403
1404         if (&mapping->list == &bo_va->valids) {
1405                 valid = false;
1406
1407                 list_for_each_entry(mapping, &bo_va->invalids, list) {
1408                         if (mapping->it.start == saddr)
1409                                 break;
1410                 }
1411
1412                 if (&mapping->list == &bo_va->invalids)
1413                         return -ENOENT;
1414         }
1415
1416         list_del(&mapping->list);
1417         interval_tree_remove(&mapping->it, &vm->va);
1418         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1419
1420         if (valid)
1421                 list_add(&mapping->list, &vm->freed);
1422         else
1423                 kfree(mapping);
1424
1425         return 0;
1426 }
1427
1428 /**
1429  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
1430  *
1431  * @adev: amdgpu_device pointer
1432  * @bo_va: requested bo_va
1433  *
1434  * Remove @bo_va->bo from the requested vm.
1435  *
1436  * Object have to be reserved!
1437  */
1438 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
1439                       struct amdgpu_bo_va *bo_va)
1440 {
1441         struct amdgpu_bo_va_mapping *mapping, *next;
1442         struct amdgpu_vm *vm = bo_va->vm;
1443
1444         list_del(&bo_va->bo_list);
1445
1446         spin_lock(&vm->status_lock);
1447         list_del(&bo_va->vm_status);
1448         spin_unlock(&vm->status_lock);
1449
1450         list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
1451                 list_del(&mapping->list);
1452                 interval_tree_remove(&mapping->it, &vm->va);
1453                 trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1454                 list_add(&mapping->list, &vm->freed);
1455         }
1456         list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
1457                 list_del(&mapping->list);
1458                 interval_tree_remove(&mapping->it, &vm->va);
1459                 kfree(mapping);
1460         }
1461
1462         fence_put(bo_va->last_pt_update);
1463         kfree(bo_va);
1464 }
1465
1466 /**
1467  * amdgpu_vm_bo_invalidate - mark the bo as invalid
1468  *
1469  * @adev: amdgpu_device pointer
1470  * @vm: requested vm
1471  * @bo: amdgpu buffer object
1472  *
1473  * Mark @bo as invalid.
1474  */
1475 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
1476                              struct amdgpu_bo *bo)
1477 {
1478         struct amdgpu_bo_va *bo_va;
1479
1480         list_for_each_entry(bo_va, &bo->va, bo_list) {
1481                 spin_lock(&bo_va->vm->status_lock);
1482                 if (list_empty(&bo_va->vm_status))
1483                         list_add(&bo_va->vm_status, &bo_va->vm->invalidated);
1484                 spin_unlock(&bo_va->vm->status_lock);
1485         }
1486 }
1487
1488 /**
1489  * amdgpu_vm_init - initialize a vm instance
1490  *
1491  * @adev: amdgpu_device pointer
1492  * @vm: requested vm
1493  *
1494  * Init @vm fields.
1495  */
1496 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1497 {
1498         const unsigned align = min(AMDGPU_VM_PTB_ALIGN_SIZE,
1499                 AMDGPU_VM_PTE_COUNT * 8);
1500         unsigned pd_size, pd_entries;
1501         unsigned ring_instance;
1502         struct amdgpu_ring *ring;
1503         struct amd_sched_rq *rq;
1504         int i, r;
1505
1506         for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
1507                 vm->ids[i] = NULL;
1508         vm->va = RB_ROOT;
1509         vm->client_id = atomic64_inc_return(&adev->vm_manager.client_counter);
1510         spin_lock_init(&vm->status_lock);
1511         INIT_LIST_HEAD(&vm->invalidated);
1512         INIT_LIST_HEAD(&vm->cleared);
1513         INIT_LIST_HEAD(&vm->freed);
1514
1515         pd_size = amdgpu_vm_directory_size(adev);
1516         pd_entries = amdgpu_vm_num_pdes(adev);
1517
1518         /* allocate page table array */
1519         vm->page_tables = drm_calloc_large(pd_entries, sizeof(struct amdgpu_vm_pt));
1520         if (vm->page_tables == NULL) {
1521                 DRM_ERROR("Cannot allocate memory for page table array\n");
1522                 return -ENOMEM;
1523         }
1524
1525         /* create scheduler entity for page table updates */
1526
1527         ring_instance = atomic_inc_return(&adev->vm_manager.vm_pte_next_ring);
1528         ring_instance %= adev->vm_manager.vm_pte_num_rings;
1529         ring = adev->vm_manager.vm_pte_rings[ring_instance];
1530         rq = &ring->sched.sched_rq[AMD_SCHED_PRIORITY_KERNEL];
1531         r = amd_sched_entity_init(&ring->sched, &vm->entity,
1532                                   rq, amdgpu_sched_jobs);
1533         if (r)
1534                 return r;
1535
1536         vm->page_directory_fence = NULL;
1537
1538         r = amdgpu_bo_create(adev, pd_size, align, true,
1539                              AMDGPU_GEM_DOMAIN_VRAM,
1540                              AMDGPU_GEM_CREATE_NO_CPU_ACCESS,
1541                              NULL, NULL, &vm->page_directory);
1542         if (r)
1543                 goto error_free_sched_entity;
1544
1545         r = amdgpu_bo_reserve(vm->page_directory, false);
1546         if (r)
1547                 goto error_free_page_directory;
1548
1549         r = amdgpu_vm_clear_bo(adev, vm, vm->page_directory);
1550         amdgpu_bo_unreserve(vm->page_directory);
1551         if (r)
1552                 goto error_free_page_directory;
1553         vm->last_eviction_counter = atomic64_read(&adev->num_evictions);
1554
1555         return 0;
1556
1557 error_free_page_directory:
1558         amdgpu_bo_unref(&vm->page_directory);
1559         vm->page_directory = NULL;
1560
1561 error_free_sched_entity:
1562         amd_sched_entity_fini(&ring->sched, &vm->entity);
1563
1564         return r;
1565 }
1566
1567 /**
1568  * amdgpu_vm_fini - tear down a vm instance
1569  *
1570  * @adev: amdgpu_device pointer
1571  * @vm: requested vm
1572  *
1573  * Tear down @vm.
1574  * Unbind the VM and remove all bos from the vm bo list
1575  */
1576 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1577 {
1578         struct amdgpu_bo_va_mapping *mapping, *tmp;
1579         int i;
1580
1581         amd_sched_entity_fini(vm->entity.sched, &vm->entity);
1582
1583         if (!RB_EMPTY_ROOT(&vm->va)) {
1584                 dev_err(adev->dev, "still active bo inside vm\n");
1585         }
1586         rbtree_postorder_for_each_entry_safe(mapping, tmp, &vm->va, it.rb) {
1587                 list_del(&mapping->list);
1588                 interval_tree_remove(&mapping->it, &vm->va);
1589                 kfree(mapping);
1590         }
1591         list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
1592                 list_del(&mapping->list);
1593                 kfree(mapping);
1594         }
1595
1596         for (i = 0; i < amdgpu_vm_num_pdes(adev); i++)
1597                 amdgpu_bo_unref(&vm->page_tables[i].entry.robj);
1598         drm_free_large(vm->page_tables);
1599
1600         amdgpu_bo_unref(&vm->page_directory);
1601         fence_put(vm->page_directory_fence);
1602 }
1603
1604 /**
1605  * amdgpu_vm_manager_init - init the VM manager
1606  *
1607  * @adev: amdgpu_device pointer
1608  *
1609  * Initialize the VM manager structures
1610  */
1611 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
1612 {
1613         unsigned i;
1614
1615         INIT_LIST_HEAD(&adev->vm_manager.ids_lru);
1616
1617         /* skip over VMID 0, since it is the system VM */
1618         for (i = 1; i < adev->vm_manager.num_ids; ++i) {
1619                 amdgpu_vm_reset_id(adev, i);
1620                 amdgpu_sync_create(&adev->vm_manager.ids[i].active);
1621                 list_add_tail(&adev->vm_manager.ids[i].list,
1622                               &adev->vm_manager.ids_lru);
1623         }
1624
1625         adev->vm_manager.fence_context = fence_context_alloc(AMDGPU_MAX_RINGS);
1626         for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
1627                 adev->vm_manager.seqno[i] = 0;
1628
1629         atomic_set(&adev->vm_manager.vm_pte_next_ring, 0);
1630         atomic64_set(&adev->vm_manager.client_counter, 0);
1631 }
1632
1633 /**
1634  * amdgpu_vm_manager_fini - cleanup VM manager
1635  *
1636  * @adev: amdgpu_device pointer
1637  *
1638  * Cleanup the VM manager and free resources.
1639  */
1640 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
1641 {
1642         unsigned i;
1643
1644         for (i = 0; i < AMDGPU_NUM_VM; ++i) {
1645                 struct amdgpu_vm_id *id = &adev->vm_manager.ids[i];
1646
1647                 fence_put(adev->vm_manager.ids[i].first);
1648                 amdgpu_sync_free(&adev->vm_manager.ids[i].active);
1649                 fence_put(id->flushed_updates);
1650         }
1651 }