drm/amdgpu: no updates shouldn't cause vm flush v2
[firefly-linux-kernel-4.4.55.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 <drm/drmP.h>
29 #include <drm/amdgpu_drm.h>
30 #include "amdgpu.h"
31 #include "amdgpu_trace.h"
32
33 /*
34  * GPUVM
35  * GPUVM is similar to the legacy gart on older asics, however
36  * rather than there being a single global gart table
37  * for the entire GPU, there are multiple VM page tables active
38  * at any given time.  The VM page tables can contain a mix
39  * vram pages and system memory pages and system memory pages
40  * can be mapped as snooped (cached system pages) or unsnooped
41  * (uncached system pages).
42  * Each VM has an ID associated with it and there is a page table
43  * associated with each VMID.  When execting a command buffer,
44  * the kernel tells the the ring what VMID to use for that command
45  * buffer.  VMIDs are allocated dynamically as commands are submitted.
46  * The userspace drivers maintain their own address space and the kernel
47  * sets up their pages tables accordingly when they submit their
48  * command buffers and a VMID is assigned.
49  * Cayman/Trinity support up to 8 active VMs at any given time;
50  * SI supports 16.
51  */
52
53 /**
54  * amdgpu_vm_num_pde - return the number of page directory entries
55  *
56  * @adev: amdgpu_device pointer
57  *
58  * Calculate the number of page directory entries (cayman+).
59  */
60 static unsigned amdgpu_vm_num_pdes(struct amdgpu_device *adev)
61 {
62         return adev->vm_manager.max_pfn >> amdgpu_vm_block_size;
63 }
64
65 /**
66  * amdgpu_vm_directory_size - returns the size of the page directory in bytes
67  *
68  * @adev: amdgpu_device pointer
69  *
70  * Calculate the size of the page directory in bytes (cayman+).
71  */
72 static unsigned amdgpu_vm_directory_size(struct amdgpu_device *adev)
73 {
74         return AMDGPU_GPU_PAGE_ALIGN(amdgpu_vm_num_pdes(adev) * 8);
75 }
76
77 /**
78  * amdgpu_vm_get_bos - add the vm BOs to a validation list
79  *
80  * @vm: vm providing the BOs
81  * @head: head of validation list
82  *
83  * Add the page directory to the list of BOs to
84  * validate for command submission (cayman+).
85  */
86 struct amdgpu_bo_list_entry *amdgpu_vm_get_bos(struct amdgpu_device *adev,
87                                           struct amdgpu_vm *vm,
88                                           struct list_head *head)
89 {
90         struct amdgpu_bo_list_entry *list;
91         unsigned i, idx;
92
93         mutex_lock(&vm->mutex);
94         list = drm_malloc_ab(vm->max_pde_used + 2,
95                              sizeof(struct amdgpu_bo_list_entry));
96         if (!list) {
97                 mutex_unlock(&vm->mutex);
98                 return NULL;
99         }
100
101         /* add the vm page table to the list */
102         list[0].robj = vm->page_directory;
103         list[0].prefered_domains = AMDGPU_GEM_DOMAIN_VRAM;
104         list[0].allowed_domains = AMDGPU_GEM_DOMAIN_VRAM;
105         list[0].priority = 0;
106         list[0].tv.bo = &vm->page_directory->tbo;
107         list[0].tv.shared = true;
108         list_add(&list[0].tv.head, head);
109
110         for (i = 0, idx = 1; i <= vm->max_pde_used; i++) {
111                 if (!vm->page_tables[i].bo)
112                         continue;
113
114                 list[idx].robj = vm->page_tables[i].bo;
115                 list[idx].prefered_domains = AMDGPU_GEM_DOMAIN_VRAM;
116                 list[idx].allowed_domains = AMDGPU_GEM_DOMAIN_VRAM;
117                 list[idx].priority = 0;
118                 list[idx].tv.bo = &list[idx].robj->tbo;
119                 list[idx].tv.shared = true;
120                 list_add(&list[idx++].tv.head, head);
121         }
122         mutex_unlock(&vm->mutex);
123
124         return list;
125 }
126
127 /**
128  * amdgpu_vm_grab_id - allocate the next free VMID
129  *
130  * @ring: ring we want to submit job to
131  * @vm: vm to allocate id for
132  *
133  * Allocate an id for the vm (cayman+).
134  * Returns the fence we need to sync to (if any).
135  *
136  * Global and local mutex must be locked!
137  */
138 struct amdgpu_fence *amdgpu_vm_grab_id(struct amdgpu_ring *ring,
139                                        struct amdgpu_vm *vm)
140 {
141         struct amdgpu_fence *best[AMDGPU_MAX_RINGS] = {};
142         struct amdgpu_vm_id *vm_id = &vm->ids[ring->idx];
143         struct amdgpu_device *adev = ring->adev;
144
145         unsigned choices[2] = {};
146         unsigned i;
147
148         /* check if the id is still valid */
149         if (vm_id->id && vm_id->last_id_use &&
150             vm_id->last_id_use == adev->vm_manager.active[vm_id->id])
151                 return NULL;
152
153         /* we definately need to flush */
154         vm_id->pd_gpu_addr = ~0ll;
155
156         /* skip over VMID 0, since it is the system VM */
157         for (i = 1; i < adev->vm_manager.nvm; ++i) {
158                 struct amdgpu_fence *fence = adev->vm_manager.active[i];
159
160                 if (fence == NULL) {
161                         /* found a free one */
162                         vm_id->id = i;
163                         trace_amdgpu_vm_grab_id(i, ring->idx);
164                         return NULL;
165                 }
166
167                 if (amdgpu_fence_is_earlier(fence, best[fence->ring->idx])) {
168                         best[fence->ring->idx] = fence;
169                         choices[fence->ring == ring ? 0 : 1] = i;
170                 }
171         }
172
173         for (i = 0; i < 2; ++i) {
174                 if (choices[i]) {
175                         vm_id->id = choices[i];
176                         trace_amdgpu_vm_grab_id(choices[i], ring->idx);
177                         return adev->vm_manager.active[choices[i]];
178                 }
179         }
180
181         /* should never happen */
182         BUG();
183         return NULL;
184 }
185
186 /**
187  * amdgpu_vm_flush - hardware flush the vm
188  *
189  * @ring: ring to use for flush
190  * @vm: vm we want to flush
191  * @updates: last vm update that we waited for
192  *
193  * Flush the vm (cayman+).
194  *
195  * Global and local mutex must be locked!
196  */
197 void amdgpu_vm_flush(struct amdgpu_ring *ring,
198                      struct amdgpu_vm *vm,
199                      struct amdgpu_fence *updates)
200 {
201         uint64_t pd_addr = amdgpu_bo_gpu_offset(vm->page_directory);
202         struct amdgpu_vm_id *vm_id = &vm->ids[ring->idx];
203         struct amdgpu_fence *flushed_updates = vm_id->flushed_updates;
204
205         if (pd_addr != vm_id->pd_gpu_addr || !flushed_updates ||
206             (updates && amdgpu_fence_is_earlier(flushed_updates, updates))) {
207
208                 trace_amdgpu_vm_flush(pd_addr, ring->idx, vm_id->id);
209                 vm_id->flushed_updates = amdgpu_fence_ref(
210                         amdgpu_fence_later(flushed_updates, updates));
211                 amdgpu_fence_unref(&flushed_updates);
212                 vm_id->pd_gpu_addr = pd_addr;
213                 amdgpu_ring_emit_vm_flush(ring, vm_id->id, vm_id->pd_gpu_addr);
214         }
215 }
216
217 /**
218  * amdgpu_vm_fence - remember fence for vm
219  *
220  * @adev: amdgpu_device pointer
221  * @vm: vm we want to fence
222  * @fence: fence to remember
223  *
224  * Fence the vm (cayman+).
225  * Set the fence used to protect page table and id.
226  *
227  * Global and local mutex must be locked!
228  */
229 void amdgpu_vm_fence(struct amdgpu_device *adev,
230                      struct amdgpu_vm *vm,
231                      struct amdgpu_fence *fence)
232 {
233         unsigned ridx = fence->ring->idx;
234         unsigned vm_id = vm->ids[ridx].id;
235
236         amdgpu_fence_unref(&adev->vm_manager.active[vm_id]);
237         adev->vm_manager.active[vm_id] = amdgpu_fence_ref(fence);
238
239         amdgpu_fence_unref(&vm->ids[ridx].last_id_use);
240         vm->ids[ridx].last_id_use = amdgpu_fence_ref(fence);
241 }
242
243 /**
244  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
245  *
246  * @vm: requested vm
247  * @bo: requested buffer object
248  *
249  * Find @bo inside the requested vm (cayman+).
250  * Search inside the @bos vm list for the requested vm
251  * Returns the found bo_va or NULL if none is found
252  *
253  * Object has to be reserved!
254  */
255 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
256                                        struct amdgpu_bo *bo)
257 {
258         struct amdgpu_bo_va *bo_va;
259
260         list_for_each_entry(bo_va, &bo->va, bo_list) {
261                 if (bo_va->vm == vm) {
262                         return bo_va;
263                 }
264         }
265         return NULL;
266 }
267
268 /**
269  * amdgpu_vm_update_pages - helper to call the right asic function
270  *
271  * @adev: amdgpu_device pointer
272  * @ib: indirect buffer to fill with commands
273  * @pe: addr of the page entry
274  * @addr: dst addr to write into pe
275  * @count: number of page entries to update
276  * @incr: increase next addr by incr bytes
277  * @flags: hw access flags
278  * @gtt_flags: GTT hw access flags
279  *
280  * Traces the parameters and calls the right asic functions
281  * to setup the page table using the DMA.
282  */
283 static void amdgpu_vm_update_pages(struct amdgpu_device *adev,
284                                    struct amdgpu_ib *ib,
285                                    uint64_t pe, uint64_t addr,
286                                    unsigned count, uint32_t incr,
287                                    uint32_t flags, uint32_t gtt_flags)
288 {
289         trace_amdgpu_vm_set_page(pe, addr, count, incr, flags);
290
291         if ((flags & AMDGPU_PTE_SYSTEM) && (flags == gtt_flags)) {
292                 uint64_t src = adev->gart.table_addr + (addr >> 12) * 8;
293                 amdgpu_vm_copy_pte(adev, ib, pe, src, count);
294
295         } else if ((flags & AMDGPU_PTE_SYSTEM) || (count < 3)) {
296                 amdgpu_vm_write_pte(adev, ib, pe, addr,
297                                       count, incr, flags);
298
299         } else {
300                 amdgpu_vm_set_pte_pde(adev, ib, pe, addr,
301                                       count, incr, flags);
302         }
303 }
304
305 /**
306  * amdgpu_vm_clear_bo - initially clear the page dir/table
307  *
308  * @adev: amdgpu_device pointer
309  * @bo: bo to clear
310  */
311 static int amdgpu_vm_clear_bo(struct amdgpu_device *adev,
312                               struct amdgpu_bo *bo)
313 {
314         struct amdgpu_ring *ring = adev->vm_manager.vm_pte_funcs_ring;
315         struct amdgpu_ib ib;
316         unsigned entries;
317         uint64_t addr;
318         int r;
319
320         r = amdgpu_bo_reserve(bo, false);
321         if (r)
322                 return r;
323
324         r = reservation_object_reserve_shared(bo->tbo.resv);
325         if (r)
326                 return r;
327
328         r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
329         if (r)
330                 goto error_unreserve;
331
332         addr = amdgpu_bo_gpu_offset(bo);
333         entries = amdgpu_bo_size(bo) / 8;
334
335         r = amdgpu_ib_get(ring, NULL, entries * 2 + 64, &ib);
336         if (r)
337                 goto error_unreserve;
338
339         ib.length_dw = 0;
340
341         amdgpu_vm_update_pages(adev, &ib, addr, 0, entries, 0, 0, 0);
342         amdgpu_vm_pad_ib(adev, &ib);
343         WARN_ON(ib.length_dw > 64);
344
345         r = amdgpu_ib_schedule(adev, 1, &ib, AMDGPU_FENCE_OWNER_VM);
346         if (r)
347                 goto error_free;
348
349         amdgpu_bo_fence(bo, ib.fence, true);
350
351 error_free:
352         amdgpu_ib_free(adev, &ib);
353
354 error_unreserve:
355         amdgpu_bo_unreserve(bo);
356         return r;
357 }
358
359 /**
360  * amdgpu_vm_map_gart - get the physical address of a gart page
361  *
362  * @adev: amdgpu_device pointer
363  * @addr: the unmapped addr
364  *
365  * Look up the physical address of the page that the pte resolves
366  * to (cayman+).
367  * Returns the physical address of the page.
368  */
369 uint64_t amdgpu_vm_map_gart(struct amdgpu_device *adev, uint64_t addr)
370 {
371         uint64_t result;
372
373         /* page table offset */
374         result = adev->gart.pages_addr[addr >> PAGE_SHIFT];
375
376         /* in case cpu page size != gpu page size*/
377         result |= addr & (~PAGE_MASK);
378
379         return result;
380 }
381
382 /**
383  * amdgpu_vm_update_pdes - make sure that page directory is valid
384  *
385  * @adev: amdgpu_device pointer
386  * @vm: requested vm
387  * @start: start of GPU address range
388  * @end: end of GPU address range
389  *
390  * Allocates new page tables if necessary
391  * and updates the page directory (cayman+).
392  * Returns 0 for success, error for failure.
393  *
394  * Global and local mutex must be locked!
395  */
396 int amdgpu_vm_update_page_directory(struct amdgpu_device *adev,
397                                     struct amdgpu_vm *vm)
398 {
399         struct amdgpu_ring *ring = adev->vm_manager.vm_pte_funcs_ring;
400         struct amdgpu_bo *pd = vm->page_directory;
401         uint64_t pd_addr = amdgpu_bo_gpu_offset(pd);
402         uint32_t incr = AMDGPU_VM_PTE_COUNT * 8;
403         uint64_t last_pde = ~0, last_pt = ~0;
404         unsigned count = 0, pt_idx, ndw;
405         struct amdgpu_ib ib;
406         int r;
407
408         /* padding, etc. */
409         ndw = 64;
410
411         /* assume the worst case */
412         ndw += vm->max_pde_used * 6;
413
414         /* update too big for an IB */
415         if (ndw > 0xfffff)
416                 return -ENOMEM;
417
418         r = amdgpu_ib_get(ring, NULL, ndw * 4, &ib);
419         if (r)
420                 return r;
421         ib.length_dw = 0;
422
423         /* walk over the address space and update the page directory */
424         for (pt_idx = 0; pt_idx <= vm->max_pde_used; ++pt_idx) {
425                 struct amdgpu_bo *bo = vm->page_tables[pt_idx].bo;
426                 uint64_t pde, pt;
427
428                 if (bo == NULL)
429                         continue;
430
431                 pt = amdgpu_bo_gpu_offset(bo);
432                 if (vm->page_tables[pt_idx].addr == pt)
433                         continue;
434                 vm->page_tables[pt_idx].addr = pt;
435
436                 pde = pd_addr + pt_idx * 8;
437                 if (((last_pde + 8 * count) != pde) ||
438                     ((last_pt + incr * count) != pt)) {
439
440                         if (count) {
441                                 amdgpu_vm_update_pages(adev, &ib, last_pde,
442                                                        last_pt, count, incr,
443                                                        AMDGPU_PTE_VALID, 0);
444                         }
445
446                         count = 1;
447                         last_pde = pde;
448                         last_pt = pt;
449                 } else {
450                         ++count;
451                 }
452         }
453
454         if (count)
455                 amdgpu_vm_update_pages(adev, &ib, last_pde, last_pt, count,
456                                        incr, AMDGPU_PTE_VALID, 0);
457
458         if (ib.length_dw != 0) {
459                 amdgpu_vm_pad_ib(adev, &ib);
460                 amdgpu_sync_resv(adev, &ib.sync, pd->tbo.resv, AMDGPU_FENCE_OWNER_VM);
461                 WARN_ON(ib.length_dw > ndw);
462                 r = amdgpu_ib_schedule(adev, 1, &ib, AMDGPU_FENCE_OWNER_VM);
463                 if (r) {
464                         amdgpu_ib_free(adev, &ib);
465                         return r;
466                 }
467                 amdgpu_bo_fence(pd, ib.fence, true);
468         }
469         amdgpu_ib_free(adev, &ib);
470
471         return 0;
472 }
473
474 /**
475  * amdgpu_vm_frag_ptes - add fragment information to PTEs
476  *
477  * @adev: amdgpu_device pointer
478  * @ib: IB for the update
479  * @pe_start: first PTE to handle
480  * @pe_end: last PTE to handle
481  * @addr: addr those PTEs should point to
482  * @flags: hw mapping flags
483  * @gtt_flags: GTT hw mapping flags
484  *
485  * Global and local mutex must be locked!
486  */
487 static void amdgpu_vm_frag_ptes(struct amdgpu_device *adev,
488                                 struct amdgpu_ib *ib,
489                                 uint64_t pe_start, uint64_t pe_end,
490                                 uint64_t addr, uint32_t flags,
491                                 uint32_t gtt_flags)
492 {
493         /**
494          * The MC L1 TLB supports variable sized pages, based on a fragment
495          * field in the PTE. When this field is set to a non-zero value, page
496          * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
497          * flags are considered valid for all PTEs within the fragment range
498          * and corresponding mappings are assumed to be physically contiguous.
499          *
500          * The L1 TLB can store a single PTE for the whole fragment,
501          * significantly increasing the space available for translation
502          * caching. This leads to large improvements in throughput when the
503          * TLB is under pressure.
504          *
505          * The L2 TLB distributes small and large fragments into two
506          * asymmetric partitions. The large fragment cache is significantly
507          * larger. Thus, we try to use large fragments wherever possible.
508          * Userspace can support this by aligning virtual base address and
509          * allocation size to the fragment size.
510          */
511
512         /* SI and newer are optimized for 64KB */
513         uint64_t frag_flags = AMDGPU_PTE_FRAG_64KB;
514         uint64_t frag_align = 0x80;
515
516         uint64_t frag_start = ALIGN(pe_start, frag_align);
517         uint64_t frag_end = pe_end & ~(frag_align - 1);
518
519         unsigned count;
520
521         /* system pages are non continuously */
522         if ((flags & AMDGPU_PTE_SYSTEM) || !(flags & AMDGPU_PTE_VALID) ||
523             (frag_start >= frag_end)) {
524
525                 count = (pe_end - pe_start) / 8;
526                 amdgpu_vm_update_pages(adev, ib, pe_start, addr, count,
527                                        AMDGPU_GPU_PAGE_SIZE, flags, gtt_flags);
528                 return;
529         }
530
531         /* handle the 4K area at the beginning */
532         if (pe_start != frag_start) {
533                 count = (frag_start - pe_start) / 8;
534                 amdgpu_vm_update_pages(adev, ib, pe_start, addr, count,
535                                        AMDGPU_GPU_PAGE_SIZE, flags, gtt_flags);
536                 addr += AMDGPU_GPU_PAGE_SIZE * count;
537         }
538
539         /* handle the area in the middle */
540         count = (frag_end - frag_start) / 8;
541         amdgpu_vm_update_pages(adev, ib, frag_start, addr, count,
542                                AMDGPU_GPU_PAGE_SIZE, flags | frag_flags,
543                                gtt_flags);
544
545         /* handle the 4K area at the end */
546         if (frag_end != pe_end) {
547                 addr += AMDGPU_GPU_PAGE_SIZE * count;
548                 count = (pe_end - frag_end) / 8;
549                 amdgpu_vm_update_pages(adev, ib, frag_end, addr, count,
550                                        AMDGPU_GPU_PAGE_SIZE, flags, gtt_flags);
551         }
552 }
553
554 /**
555  * amdgpu_vm_update_ptes - make sure that page tables are valid
556  *
557  * @adev: amdgpu_device pointer
558  * @vm: requested vm
559  * @start: start of GPU address range
560  * @end: end of GPU address range
561  * @dst: destination address to map to
562  * @flags: mapping flags
563  *
564  * Update the page tables in the range @start - @end (cayman+).
565  *
566  * Global and local mutex must be locked!
567  */
568 static int amdgpu_vm_update_ptes(struct amdgpu_device *adev,
569                                  struct amdgpu_vm *vm,
570                                  struct amdgpu_ib *ib,
571                                  uint64_t start, uint64_t end,
572                                  uint64_t dst, uint32_t flags,
573                                  uint32_t gtt_flags)
574 {
575         uint64_t mask = AMDGPU_VM_PTE_COUNT - 1;
576         uint64_t last_pte = ~0, last_dst = ~0;
577         unsigned count = 0;
578         uint64_t addr;
579
580         /* walk over the address space and update the page tables */
581         for (addr = start; addr < end; ) {
582                 uint64_t pt_idx = addr >> amdgpu_vm_block_size;
583                 struct amdgpu_bo *pt = vm->page_tables[pt_idx].bo;
584                 unsigned nptes;
585                 uint64_t pte;
586                 int r;
587
588                 amdgpu_sync_resv(adev, &ib->sync, pt->tbo.resv,
589                                  AMDGPU_FENCE_OWNER_VM);
590                 r = reservation_object_reserve_shared(pt->tbo.resv);
591                 if (r)
592                         return r;
593
594                 if ((addr & ~mask) == (end & ~mask))
595                         nptes = end - addr;
596                 else
597                         nptes = AMDGPU_VM_PTE_COUNT - (addr & mask);
598
599                 pte = amdgpu_bo_gpu_offset(pt);
600                 pte += (addr & mask) * 8;
601
602                 if ((last_pte + 8 * count) != pte) {
603
604                         if (count) {
605                                 amdgpu_vm_frag_ptes(adev, ib, last_pte,
606                                                     last_pte + 8 * count,
607                                                     last_dst, flags,
608                                                     gtt_flags);
609                         }
610
611                         count = nptes;
612                         last_pte = pte;
613                         last_dst = dst;
614                 } else {
615                         count += nptes;
616                 }
617
618                 addr += nptes;
619                 dst += nptes * AMDGPU_GPU_PAGE_SIZE;
620         }
621
622         if (count) {
623                 amdgpu_vm_frag_ptes(adev, ib, last_pte,
624                                     last_pte + 8 * count,
625                                     last_dst, flags, gtt_flags);
626         }
627
628         return 0;
629 }
630
631 /**
632  * amdgpu_vm_fence_pts - fence page tables after an update
633  *
634  * @vm: requested vm
635  * @start: start of GPU address range
636  * @end: end of GPU address range
637  * @fence: fence to use
638  *
639  * Fence the page tables in the range @start - @end (cayman+).
640  *
641  * Global and local mutex must be locked!
642  */
643 static void amdgpu_vm_fence_pts(struct amdgpu_vm *vm,
644                                 uint64_t start, uint64_t end,
645                                 struct amdgpu_fence *fence)
646 {
647         unsigned i;
648
649         start >>= amdgpu_vm_block_size;
650         end >>= amdgpu_vm_block_size;
651
652         for (i = start; i <= end; ++i)
653                 amdgpu_bo_fence(vm->page_tables[i].bo, fence, true);
654 }
655
656 /**
657  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
658  *
659  * @adev: amdgpu_device pointer
660  * @vm: requested vm
661  * @mapping: mapped range and flags to use for the update
662  * @addr: addr to set the area to
663  * @gtt_flags: flags as they are used for GTT
664  * @fence: optional resulting fence
665  *
666  * Fill in the page table entries for @mapping.
667  * Returns 0 for success, -EINVAL for failure.
668  *
669  * Object have to be reserved and mutex must be locked!
670  */
671 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
672                                        struct amdgpu_vm *vm,
673                                        struct amdgpu_bo_va_mapping *mapping,
674                                        uint64_t addr, uint32_t gtt_flags,
675                                        struct amdgpu_fence **fence)
676 {
677         struct amdgpu_ring *ring = adev->vm_manager.vm_pte_funcs_ring;
678         unsigned nptes, ncmds, ndw;
679         uint32_t flags = gtt_flags;
680         struct amdgpu_ib ib;
681         int r;
682
683         /* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
684          * but in case of something, we filter the flags in first place
685          */
686         if (!(mapping->flags & AMDGPU_PTE_READABLE))
687                 flags &= ~AMDGPU_PTE_READABLE;
688         if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
689                 flags &= ~AMDGPU_PTE_WRITEABLE;
690
691         trace_amdgpu_vm_bo_update(mapping);
692
693         nptes = mapping->it.last - mapping->it.start + 1;
694
695         /*
696          * reserve space for one command every (1 << BLOCK_SIZE)
697          *  entries or 2k dwords (whatever is smaller)
698          */
699         ncmds = (nptes >> min(amdgpu_vm_block_size, 11)) + 1;
700
701         /* padding, etc. */
702         ndw = 64;
703
704         if ((flags & AMDGPU_PTE_SYSTEM) && (flags == gtt_flags)) {
705                 /* only copy commands needed */
706                 ndw += ncmds * 7;
707
708         } else if (flags & AMDGPU_PTE_SYSTEM) {
709                 /* header for write data commands */
710                 ndw += ncmds * 4;
711
712                 /* body of write data command */
713                 ndw += nptes * 2;
714
715         } else {
716                 /* set page commands needed */
717                 ndw += ncmds * 10;
718
719                 /* two extra commands for begin/end of fragment */
720                 ndw += 2 * 10;
721         }
722
723         /* update too big for an IB */
724         if (ndw > 0xfffff)
725                 return -ENOMEM;
726
727         r = amdgpu_ib_get(ring, NULL, ndw * 4, &ib);
728         if (r)
729                 return r;
730         ib.length_dw = 0;
731
732         if (!(flags & AMDGPU_PTE_VALID)) {
733                 unsigned i;
734
735                 for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
736                         struct amdgpu_fence *f = vm->ids[i].last_id_use;
737                         r = amdgpu_sync_fence(adev, &ib.sync, &f->base);
738                         if (r)
739                                 return r;
740                 }
741         }
742
743         r = amdgpu_vm_update_ptes(adev, vm, &ib, mapping->it.start,
744                                   mapping->it.last + 1, addr + mapping->offset,
745                                   flags, gtt_flags);
746
747         if (r) {
748                 amdgpu_ib_free(adev, &ib);
749                 return r;
750         }
751
752         amdgpu_vm_pad_ib(adev, &ib);
753         WARN_ON(ib.length_dw > ndw);
754
755         r = amdgpu_ib_schedule(adev, 1, &ib, AMDGPU_FENCE_OWNER_VM);
756         if (r) {
757                 amdgpu_ib_free(adev, &ib);
758                 return r;
759         }
760         amdgpu_vm_fence_pts(vm, mapping->it.start,
761                             mapping->it.last + 1, ib.fence);
762         if (fence) {
763                 amdgpu_fence_unref(fence);
764                 *fence = amdgpu_fence_ref(ib.fence);
765         }
766         amdgpu_ib_free(adev, &ib);
767
768         return 0;
769 }
770
771 /**
772  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
773  *
774  * @adev: amdgpu_device pointer
775  * @bo_va: requested BO and VM object
776  * @mem: ttm mem
777  *
778  * Fill in the page table entries for @bo_va.
779  * Returns 0 for success, -EINVAL for failure.
780  *
781  * Object have to be reserved and mutex must be locked!
782  */
783 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
784                         struct amdgpu_bo_va *bo_va,
785                         struct ttm_mem_reg *mem)
786 {
787         struct amdgpu_vm *vm = bo_va->vm;
788         struct amdgpu_bo_va_mapping *mapping;
789         uint32_t flags;
790         uint64_t addr;
791         int r;
792
793         if (mem) {
794                 addr = mem->start << PAGE_SHIFT;
795                 if (mem->mem_type != TTM_PL_TT)
796                         addr += adev->vm_manager.vram_base_offset;
797         } else {
798                 addr = 0;
799         }
800
801         if (addr == bo_va->addr)
802                 return 0;
803
804         flags = amdgpu_ttm_tt_pte_flags(adev, bo_va->bo->tbo.ttm, mem);
805
806         list_for_each_entry(mapping, &bo_va->mappings, list) {
807                 r = amdgpu_vm_bo_update_mapping(adev, vm, mapping, addr,
808                                                 flags, &bo_va->last_pt_update);
809                 if (r)
810                         return r;
811         }
812
813         bo_va->addr = addr;
814         spin_lock(&vm->status_lock);
815         list_del_init(&bo_va->vm_status);
816         spin_unlock(&vm->status_lock);
817
818         return 0;
819 }
820
821 /**
822  * amdgpu_vm_clear_freed - clear freed BOs in the PT
823  *
824  * @adev: amdgpu_device pointer
825  * @vm: requested vm
826  *
827  * Make sure all freed BOs are cleared in the PT.
828  * Returns 0 for success.
829  *
830  * PTs have to be reserved and mutex must be locked!
831  */
832 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
833                           struct amdgpu_vm *vm)
834 {
835         struct amdgpu_bo_va_mapping *mapping;
836         int r;
837
838         while (!list_empty(&vm->freed)) {
839                 mapping = list_first_entry(&vm->freed,
840                         struct amdgpu_bo_va_mapping, list);
841                 list_del(&mapping->list);
842
843                 r = amdgpu_vm_bo_update_mapping(adev, vm, mapping, 0, 0, NULL);
844                 kfree(mapping);
845                 if (r)
846                         return r;
847
848         }
849         return 0;
850
851 }
852
853 /**
854  * amdgpu_vm_clear_invalids - clear invalidated BOs in the PT
855  *
856  * @adev: amdgpu_device pointer
857  * @vm: requested vm
858  *
859  * Make sure all invalidated BOs are cleared in the PT.
860  * Returns 0 for success.
861  *
862  * PTs have to be reserved and mutex must be locked!
863  */
864 int amdgpu_vm_clear_invalids(struct amdgpu_device *adev,
865                              struct amdgpu_vm *vm, struct amdgpu_sync *sync)
866 {
867         struct amdgpu_bo_va *bo_va = NULL;
868         int r = 0;
869
870         spin_lock(&vm->status_lock);
871         while (!list_empty(&vm->invalidated)) {
872                 bo_va = list_first_entry(&vm->invalidated,
873                         struct amdgpu_bo_va, vm_status);
874                 spin_unlock(&vm->status_lock);
875
876                 r = amdgpu_vm_bo_update(adev, bo_va, NULL);
877                 if (r)
878                         return r;
879
880                 spin_lock(&vm->status_lock);
881         }
882         spin_unlock(&vm->status_lock);
883
884         if (bo_va)
885                 r = amdgpu_sync_fence(adev, sync, &bo_va->last_pt_update->base);
886
887         return r;
888 }
889
890 /**
891  * amdgpu_vm_bo_add - add a bo to a specific vm
892  *
893  * @adev: amdgpu_device pointer
894  * @vm: requested vm
895  * @bo: amdgpu buffer object
896  *
897  * Add @bo into the requested vm (cayman+).
898  * Add @bo to the list of bos associated with the vm
899  * Returns newly added bo_va or NULL for failure
900  *
901  * Object has to be reserved!
902  */
903 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
904                                       struct amdgpu_vm *vm,
905                                       struct amdgpu_bo *bo)
906 {
907         struct amdgpu_bo_va *bo_va;
908
909         bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
910         if (bo_va == NULL) {
911                 return NULL;
912         }
913         bo_va->vm = vm;
914         bo_va->bo = bo;
915         bo_va->addr = 0;
916         bo_va->ref_count = 1;
917         INIT_LIST_HEAD(&bo_va->bo_list);
918         INIT_LIST_HEAD(&bo_va->mappings);
919         INIT_LIST_HEAD(&bo_va->vm_status);
920
921         mutex_lock(&vm->mutex);
922         list_add_tail(&bo_va->bo_list, &bo->va);
923         mutex_unlock(&vm->mutex);
924
925         return bo_va;
926 }
927
928 /**
929  * amdgpu_vm_bo_map - map bo inside a vm
930  *
931  * @adev: amdgpu_device pointer
932  * @bo_va: bo_va to store the address
933  * @saddr: where to map the BO
934  * @offset: requested offset in the BO
935  * @flags: attributes of pages (read/write/valid/etc.)
936  *
937  * Add a mapping of the BO at the specefied addr into the VM.
938  * Returns 0 for success, error for failure.
939  *
940  * Object has to be reserved and gets unreserved by this function!
941  */
942 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
943                      struct amdgpu_bo_va *bo_va,
944                      uint64_t saddr, uint64_t offset,
945                      uint64_t size, uint32_t flags)
946 {
947         struct amdgpu_bo_va_mapping *mapping;
948         struct amdgpu_vm *vm = bo_va->vm;
949         struct interval_tree_node *it;
950         unsigned last_pfn, pt_idx;
951         uint64_t eaddr;
952         int r;
953
954         /* validate the parameters */
955         if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
956             size == 0 || size & AMDGPU_GPU_PAGE_MASK) {
957                 amdgpu_bo_unreserve(bo_va->bo);
958                 return -EINVAL;
959         }
960
961         /* make sure object fit at this offset */
962         eaddr = saddr + size;
963         if ((saddr >= eaddr) || (offset + size > amdgpu_bo_size(bo_va->bo))) {
964                 amdgpu_bo_unreserve(bo_va->bo);
965                 return -EINVAL;
966         }
967
968         last_pfn = eaddr / AMDGPU_GPU_PAGE_SIZE;
969         if (last_pfn > adev->vm_manager.max_pfn) {
970                 dev_err(adev->dev, "va above limit (0x%08X > 0x%08X)\n",
971                         last_pfn, adev->vm_manager.max_pfn);
972                 amdgpu_bo_unreserve(bo_va->bo);
973                 return -EINVAL;
974         }
975
976         mutex_lock(&vm->mutex);
977
978         saddr /= AMDGPU_GPU_PAGE_SIZE;
979         eaddr /= AMDGPU_GPU_PAGE_SIZE;
980
981         it = interval_tree_iter_first(&vm->va, saddr, eaddr - 1);
982         if (it) {
983                 struct amdgpu_bo_va_mapping *tmp;
984                 tmp = container_of(it, struct amdgpu_bo_va_mapping, it);
985                 /* bo and tmp overlap, invalid addr */
986                 dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
987                         "0x%010lx-0x%010lx\n", bo_va->bo, saddr, eaddr,
988                         tmp->it.start, tmp->it.last + 1);
989                 amdgpu_bo_unreserve(bo_va->bo);
990                 r = -EINVAL;
991                 goto error_unlock;
992         }
993
994         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
995         if (!mapping) {
996                 amdgpu_bo_unreserve(bo_va->bo);
997                 r = -ENOMEM;
998                 goto error_unlock;
999         }
1000
1001         INIT_LIST_HEAD(&mapping->list);
1002         mapping->it.start = saddr;
1003         mapping->it.last = eaddr - 1;
1004         mapping->offset = offset;
1005         mapping->flags = flags;
1006
1007         list_add(&mapping->list, &bo_va->mappings);
1008         interval_tree_insert(&mapping->it, &vm->va);
1009         trace_amdgpu_vm_bo_map(bo_va, mapping);
1010
1011         bo_va->addr = 0;
1012
1013         /* Make sure the page tables are allocated */
1014         saddr >>= amdgpu_vm_block_size;
1015         eaddr >>= amdgpu_vm_block_size;
1016
1017         BUG_ON(eaddr >= amdgpu_vm_num_pdes(adev));
1018
1019         if (eaddr > vm->max_pde_used)
1020                 vm->max_pde_used = eaddr;
1021
1022         amdgpu_bo_unreserve(bo_va->bo);
1023
1024         /* walk over the address space and allocate the page tables */
1025         for (pt_idx = saddr; pt_idx <= eaddr; ++pt_idx) {
1026                 struct amdgpu_bo *pt;
1027
1028                 if (vm->page_tables[pt_idx].bo)
1029                         continue;
1030
1031                 /* drop mutex to allocate and clear page table */
1032                 mutex_unlock(&vm->mutex);
1033
1034                 r = amdgpu_bo_create(adev, AMDGPU_VM_PTE_COUNT * 8,
1035                                      AMDGPU_GPU_PAGE_SIZE, true,
1036                                      AMDGPU_GEM_DOMAIN_VRAM, 0, NULL, &pt);
1037                 if (r)
1038                         goto error_free;
1039
1040                 r = amdgpu_vm_clear_bo(adev, pt);
1041                 if (r) {
1042                         amdgpu_bo_unref(&pt);
1043                         goto error_free;
1044                 }
1045
1046                 /* aquire mutex again */
1047                 mutex_lock(&vm->mutex);
1048                 if (vm->page_tables[pt_idx].bo) {
1049                         /* someone else allocated the pt in the meantime */
1050                         mutex_unlock(&vm->mutex);
1051                         amdgpu_bo_unref(&pt);
1052                         mutex_lock(&vm->mutex);
1053                         continue;
1054                 }
1055
1056                 vm->page_tables[pt_idx].addr = 0;
1057                 vm->page_tables[pt_idx].bo = pt;
1058         }
1059
1060         mutex_unlock(&vm->mutex);
1061         return 0;
1062
1063 error_free:
1064         mutex_lock(&vm->mutex);
1065         list_del(&mapping->list);
1066         interval_tree_remove(&mapping->it, &vm->va);
1067         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1068         kfree(mapping);
1069
1070 error_unlock:
1071         mutex_unlock(&vm->mutex);
1072         return r;
1073 }
1074
1075 /**
1076  * amdgpu_vm_bo_unmap - remove bo mapping from vm
1077  *
1078  * @adev: amdgpu_device pointer
1079  * @bo_va: bo_va to remove the address from
1080  * @saddr: where to the BO is mapped
1081  *
1082  * Remove a mapping of the BO at the specefied addr from the VM.
1083  * Returns 0 for success, error for failure.
1084  *
1085  * Object has to be reserved and gets unreserved by this function!
1086  */
1087 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
1088                        struct amdgpu_bo_va *bo_va,
1089                        uint64_t saddr)
1090 {
1091         struct amdgpu_bo_va_mapping *mapping;
1092         struct amdgpu_vm *vm = bo_va->vm;
1093
1094         saddr /= AMDGPU_GPU_PAGE_SIZE;
1095
1096         list_for_each_entry(mapping, &bo_va->mappings, list) {
1097                 if (mapping->it.start == saddr)
1098                         break;
1099         }
1100
1101         if (&mapping->list == &bo_va->mappings) {
1102                 amdgpu_bo_unreserve(bo_va->bo);
1103                 return -ENOENT;
1104         }
1105
1106         mutex_lock(&vm->mutex);
1107         list_del(&mapping->list);
1108         interval_tree_remove(&mapping->it, &vm->va);
1109         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1110
1111         if (bo_va->addr) {
1112                 /* clear the old address */
1113                 list_add(&mapping->list, &vm->freed);
1114         } else {
1115                 kfree(mapping);
1116         }
1117         mutex_unlock(&vm->mutex);
1118         amdgpu_bo_unreserve(bo_va->bo);
1119
1120         return 0;
1121 }
1122
1123 /**
1124  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
1125  *
1126  * @adev: amdgpu_device pointer
1127  * @bo_va: requested bo_va
1128  *
1129  * Remove @bo_va->bo from the requested vm (cayman+).
1130  *
1131  * Object have to be reserved!
1132  */
1133 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
1134                       struct amdgpu_bo_va *bo_va)
1135 {
1136         struct amdgpu_bo_va_mapping *mapping, *next;
1137         struct amdgpu_vm *vm = bo_va->vm;
1138
1139         list_del(&bo_va->bo_list);
1140
1141         mutex_lock(&vm->mutex);
1142
1143         spin_lock(&vm->status_lock);
1144         list_del(&bo_va->vm_status);
1145         spin_unlock(&vm->status_lock);
1146
1147         list_for_each_entry_safe(mapping, next, &bo_va->mappings, list) {
1148                 list_del(&mapping->list);
1149                 interval_tree_remove(&mapping->it, &vm->va);
1150                 trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1151                 if (bo_va->addr)
1152                         list_add(&mapping->list, &vm->freed);
1153                 else
1154                         kfree(mapping);
1155         }
1156         amdgpu_fence_unref(&bo_va->last_pt_update);
1157         kfree(bo_va);
1158
1159         mutex_unlock(&vm->mutex);
1160 }
1161
1162 /**
1163  * amdgpu_vm_bo_invalidate - mark the bo as invalid
1164  *
1165  * @adev: amdgpu_device pointer
1166  * @vm: requested vm
1167  * @bo: amdgpu buffer object
1168  *
1169  * Mark @bo as invalid (cayman+).
1170  */
1171 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
1172                              struct amdgpu_bo *bo)
1173 {
1174         struct amdgpu_bo_va *bo_va;
1175
1176         list_for_each_entry(bo_va, &bo->va, bo_list) {
1177                 if (bo_va->addr) {
1178                         spin_lock(&bo_va->vm->status_lock);
1179                         list_del(&bo_va->vm_status);
1180                         list_add(&bo_va->vm_status, &bo_va->vm->invalidated);
1181                         spin_unlock(&bo_va->vm->status_lock);
1182                 }
1183         }
1184 }
1185
1186 /**
1187  * amdgpu_vm_init - initialize a vm instance
1188  *
1189  * @adev: amdgpu_device pointer
1190  * @vm: requested vm
1191  *
1192  * Init @vm fields (cayman+).
1193  */
1194 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1195 {
1196         const unsigned align = min(AMDGPU_VM_PTB_ALIGN_SIZE,
1197                 AMDGPU_VM_PTE_COUNT * 8);
1198         unsigned pd_size, pd_entries, pts_size;
1199         int i, r;
1200
1201         for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
1202                 vm->ids[i].id = 0;
1203                 vm->ids[i].flushed_updates = NULL;
1204                 vm->ids[i].last_id_use = NULL;
1205         }
1206         mutex_init(&vm->mutex);
1207         vm->va = RB_ROOT;
1208         spin_lock_init(&vm->status_lock);
1209         INIT_LIST_HEAD(&vm->invalidated);
1210         INIT_LIST_HEAD(&vm->freed);
1211
1212         pd_size = amdgpu_vm_directory_size(adev);
1213         pd_entries = amdgpu_vm_num_pdes(adev);
1214
1215         /* allocate page table array */
1216         pts_size = pd_entries * sizeof(struct amdgpu_vm_pt);
1217         vm->page_tables = kzalloc(pts_size, GFP_KERNEL);
1218         if (vm->page_tables == NULL) {
1219                 DRM_ERROR("Cannot allocate memory for page table array\n");
1220                 return -ENOMEM;
1221         }
1222
1223         r = amdgpu_bo_create(adev, pd_size, align, true,
1224                              AMDGPU_GEM_DOMAIN_VRAM, 0,
1225                              NULL, &vm->page_directory);
1226         if (r)
1227                 return r;
1228
1229         r = amdgpu_vm_clear_bo(adev, vm->page_directory);
1230         if (r) {
1231                 amdgpu_bo_unref(&vm->page_directory);
1232                 vm->page_directory = NULL;
1233                 return r;
1234         }
1235
1236         return 0;
1237 }
1238
1239 /**
1240  * amdgpu_vm_fini - tear down a vm instance
1241  *
1242  * @adev: amdgpu_device pointer
1243  * @vm: requested vm
1244  *
1245  * Tear down @vm (cayman+).
1246  * Unbind the VM and remove all bos from the vm bo list
1247  */
1248 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1249 {
1250         struct amdgpu_bo_va_mapping *mapping, *tmp;
1251         int i;
1252
1253         if (!RB_EMPTY_ROOT(&vm->va)) {
1254                 dev_err(adev->dev, "still active bo inside vm\n");
1255         }
1256         rbtree_postorder_for_each_entry_safe(mapping, tmp, &vm->va, it.rb) {
1257                 list_del(&mapping->list);
1258                 interval_tree_remove(&mapping->it, &vm->va);
1259                 kfree(mapping);
1260         }
1261         list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
1262                 list_del(&mapping->list);
1263                 kfree(mapping);
1264         }
1265
1266         for (i = 0; i < amdgpu_vm_num_pdes(adev); i++)
1267                 amdgpu_bo_unref(&vm->page_tables[i].bo);
1268         kfree(vm->page_tables);
1269
1270         amdgpu_bo_unref(&vm->page_directory);
1271
1272         for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
1273                 amdgpu_fence_unref(&vm->ids[i].flushed_updates);
1274                 amdgpu_fence_unref(&vm->ids[i].last_id_use);
1275         }
1276
1277         mutex_destroy(&vm->mutex);
1278 }