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