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