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