Merge tag 'amd-drm-next-5.19-2022-04-15' of https://gitlab.freedesktop.org/agd5f...
[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
29 #include <linux/dma-fence-array.h>
30 #include <linux/interval_tree_generic.h>
31 #include <linux/idr.h>
32 #include <linux/dma-buf.h>
33
34 #include <drm/amdgpu_drm.h>
35 #include <drm/drm_drv.h>
36 #include "amdgpu.h"
37 #include "amdgpu_trace.h"
38 #include "amdgpu_amdkfd.h"
39 #include "amdgpu_gmc.h"
40 #include "amdgpu_xgmi.h"
41 #include "amdgpu_dma_buf.h"
42 #include "amdgpu_res_cursor.h"
43 #include "kfd_svm.h"
44
45 /**
46  * DOC: GPUVM
47  *
48  * GPUVM is similar to the legacy gart on older asics, however
49  * rather than there being a single global gart table
50  * for the entire GPU, there are multiple VM page tables active
51  * at any given time.  The VM page tables can contain a mix
52  * vram pages and system memory pages and system memory pages
53  * can be mapped as snooped (cached system pages) or unsnooped
54  * (uncached system pages).
55  * Each VM has an ID associated with it and there is a page table
56  * associated with each VMID.  When executing a command buffer,
57  * the kernel tells the the ring what VMID to use for that command
58  * buffer.  VMIDs are allocated dynamically as commands are submitted.
59  * The userspace drivers maintain their own address space and the kernel
60  * sets up their pages tables accordingly when they submit their
61  * command buffers and a VMID is assigned.
62  * Cayman/Trinity support up to 8 active VMs at any given time;
63  * SI supports 16.
64  */
65
66 #define START(node) ((node)->start)
67 #define LAST(node) ((node)->last)
68
69 INTERVAL_TREE_DEFINE(struct amdgpu_bo_va_mapping, rb, uint64_t, __subtree_last,
70                      START, LAST, static, amdgpu_vm_it)
71
72 #undef START
73 #undef LAST
74
75 /**
76  * struct amdgpu_prt_cb - Helper to disable partial resident texture feature from a fence callback
77  */
78 struct amdgpu_prt_cb {
79
80         /**
81          * @adev: amdgpu device
82          */
83         struct amdgpu_device *adev;
84
85         /**
86          * @cb: callback
87          */
88         struct dma_fence_cb cb;
89 };
90
91 /**
92  * struct amdgpu_vm_tlb_seq_cb - Helper to increment the TLB flush sequence
93  */
94 struct amdgpu_vm_tlb_seq_cb {
95         /**
96          * @vm: pointer to the amdgpu_vm structure to set the fence sequence on
97          */
98         struct amdgpu_vm *vm;
99
100         /**
101          * @cb: callback
102          */
103         struct dma_fence_cb cb;
104 };
105
106 /**
107  * amdgpu_vm_set_pasid - manage pasid and vm ptr mapping
108  *
109  * @adev: amdgpu_device pointer
110  * @vm: amdgpu_vm pointer
111  * @pasid: the pasid the VM is using on this GPU
112  *
113  * Set the pasid this VM is using on this GPU, can also be used to remove the
114  * pasid by passing in zero.
115  *
116  */
117 int amdgpu_vm_set_pasid(struct amdgpu_device *adev, struct amdgpu_vm *vm,
118                         u32 pasid)
119 {
120         int r;
121
122         if (vm->pasid == pasid)
123                 return 0;
124
125         if (vm->pasid) {
126                 r = xa_err(xa_erase_irq(&adev->vm_manager.pasids, vm->pasid));
127                 if (r < 0)
128                         return r;
129
130                 vm->pasid = 0;
131         }
132
133         if (pasid) {
134                 r = xa_err(xa_store_irq(&adev->vm_manager.pasids, pasid, vm,
135                                         GFP_KERNEL));
136                 if (r < 0)
137                         return r;
138
139                 vm->pasid = pasid;
140         }
141
142
143         return 0;
144 }
145
146 /*
147  * vm eviction_lock can be taken in MMU notifiers. Make sure no reclaim-FS
148  * happens while holding this lock anywhere to prevent deadlocks when
149  * an MMU notifier runs in reclaim-FS context.
150  */
151 static inline void amdgpu_vm_eviction_lock(struct amdgpu_vm *vm)
152 {
153         mutex_lock(&vm->eviction_lock);
154         vm->saved_flags = memalloc_noreclaim_save();
155 }
156
157 static inline int amdgpu_vm_eviction_trylock(struct amdgpu_vm *vm)
158 {
159         if (mutex_trylock(&vm->eviction_lock)) {
160                 vm->saved_flags = memalloc_noreclaim_save();
161                 return 1;
162         }
163         return 0;
164 }
165
166 static inline void amdgpu_vm_eviction_unlock(struct amdgpu_vm *vm)
167 {
168         memalloc_noreclaim_restore(vm->saved_flags);
169         mutex_unlock(&vm->eviction_lock);
170 }
171
172 /**
173  * amdgpu_vm_bo_evicted - vm_bo is evicted
174  *
175  * @vm_bo: vm_bo which is evicted
176  *
177  * State for PDs/PTs and per VM BOs which are not at the location they should
178  * be.
179  */
180 static void amdgpu_vm_bo_evicted(struct amdgpu_vm_bo_base *vm_bo)
181 {
182         struct amdgpu_vm *vm = vm_bo->vm;
183         struct amdgpu_bo *bo = vm_bo->bo;
184
185         vm_bo->moved = true;
186         if (bo->tbo.type == ttm_bo_type_kernel)
187                 list_move(&vm_bo->vm_status, &vm->evicted);
188         else
189                 list_move_tail(&vm_bo->vm_status, &vm->evicted);
190 }
191 /**
192  * amdgpu_vm_bo_moved - vm_bo is moved
193  *
194  * @vm_bo: vm_bo which is moved
195  *
196  * State for per VM BOs which are moved, but that change is not yet reflected
197  * in the page tables.
198  */
199 static void amdgpu_vm_bo_moved(struct amdgpu_vm_bo_base *vm_bo)
200 {
201         list_move(&vm_bo->vm_status, &vm_bo->vm->moved);
202 }
203
204 /**
205  * amdgpu_vm_bo_idle - vm_bo is idle
206  *
207  * @vm_bo: vm_bo which is now idle
208  *
209  * State for PDs/PTs and per VM BOs which have gone through the state machine
210  * and are now idle.
211  */
212 static void amdgpu_vm_bo_idle(struct amdgpu_vm_bo_base *vm_bo)
213 {
214         list_move(&vm_bo->vm_status, &vm_bo->vm->idle);
215         vm_bo->moved = false;
216 }
217
218 /**
219  * amdgpu_vm_bo_invalidated - vm_bo is invalidated
220  *
221  * @vm_bo: vm_bo which is now invalidated
222  *
223  * State for normal BOs which are invalidated and that change not yet reflected
224  * in the PTs.
225  */
226 static void amdgpu_vm_bo_invalidated(struct amdgpu_vm_bo_base *vm_bo)
227 {
228         spin_lock(&vm_bo->vm->invalidated_lock);
229         list_move(&vm_bo->vm_status, &vm_bo->vm->invalidated);
230         spin_unlock(&vm_bo->vm->invalidated_lock);
231 }
232
233 /**
234  * amdgpu_vm_bo_relocated - vm_bo is reloacted
235  *
236  * @vm_bo: vm_bo which is relocated
237  *
238  * State for PDs/PTs which needs to update their parent PD.
239  * For the root PD, just move to idle state.
240  */
241 static void amdgpu_vm_bo_relocated(struct amdgpu_vm_bo_base *vm_bo)
242 {
243         if (vm_bo->bo->parent)
244                 list_move(&vm_bo->vm_status, &vm_bo->vm->relocated);
245         else
246                 amdgpu_vm_bo_idle(vm_bo);
247 }
248
249 /**
250  * amdgpu_vm_bo_done - vm_bo is done
251  *
252  * @vm_bo: vm_bo which is now done
253  *
254  * State for normal BOs which are invalidated and that change has been updated
255  * in the PTs.
256  */
257 static void amdgpu_vm_bo_done(struct amdgpu_vm_bo_base *vm_bo)
258 {
259         spin_lock(&vm_bo->vm->invalidated_lock);
260         list_move(&vm_bo->vm_status, &vm_bo->vm->done);
261         spin_unlock(&vm_bo->vm->invalidated_lock);
262 }
263
264 /**
265  * amdgpu_vm_bo_base_init - Adds bo to the list of bos associated with the vm
266  *
267  * @base: base structure for tracking BO usage in a VM
268  * @vm: vm to which bo is to be added
269  * @bo: amdgpu buffer object
270  *
271  * Initialize a bo_va_base structure and add it to the appropriate lists
272  *
273  */
274 void amdgpu_vm_bo_base_init(struct amdgpu_vm_bo_base *base,
275                             struct amdgpu_vm *vm, struct amdgpu_bo *bo)
276 {
277         base->vm = vm;
278         base->bo = bo;
279         base->next = NULL;
280         INIT_LIST_HEAD(&base->vm_status);
281
282         if (!bo)
283                 return;
284         base->next = bo->vm_bo;
285         bo->vm_bo = base;
286
287         if (bo->tbo.base.resv != vm->root.bo->tbo.base.resv)
288                 return;
289
290         dma_resv_assert_held(vm->root.bo->tbo.base.resv);
291
292         ttm_bo_set_bulk_move(&bo->tbo, &vm->lru_bulk_move);
293         if (bo->tbo.type == ttm_bo_type_kernel && bo->parent)
294                 amdgpu_vm_bo_relocated(base);
295         else
296                 amdgpu_vm_bo_idle(base);
297
298         if (bo->preferred_domains &
299             amdgpu_mem_type_to_domain(bo->tbo.resource->mem_type))
300                 return;
301
302         /*
303          * we checked all the prerequisites, but it looks like this per vm bo
304          * is currently evicted. add the bo to the evicted list to make sure it
305          * is validated on next vm use to avoid fault.
306          * */
307         amdgpu_vm_bo_evicted(base);
308 }
309
310 /**
311  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
312  *
313  * @vm: vm providing the BOs
314  * @validated: head of validation list
315  * @entry: entry to add
316  *
317  * Add the page directory to the list of BOs to
318  * validate for command submission.
319  */
320 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
321                          struct list_head *validated,
322                          struct amdgpu_bo_list_entry *entry)
323 {
324         entry->priority = 0;
325         entry->tv.bo = &vm->root.bo->tbo;
326         /* Two for VM updates, one for TTM and one for the CS job */
327         entry->tv.num_shared = 4;
328         entry->user_pages = NULL;
329         list_add(&entry->tv.head, validated);
330 }
331
332 /**
333  * amdgpu_vm_move_to_lru_tail - move all BOs to the end of LRU
334  *
335  * @adev: amdgpu device pointer
336  * @vm: vm providing the BOs
337  *
338  * Move all BOs to the end of LRU and remember their positions to put them
339  * together.
340  */
341 void amdgpu_vm_move_to_lru_tail(struct amdgpu_device *adev,
342                                 struct amdgpu_vm *vm)
343 {
344         spin_lock(&adev->mman.bdev.lru_lock);
345         ttm_lru_bulk_move_tail(&vm->lru_bulk_move);
346         spin_unlock(&adev->mman.bdev.lru_lock);
347 }
348
349 /**
350  * amdgpu_vm_validate_pt_bos - validate the page table BOs
351  *
352  * @adev: amdgpu device pointer
353  * @vm: vm providing the BOs
354  * @validate: callback to do the validation
355  * @param: parameter for the validation callback
356  *
357  * Validate the page table BOs on command submission if neccessary.
358  *
359  * Returns:
360  * Validation result.
361  */
362 int amdgpu_vm_validate_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
363                               int (*validate)(void *p, struct amdgpu_bo *bo),
364                               void *param)
365 {
366         struct amdgpu_vm_bo_base *bo_base, *tmp;
367         int r;
368
369         list_for_each_entry_safe(bo_base, tmp, &vm->evicted, vm_status) {
370                 struct amdgpu_bo *bo = bo_base->bo;
371                 struct amdgpu_bo *shadow = amdgpu_bo_shadowed(bo);
372
373                 r = validate(param, bo);
374                 if (r)
375                         return r;
376                 if (shadow) {
377                         r = validate(param, shadow);
378                         if (r)
379                                 return r;
380                 }
381
382                 if (bo->tbo.type != ttm_bo_type_kernel) {
383                         amdgpu_vm_bo_moved(bo_base);
384                 } else {
385                         vm->update_funcs->map_table(to_amdgpu_bo_vm(bo));
386                         amdgpu_vm_bo_relocated(bo_base);
387                 }
388         }
389
390         amdgpu_vm_eviction_lock(vm);
391         vm->evicting = false;
392         amdgpu_vm_eviction_unlock(vm);
393
394         return 0;
395 }
396
397 /**
398  * amdgpu_vm_ready - check VM is ready for updates
399  *
400  * @vm: VM to check
401  *
402  * Check if all VM PDs/PTs are ready for updates
403  *
404  * Returns:
405  * True if VM is not evicting.
406  */
407 bool amdgpu_vm_ready(struct amdgpu_vm *vm)
408 {
409         bool ret;
410
411         amdgpu_vm_eviction_lock(vm);
412         ret = !vm->evicting;
413         amdgpu_vm_eviction_unlock(vm);
414
415         return ret && list_empty(&vm->evicted);
416 }
417
418 /**
419  * amdgpu_vm_check_compute_bug - check whether asic has compute vm bug
420  *
421  * @adev: amdgpu_device pointer
422  */
423 void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
424 {
425         const struct amdgpu_ip_block *ip_block;
426         bool has_compute_vm_bug;
427         struct amdgpu_ring *ring;
428         int i;
429
430         has_compute_vm_bug = false;
431
432         ip_block = amdgpu_device_ip_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
433         if (ip_block) {
434                 /* Compute has a VM bug for GFX version < 7.
435                    Compute has a VM bug for GFX 8 MEC firmware version < 673.*/
436                 if (ip_block->version->major <= 7)
437                         has_compute_vm_bug = true;
438                 else if (ip_block->version->major == 8)
439                         if (adev->gfx.mec_fw_version < 673)
440                                 has_compute_vm_bug = true;
441         }
442
443         for (i = 0; i < adev->num_rings; i++) {
444                 ring = adev->rings[i];
445                 if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE)
446                         /* only compute rings */
447                         ring->has_compute_vm_bug = has_compute_vm_bug;
448                 else
449                         ring->has_compute_vm_bug = false;
450         }
451 }
452
453 /**
454  * amdgpu_vm_need_pipeline_sync - Check if pipe sync is needed for job.
455  *
456  * @ring: ring on which the job will be submitted
457  * @job: job to submit
458  *
459  * Returns:
460  * True if sync is needed.
461  */
462 bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring,
463                                   struct amdgpu_job *job)
464 {
465         struct amdgpu_device *adev = ring->adev;
466         unsigned vmhub = ring->funcs->vmhub;
467         struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
468         struct amdgpu_vmid *id;
469         bool gds_switch_needed;
470         bool vm_flush_needed = job->vm_needs_flush || ring->has_compute_vm_bug;
471
472         if (job->vmid == 0)
473                 return false;
474         id = &id_mgr->ids[job->vmid];
475         gds_switch_needed = ring->funcs->emit_gds_switch && (
476                 id->gds_base != job->gds_base ||
477                 id->gds_size != job->gds_size ||
478                 id->gws_base != job->gws_base ||
479                 id->gws_size != job->gws_size ||
480                 id->oa_base != job->oa_base ||
481                 id->oa_size != job->oa_size);
482
483         if (amdgpu_vmid_had_gpu_reset(adev, id))
484                 return true;
485
486         return vm_flush_needed || gds_switch_needed;
487 }
488
489 /**
490  * amdgpu_vm_flush - hardware flush the vm
491  *
492  * @ring: ring to use for flush
493  * @job:  related job
494  * @need_pipe_sync: is pipe sync needed
495  *
496  * Emit a VM flush when it is necessary.
497  *
498  * Returns:
499  * 0 on success, errno otherwise.
500  */
501 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job,
502                     bool need_pipe_sync)
503 {
504         struct amdgpu_device *adev = ring->adev;
505         unsigned vmhub = ring->funcs->vmhub;
506         struct amdgpu_vmid_mgr *id_mgr = &adev->vm_manager.id_mgr[vmhub];
507         struct amdgpu_vmid *id = &id_mgr->ids[job->vmid];
508         bool gds_switch_needed = ring->funcs->emit_gds_switch && (
509                 id->gds_base != job->gds_base ||
510                 id->gds_size != job->gds_size ||
511                 id->gws_base != job->gws_base ||
512                 id->gws_size != job->gws_size ||
513                 id->oa_base != job->oa_base ||
514                 id->oa_size != job->oa_size);
515         bool vm_flush_needed = job->vm_needs_flush;
516         struct dma_fence *fence = NULL;
517         bool pasid_mapping_needed = false;
518         unsigned patch_offset = 0;
519         bool update_spm_vmid_needed = (job->vm && (job->vm->reserved_vmid[vmhub] != NULL));
520         int r;
521
522         if (update_spm_vmid_needed && adev->gfx.rlc.funcs->update_spm_vmid)
523                 adev->gfx.rlc.funcs->update_spm_vmid(adev, job->vmid);
524
525         if (amdgpu_vmid_had_gpu_reset(adev, id)) {
526                 gds_switch_needed = true;
527                 vm_flush_needed = true;
528                 pasid_mapping_needed = true;
529         }
530
531         mutex_lock(&id_mgr->lock);
532         if (id->pasid != job->pasid || !id->pasid_mapping ||
533             !dma_fence_is_signaled(id->pasid_mapping))
534                 pasid_mapping_needed = true;
535         mutex_unlock(&id_mgr->lock);
536
537         gds_switch_needed &= !!ring->funcs->emit_gds_switch;
538         vm_flush_needed &= !!ring->funcs->emit_vm_flush  &&
539                         job->vm_pd_addr != AMDGPU_BO_INVALID_OFFSET;
540         pasid_mapping_needed &= adev->gmc.gmc_funcs->emit_pasid_mapping &&
541                 ring->funcs->emit_wreg;
542
543         if (!vm_flush_needed && !gds_switch_needed && !need_pipe_sync)
544                 return 0;
545
546         if (ring->funcs->init_cond_exec)
547                 patch_offset = amdgpu_ring_init_cond_exec(ring);
548
549         if (need_pipe_sync)
550                 amdgpu_ring_emit_pipeline_sync(ring);
551
552         if (vm_flush_needed) {
553                 trace_amdgpu_vm_flush(ring, job->vmid, job->vm_pd_addr);
554                 amdgpu_ring_emit_vm_flush(ring, job->vmid, job->vm_pd_addr);
555         }
556
557         if (pasid_mapping_needed)
558                 amdgpu_gmc_emit_pasid_mapping(ring, job->vmid, job->pasid);
559
560         if (vm_flush_needed || pasid_mapping_needed) {
561                 r = amdgpu_fence_emit(ring, &fence, NULL, 0);
562                 if (r)
563                         return r;
564         }
565
566         if (vm_flush_needed) {
567                 mutex_lock(&id_mgr->lock);
568                 dma_fence_put(id->last_flush);
569                 id->last_flush = dma_fence_get(fence);
570                 id->current_gpu_reset_count =
571                         atomic_read(&adev->gpu_reset_counter);
572                 mutex_unlock(&id_mgr->lock);
573         }
574
575         if (pasid_mapping_needed) {
576                 mutex_lock(&id_mgr->lock);
577                 id->pasid = job->pasid;
578                 dma_fence_put(id->pasid_mapping);
579                 id->pasid_mapping = dma_fence_get(fence);
580                 mutex_unlock(&id_mgr->lock);
581         }
582         dma_fence_put(fence);
583
584         if (ring->funcs->emit_gds_switch && gds_switch_needed) {
585                 id->gds_base = job->gds_base;
586                 id->gds_size = job->gds_size;
587                 id->gws_base = job->gws_base;
588                 id->gws_size = job->gws_size;
589                 id->oa_base = job->oa_base;
590                 id->oa_size = job->oa_size;
591                 amdgpu_ring_emit_gds_switch(ring, job->vmid, job->gds_base,
592                                             job->gds_size, job->gws_base,
593                                             job->gws_size, job->oa_base,
594                                             job->oa_size);
595         }
596
597         if (ring->funcs->patch_cond_exec)
598                 amdgpu_ring_patch_cond_exec(ring, patch_offset);
599
600         /* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
601         if (ring->funcs->emit_switch_buffer) {
602                 amdgpu_ring_emit_switch_buffer(ring);
603                 amdgpu_ring_emit_switch_buffer(ring);
604         }
605         return 0;
606 }
607
608 /**
609  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
610  *
611  * @vm: requested vm
612  * @bo: requested buffer object
613  *
614  * Find @bo inside the requested vm.
615  * Search inside the @bos vm list for the requested vm
616  * Returns the found bo_va or NULL if none is found
617  *
618  * Object has to be reserved!
619  *
620  * Returns:
621  * Found bo_va or NULL.
622  */
623 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
624                                        struct amdgpu_bo *bo)
625 {
626         struct amdgpu_vm_bo_base *base;
627
628         for (base = bo->vm_bo; base; base = base->next) {
629                 if (base->vm != vm)
630                         continue;
631
632                 return container_of(base, struct amdgpu_bo_va, base);
633         }
634         return NULL;
635 }
636
637 /**
638  * amdgpu_vm_map_gart - Resolve gart mapping of addr
639  *
640  * @pages_addr: optional DMA address to use for lookup
641  * @addr: the unmapped addr
642  *
643  * Look up the physical address of the page that the pte resolves
644  * to.
645  *
646  * Returns:
647  * The pointer for the page table entry.
648  */
649 uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
650 {
651         uint64_t result;
652
653         /* page table offset */
654         result = pages_addr[addr >> PAGE_SHIFT];
655
656         /* in case cpu page size != gpu page size*/
657         result |= addr & (~PAGE_MASK);
658
659         result &= 0xFFFFFFFFFFFFF000ULL;
660
661         return result;
662 }
663
664 /**
665  * amdgpu_vm_update_pdes - make sure that all directories are valid
666  *
667  * @adev: amdgpu_device pointer
668  * @vm: requested vm
669  * @immediate: submit immediately to the paging queue
670  *
671  * Makes sure all directories are up to date.
672  *
673  * Returns:
674  * 0 for success, error for failure.
675  */
676 int amdgpu_vm_update_pdes(struct amdgpu_device *adev,
677                           struct amdgpu_vm *vm, bool immediate)
678 {
679         struct amdgpu_vm_update_params params;
680         struct amdgpu_vm_bo_base *entry;
681         int r, idx;
682
683         if (list_empty(&vm->relocated))
684                 return 0;
685
686         if (!drm_dev_enter(adev_to_drm(adev), &idx))
687                 return -ENODEV;
688
689         memset(&params, 0, sizeof(params));
690         params.adev = adev;
691         params.vm = vm;
692         params.immediate = immediate;
693
694         r = vm->update_funcs->prepare(&params, NULL, AMDGPU_SYNC_EXPLICIT);
695         if (r)
696                 goto error;
697
698         list_for_each_entry(entry, &vm->relocated, vm_status) {
699                 r = amdgpu_vm_pde_update(&params, entry);
700                 if (r)
701                         goto error;
702         }
703
704         r = vm->update_funcs->commit(&params, &vm->last_update);
705         if (r)
706                 goto error;
707
708         while (!list_empty(&vm->relocated)) {
709                 entry = list_first_entry(&vm->relocated,
710                                          struct amdgpu_vm_bo_base,
711                                          vm_status);
712                 amdgpu_vm_bo_idle(entry);
713         }
714
715 error:
716         drm_dev_exit(idx);
717         return r;
718 }
719
720 /**
721  * amdgpu_vm_tlb_seq_cb - make sure to increment tlb sequence
722  * @fence: unused
723  * @cb: the callback structure
724  *
725  * Increments the tlb sequence to make sure that future CS execute a VM flush.
726  */
727 static void amdgpu_vm_tlb_seq_cb(struct dma_fence *fence,
728                                  struct dma_fence_cb *cb)
729 {
730         struct amdgpu_vm_tlb_seq_cb *tlb_cb;
731
732         tlb_cb = container_of(cb, typeof(*tlb_cb), cb);
733         atomic64_inc(&tlb_cb->vm->tlb_seq);
734         kfree(tlb_cb);
735 }
736
737 /**
738  * amdgpu_vm_update_range - update a range in the vm page table
739  *
740  * @adev: amdgpu_device pointer to use for commands
741  * @vm: the VM to update the range
742  * @immediate: immediate submission in a page fault
743  * @unlocked: unlocked invalidation during MM callback
744  * @flush_tlb: trigger tlb invalidation after update completed
745  * @resv: fences we need to sync to
746  * @start: start of mapped range
747  * @last: last mapped entry
748  * @flags: flags for the entries
749  * @offset: offset into nodes and pages_addr
750  * @vram_base: base for vram mappings
751  * @res: ttm_resource to map
752  * @pages_addr: DMA addresses to use for mapping
753  * @fence: optional resulting fence
754  *
755  * Fill in the page table entries between @start and @last.
756  *
757  * Returns:
758  * 0 for success, negative erro code for failure.
759  */
760 int amdgpu_vm_update_range(struct amdgpu_device *adev, struct amdgpu_vm *vm,
761                            bool immediate, bool unlocked, bool flush_tlb,
762                            struct dma_resv *resv, uint64_t start, uint64_t last,
763                            uint64_t flags, uint64_t offset, uint64_t vram_base,
764                            struct ttm_resource *res, dma_addr_t *pages_addr,
765                            struct dma_fence **fence)
766 {
767         struct amdgpu_vm_update_params params;
768         struct amdgpu_vm_tlb_seq_cb *tlb_cb;
769         struct amdgpu_res_cursor cursor;
770         enum amdgpu_sync_mode sync_mode;
771         int r, idx;
772
773         if (!drm_dev_enter(adev_to_drm(adev), &idx))
774                 return -ENODEV;
775
776         tlb_cb = kmalloc(sizeof(*tlb_cb), GFP_KERNEL);
777         if (!tlb_cb) {
778                 r = -ENOMEM;
779                 goto error_unlock;
780         }
781
782         /* Vega20+XGMI where PTEs get inadvertently cached in L2 texture cache,
783          * heavy-weight flush TLB unconditionally.
784          */
785         flush_tlb |= adev->gmc.xgmi.num_physical_nodes &&
786                      adev->ip_versions[GC_HWIP][0] == IP_VERSION(9, 4, 0);
787
788         memset(&params, 0, sizeof(params));
789         params.adev = adev;
790         params.vm = vm;
791         params.immediate = immediate;
792         params.pages_addr = pages_addr;
793         params.unlocked = unlocked;
794
795         /* Implicitly sync to command submissions in the same VM before
796          * unmapping. Sync to moving fences before mapping.
797          */
798         if (!(flags & AMDGPU_PTE_VALID))
799                 sync_mode = AMDGPU_SYNC_EQ_OWNER;
800         else
801                 sync_mode = AMDGPU_SYNC_EXPLICIT;
802
803         amdgpu_vm_eviction_lock(vm);
804         if (vm->evicting) {
805                 r = -EBUSY;
806                 goto error_free;
807         }
808
809         if (!unlocked && !dma_fence_is_signaled(vm->last_unlocked)) {
810                 struct dma_fence *tmp = dma_fence_get_stub();
811
812                 amdgpu_bo_fence(vm->root.bo, vm->last_unlocked, true);
813                 swap(vm->last_unlocked, tmp);
814                 dma_fence_put(tmp);
815         }
816
817         r = vm->update_funcs->prepare(&params, resv, sync_mode);
818         if (r)
819                 goto error_free;
820
821         amdgpu_res_first(pages_addr ? NULL : res, offset,
822                          (last - start + 1) * AMDGPU_GPU_PAGE_SIZE, &cursor);
823         while (cursor.remaining) {
824                 uint64_t tmp, num_entries, addr;
825
826                 num_entries = cursor.size >> AMDGPU_GPU_PAGE_SHIFT;
827                 if (pages_addr) {
828                         bool contiguous = true;
829
830                         if (num_entries > AMDGPU_GPU_PAGES_IN_CPU_PAGE) {
831                                 uint64_t pfn = cursor.start >> PAGE_SHIFT;
832                                 uint64_t count;
833
834                                 contiguous = pages_addr[pfn + 1] ==
835                                         pages_addr[pfn] + PAGE_SIZE;
836
837                                 tmp = num_entries /
838                                         AMDGPU_GPU_PAGES_IN_CPU_PAGE;
839                                 for (count = 2; count < tmp; ++count) {
840                                         uint64_t idx = pfn + count;
841
842                                         if (contiguous != (pages_addr[idx] ==
843                                             pages_addr[idx - 1] + PAGE_SIZE))
844                                                 break;
845                                 }
846                                 num_entries = count *
847                                         AMDGPU_GPU_PAGES_IN_CPU_PAGE;
848                         }
849
850                         if (!contiguous) {
851                                 addr = cursor.start;
852                                 params.pages_addr = pages_addr;
853                         } else {
854                                 addr = pages_addr[cursor.start >> PAGE_SHIFT];
855                                 params.pages_addr = NULL;
856                         }
857
858                 } else if (flags & (AMDGPU_PTE_VALID | AMDGPU_PTE_PRT)) {
859                         addr = vram_base + cursor.start;
860                 } else {
861                         addr = 0;
862                 }
863
864                 tmp = start + num_entries;
865                 r = amdgpu_vm_ptes_update(&params, start, tmp, addr, flags);
866                 if (r)
867                         goto error_free;
868
869                 amdgpu_res_next(&cursor, num_entries * AMDGPU_GPU_PAGE_SIZE);
870                 start = tmp;
871         }
872
873         r = vm->update_funcs->commit(&params, fence);
874
875         if (flush_tlb || params.table_freed) {
876                 tlb_cb->vm = vm;
877                 if (fence && *fence &&
878                     !dma_fence_add_callback(*fence, &tlb_cb->cb,
879                                            amdgpu_vm_tlb_seq_cb)) {
880                         dma_fence_put(vm->last_tlb_flush);
881                         vm->last_tlb_flush = dma_fence_get(*fence);
882                 } else {
883                         amdgpu_vm_tlb_seq_cb(NULL, &tlb_cb->cb);
884                 }
885                 tlb_cb = NULL;
886         }
887
888 error_free:
889         kfree(tlb_cb);
890
891 error_unlock:
892         amdgpu_vm_eviction_unlock(vm);
893         drm_dev_exit(idx);
894         return r;
895 }
896
897 void amdgpu_vm_get_memory(struct amdgpu_vm *vm, uint64_t *vram_mem,
898                                 uint64_t *gtt_mem, uint64_t *cpu_mem)
899 {
900         struct amdgpu_bo_va *bo_va, *tmp;
901
902         list_for_each_entry_safe(bo_va, tmp, &vm->idle, base.vm_status) {
903                 if (!bo_va->base.bo)
904                         continue;
905                 amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
906                                 gtt_mem, cpu_mem);
907         }
908         list_for_each_entry_safe(bo_va, tmp, &vm->evicted, base.vm_status) {
909                 if (!bo_va->base.bo)
910                         continue;
911                 amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
912                                 gtt_mem, cpu_mem);
913         }
914         list_for_each_entry_safe(bo_va, tmp, &vm->relocated, base.vm_status) {
915                 if (!bo_va->base.bo)
916                         continue;
917                 amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
918                                 gtt_mem, cpu_mem);
919         }
920         list_for_each_entry_safe(bo_va, tmp, &vm->moved, base.vm_status) {
921                 if (!bo_va->base.bo)
922                         continue;
923                 amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
924                                 gtt_mem, cpu_mem);
925         }
926         spin_lock(&vm->invalidated_lock);
927         list_for_each_entry_safe(bo_va, tmp, &vm->invalidated, base.vm_status) {
928                 if (!bo_va->base.bo)
929                         continue;
930                 amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
931                                 gtt_mem, cpu_mem);
932         }
933         list_for_each_entry_safe(bo_va, tmp, &vm->done, base.vm_status) {
934                 if (!bo_va->base.bo)
935                         continue;
936                 amdgpu_bo_get_memory(bo_va->base.bo, vram_mem,
937                                 gtt_mem, cpu_mem);
938         }
939         spin_unlock(&vm->invalidated_lock);
940 }
941 /**
942  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
943  *
944  * @adev: amdgpu_device pointer
945  * @bo_va: requested BO and VM object
946  * @clear: if true clear the entries
947  *
948  * Fill in the page table entries for @bo_va.
949  *
950  * Returns:
951  * 0 for success, -EINVAL for failure.
952  */
953 int amdgpu_vm_bo_update(struct amdgpu_device *adev, struct amdgpu_bo_va *bo_va,
954                         bool clear)
955 {
956         struct amdgpu_bo *bo = bo_va->base.bo;
957         struct amdgpu_vm *vm = bo_va->base.vm;
958         struct amdgpu_bo_va_mapping *mapping;
959         dma_addr_t *pages_addr = NULL;
960         struct ttm_resource *mem;
961         struct dma_fence **last_update;
962         bool flush_tlb = clear;
963         struct dma_resv *resv;
964         uint64_t vram_base;
965         uint64_t flags;
966         int r;
967
968         if (clear || !bo) {
969                 mem = NULL;
970                 resv = vm->root.bo->tbo.base.resv;
971         } else {
972                 struct drm_gem_object *obj = &bo->tbo.base;
973
974                 resv = bo->tbo.base.resv;
975                 if (obj->import_attach && bo_va->is_xgmi) {
976                         struct dma_buf *dma_buf = obj->import_attach->dmabuf;
977                         struct drm_gem_object *gobj = dma_buf->priv;
978                         struct amdgpu_bo *abo = gem_to_amdgpu_bo(gobj);
979
980                         if (abo->tbo.resource->mem_type == TTM_PL_VRAM)
981                                 bo = gem_to_amdgpu_bo(gobj);
982                 }
983                 mem = bo->tbo.resource;
984                 if (mem->mem_type == TTM_PL_TT ||
985                     mem->mem_type == AMDGPU_PL_PREEMPT)
986                         pages_addr = bo->tbo.ttm->dma_address;
987         }
988
989         if (bo) {
990                 struct amdgpu_device *bo_adev;
991
992                 flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
993
994                 if (amdgpu_bo_encrypted(bo))
995                         flags |= AMDGPU_PTE_TMZ;
996
997                 bo_adev = amdgpu_ttm_adev(bo->tbo.bdev);
998                 vram_base = bo_adev->vm_manager.vram_base_offset;
999         } else {
1000                 flags = 0x0;
1001                 vram_base = 0;
1002         }
1003
1004         if (clear || (bo && bo->tbo.base.resv ==
1005                       vm->root.bo->tbo.base.resv))
1006                 last_update = &vm->last_update;
1007         else
1008                 last_update = &bo_va->last_pt_update;
1009
1010         if (!clear && bo_va->base.moved) {
1011                 flush_tlb = true;
1012                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1013
1014         } else if (bo_va->cleared != clear) {
1015                 list_splice_init(&bo_va->valids, &bo_va->invalids);
1016         }
1017
1018         list_for_each_entry(mapping, &bo_va->invalids, list) {
1019                 uint64_t update_flags = flags;
1020
1021                 /* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1022                  * but in case of something, we filter the flags in first place
1023                  */
1024                 if (!(mapping->flags & AMDGPU_PTE_READABLE))
1025                         update_flags &= ~AMDGPU_PTE_READABLE;
1026                 if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1027                         update_flags &= ~AMDGPU_PTE_WRITEABLE;
1028
1029                 /* Apply ASIC specific mapping flags */
1030                 amdgpu_gmc_get_vm_pte(adev, mapping, &update_flags);
1031
1032                 trace_amdgpu_vm_bo_update(mapping);
1033
1034                 r = amdgpu_vm_update_range(adev, vm, false, false, flush_tlb,
1035                                            resv, mapping->start, mapping->last,
1036                                            update_flags, mapping->offset,
1037                                            vram_base, mem, pages_addr,
1038                                            last_update);
1039                 if (r)
1040                         return r;
1041         }
1042
1043         /* If the BO is not in its preferred location add it back to
1044          * the evicted list so that it gets validated again on the
1045          * next command submission.
1046          */
1047         if (bo && bo->tbo.base.resv == vm->root.bo->tbo.base.resv) {
1048                 uint32_t mem_type = bo->tbo.resource->mem_type;
1049
1050                 if (!(bo->preferred_domains &
1051                       amdgpu_mem_type_to_domain(mem_type)))
1052                         amdgpu_vm_bo_evicted(&bo_va->base);
1053                 else
1054                         amdgpu_vm_bo_idle(&bo_va->base);
1055         } else {
1056                 amdgpu_vm_bo_done(&bo_va->base);
1057         }
1058
1059         list_splice_init(&bo_va->invalids, &bo_va->valids);
1060         bo_va->cleared = clear;
1061         bo_va->base.moved = false;
1062
1063         if (trace_amdgpu_vm_bo_mapping_enabled()) {
1064                 list_for_each_entry(mapping, &bo_va->valids, list)
1065                         trace_amdgpu_vm_bo_mapping(mapping);
1066         }
1067
1068         return 0;
1069 }
1070
1071 /**
1072  * amdgpu_vm_update_prt_state - update the global PRT state
1073  *
1074  * @adev: amdgpu_device pointer
1075  */
1076 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1077 {
1078         unsigned long flags;
1079         bool enable;
1080
1081         spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1082         enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1083         adev->gmc.gmc_funcs->set_prt(adev, enable);
1084         spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1085 }
1086
1087 /**
1088  * amdgpu_vm_prt_get - add a PRT user
1089  *
1090  * @adev: amdgpu_device pointer
1091  */
1092 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1093 {
1094         if (!adev->gmc.gmc_funcs->set_prt)
1095                 return;
1096
1097         if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1098                 amdgpu_vm_update_prt_state(adev);
1099 }
1100
1101 /**
1102  * amdgpu_vm_prt_put - drop a PRT user
1103  *
1104  * @adev: amdgpu_device pointer
1105  */
1106 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1107 {
1108         if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1109                 amdgpu_vm_update_prt_state(adev);
1110 }
1111
1112 /**
1113  * amdgpu_vm_prt_cb - callback for updating the PRT status
1114  *
1115  * @fence: fence for the callback
1116  * @_cb: the callback function
1117  */
1118 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1119 {
1120         struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1121
1122         amdgpu_vm_prt_put(cb->adev);
1123         kfree(cb);
1124 }
1125
1126 /**
1127  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1128  *
1129  * @adev: amdgpu_device pointer
1130  * @fence: fence for the callback
1131  */
1132 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1133                                  struct dma_fence *fence)
1134 {
1135         struct amdgpu_prt_cb *cb;
1136
1137         if (!adev->gmc.gmc_funcs->set_prt)
1138                 return;
1139
1140         cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
1141         if (!cb) {
1142                 /* Last resort when we are OOM */
1143                 if (fence)
1144                         dma_fence_wait(fence, false);
1145
1146                 amdgpu_vm_prt_put(adev);
1147         } else {
1148                 cb->adev = adev;
1149                 if (!fence || dma_fence_add_callback(fence, &cb->cb,
1150                                                      amdgpu_vm_prt_cb))
1151                         amdgpu_vm_prt_cb(fence, &cb->cb);
1152         }
1153 }
1154
1155 /**
1156  * amdgpu_vm_free_mapping - free a mapping
1157  *
1158  * @adev: amdgpu_device pointer
1159  * @vm: requested vm
1160  * @mapping: mapping to be freed
1161  * @fence: fence of the unmap operation
1162  *
1163  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1164  */
1165 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1166                                    struct amdgpu_vm *vm,
1167                                    struct amdgpu_bo_va_mapping *mapping,
1168                                    struct dma_fence *fence)
1169 {
1170         if (mapping->flags & AMDGPU_PTE_PRT)
1171                 amdgpu_vm_add_prt_cb(adev, fence);
1172         kfree(mapping);
1173 }
1174
1175 /**
1176  * amdgpu_vm_prt_fini - finish all prt mappings
1177  *
1178  * @adev: amdgpu_device pointer
1179  * @vm: requested vm
1180  *
1181  * Register a cleanup callback to disable PRT support after VM dies.
1182  */
1183 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1184 {
1185         struct dma_resv *resv = vm->root.bo->tbo.base.resv;
1186         struct dma_resv_iter cursor;
1187         struct dma_fence *fence;
1188
1189         dma_resv_for_each_fence(&cursor, resv, DMA_RESV_USAGE_BOOKKEEP, fence) {
1190                 /* Add a callback for each fence in the reservation object */
1191                 amdgpu_vm_prt_get(adev);
1192                 amdgpu_vm_add_prt_cb(adev, fence);
1193         }
1194 }
1195
1196 /**
1197  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1198  *
1199  * @adev: amdgpu_device pointer
1200  * @vm: requested vm
1201  * @fence: optional resulting fence (unchanged if no work needed to be done
1202  * or if an error occurred)
1203  *
1204  * Make sure all freed BOs are cleared in the PT.
1205  * PTs have to be reserved and mutex must be locked!
1206  *
1207  * Returns:
1208  * 0 for success.
1209  *
1210  */
1211 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
1212                           struct amdgpu_vm *vm,
1213                           struct dma_fence **fence)
1214 {
1215         struct dma_resv *resv = vm->root.bo->tbo.base.resv;
1216         struct amdgpu_bo_va_mapping *mapping;
1217         uint64_t init_pte_value = 0;
1218         struct dma_fence *f = NULL;
1219         int r;
1220
1221         while (!list_empty(&vm->freed)) {
1222                 mapping = list_first_entry(&vm->freed,
1223                         struct amdgpu_bo_va_mapping, list);
1224                 list_del(&mapping->list);
1225
1226                 if (vm->pte_support_ats &&
1227                     mapping->start < AMDGPU_GMC_HOLE_START)
1228                         init_pte_value = AMDGPU_PTE_DEFAULT_ATC;
1229
1230                 r = amdgpu_vm_update_range(adev, vm, false, false, true, resv,
1231                                            mapping->start, mapping->last,
1232                                            init_pte_value, 0, 0, NULL, NULL,
1233                                            &f);
1234                 amdgpu_vm_free_mapping(adev, vm, mapping, f);
1235                 if (r) {
1236                         dma_fence_put(f);
1237                         return r;
1238                 }
1239         }
1240
1241         if (fence && f) {
1242                 dma_fence_put(*fence);
1243                 *fence = f;
1244         } else {
1245                 dma_fence_put(f);
1246         }
1247
1248         return 0;
1249
1250 }
1251
1252 /**
1253  * amdgpu_vm_handle_moved - handle moved BOs in the PT
1254  *
1255  * @adev: amdgpu_device pointer
1256  * @vm: requested vm
1257  *
1258  * Make sure all BOs which are moved are updated in the PTs.
1259  *
1260  * Returns:
1261  * 0 for success.
1262  *
1263  * PTs have to be reserved!
1264  */
1265 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
1266                            struct amdgpu_vm *vm)
1267 {
1268         struct amdgpu_bo_va *bo_va, *tmp;
1269         struct dma_resv *resv;
1270         bool clear;
1271         int r;
1272
1273         list_for_each_entry_safe(bo_va, tmp, &vm->moved, base.vm_status) {
1274                 /* Per VM BOs never need to bo cleared in the page tables */
1275                 r = amdgpu_vm_bo_update(adev, bo_va, false);
1276                 if (r)
1277                         return r;
1278         }
1279
1280         spin_lock(&vm->invalidated_lock);
1281         while (!list_empty(&vm->invalidated)) {
1282                 bo_va = list_first_entry(&vm->invalidated, struct amdgpu_bo_va,
1283                                          base.vm_status);
1284                 resv = bo_va->base.bo->tbo.base.resv;
1285                 spin_unlock(&vm->invalidated_lock);
1286
1287                 /* Try to reserve the BO to avoid clearing its ptes */
1288                 if (!amdgpu_vm_debug && dma_resv_trylock(resv))
1289                         clear = false;
1290                 /* Somebody else is using the BO right now */
1291                 else
1292                         clear = true;
1293
1294                 r = amdgpu_vm_bo_update(adev, bo_va, clear);
1295                 if (r)
1296                         return r;
1297
1298                 if (!clear)
1299                         dma_resv_unlock(resv);
1300                 spin_lock(&vm->invalidated_lock);
1301         }
1302         spin_unlock(&vm->invalidated_lock);
1303
1304         return 0;
1305 }
1306
1307 /**
1308  * amdgpu_vm_bo_add - add a bo to a specific vm
1309  *
1310  * @adev: amdgpu_device pointer
1311  * @vm: requested vm
1312  * @bo: amdgpu buffer object
1313  *
1314  * Add @bo into the requested vm.
1315  * Add @bo to the list of bos associated with the vm
1316  *
1317  * Returns:
1318  * Newly added bo_va or NULL for failure
1319  *
1320  * Object has to be reserved!
1321  */
1322 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
1323                                       struct amdgpu_vm *vm,
1324                                       struct amdgpu_bo *bo)
1325 {
1326         struct amdgpu_bo_va *bo_va;
1327
1328         bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
1329         if (bo_va == NULL) {
1330                 return NULL;
1331         }
1332         amdgpu_vm_bo_base_init(&bo_va->base, vm, bo);
1333
1334         bo_va->ref_count = 1;
1335         INIT_LIST_HEAD(&bo_va->valids);
1336         INIT_LIST_HEAD(&bo_va->invalids);
1337
1338         if (!bo)
1339                 return bo_va;
1340
1341         dma_resv_assert_held(bo->tbo.base.resv);
1342         if (amdgpu_dmabuf_is_xgmi_accessible(adev, bo)) {
1343                 bo_va->is_xgmi = true;
1344                 /* Power up XGMI if it can be potentially used */
1345                 amdgpu_xgmi_set_pstate(adev, AMDGPU_XGMI_PSTATE_MAX_VEGA20);
1346         }
1347
1348         return bo_va;
1349 }
1350
1351
1352 /**
1353  * amdgpu_vm_bo_insert_map - insert a new mapping
1354  *
1355  * @adev: amdgpu_device pointer
1356  * @bo_va: bo_va to store the address
1357  * @mapping: the mapping to insert
1358  *
1359  * Insert a new mapping into all structures.
1360  */
1361 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
1362                                     struct amdgpu_bo_va *bo_va,
1363                                     struct amdgpu_bo_va_mapping *mapping)
1364 {
1365         struct amdgpu_vm *vm = bo_va->base.vm;
1366         struct amdgpu_bo *bo = bo_va->base.bo;
1367
1368         mapping->bo_va = bo_va;
1369         list_add(&mapping->list, &bo_va->invalids);
1370         amdgpu_vm_it_insert(mapping, &vm->va);
1371
1372         if (mapping->flags & AMDGPU_PTE_PRT)
1373                 amdgpu_vm_prt_get(adev);
1374
1375         if (bo && bo->tbo.base.resv == vm->root.bo->tbo.base.resv &&
1376             !bo_va->base.moved) {
1377                 list_move(&bo_va->base.vm_status, &vm->moved);
1378         }
1379         trace_amdgpu_vm_bo_map(bo_va, mapping);
1380 }
1381
1382 /**
1383  * amdgpu_vm_bo_map - map bo inside a vm
1384  *
1385  * @adev: amdgpu_device pointer
1386  * @bo_va: bo_va to store the address
1387  * @saddr: where to map the BO
1388  * @offset: requested offset in the BO
1389  * @size: BO size in bytes
1390  * @flags: attributes of pages (read/write/valid/etc.)
1391  *
1392  * Add a mapping of the BO at the specefied addr into the VM.
1393  *
1394  * Returns:
1395  * 0 for success, error for failure.
1396  *
1397  * Object has to be reserved and unreserved outside!
1398  */
1399 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1400                      struct amdgpu_bo_va *bo_va,
1401                      uint64_t saddr, uint64_t offset,
1402                      uint64_t size, uint64_t flags)
1403 {
1404         struct amdgpu_bo_va_mapping *mapping, *tmp;
1405         struct amdgpu_bo *bo = bo_va->base.bo;
1406         struct amdgpu_vm *vm = bo_va->base.vm;
1407         uint64_t eaddr;
1408
1409         /* validate the parameters */
1410         if (saddr & ~PAGE_MASK || offset & ~PAGE_MASK ||
1411             size == 0 || size & ~PAGE_MASK)
1412                 return -EINVAL;
1413
1414         /* make sure object fit at this offset */
1415         eaddr = saddr + size - 1;
1416         if (saddr >= eaddr ||
1417             (bo && offset + size > amdgpu_bo_size(bo)) ||
1418             (eaddr >= adev->vm_manager.max_pfn << AMDGPU_GPU_PAGE_SHIFT))
1419                 return -EINVAL;
1420
1421         saddr /= AMDGPU_GPU_PAGE_SIZE;
1422         eaddr /= AMDGPU_GPU_PAGE_SIZE;
1423
1424         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
1425         if (tmp) {
1426                 /* bo and tmp overlap, invalid addr */
1427                 dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1428                         "0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
1429                         tmp->start, tmp->last + 1);
1430                 return -EINVAL;
1431         }
1432
1433         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1434         if (!mapping)
1435                 return -ENOMEM;
1436
1437         mapping->start = saddr;
1438         mapping->last = eaddr;
1439         mapping->offset = offset;
1440         mapping->flags = flags;
1441
1442         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1443
1444         return 0;
1445 }
1446
1447 /**
1448  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
1449  *
1450  * @adev: amdgpu_device pointer
1451  * @bo_va: bo_va to store the address
1452  * @saddr: where to map the BO
1453  * @offset: requested offset in the BO
1454  * @size: BO size in bytes
1455  * @flags: attributes of pages (read/write/valid/etc.)
1456  *
1457  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
1458  * mappings as we do so.
1459  *
1460  * Returns:
1461  * 0 for success, error for failure.
1462  *
1463  * Object has to be reserved and unreserved outside!
1464  */
1465 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
1466                              struct amdgpu_bo_va *bo_va,
1467                              uint64_t saddr, uint64_t offset,
1468                              uint64_t size, uint64_t flags)
1469 {
1470         struct amdgpu_bo_va_mapping *mapping;
1471         struct amdgpu_bo *bo = bo_va->base.bo;
1472         uint64_t eaddr;
1473         int r;
1474
1475         /* validate the parameters */
1476         if (saddr & ~PAGE_MASK || offset & ~PAGE_MASK ||
1477             size == 0 || size & ~PAGE_MASK)
1478                 return -EINVAL;
1479
1480         /* make sure object fit at this offset */
1481         eaddr = saddr + size - 1;
1482         if (saddr >= eaddr ||
1483             (bo && offset + size > amdgpu_bo_size(bo)) ||
1484             (eaddr >= adev->vm_manager.max_pfn << AMDGPU_GPU_PAGE_SHIFT))
1485                 return -EINVAL;
1486
1487         /* Allocate all the needed memory */
1488         mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1489         if (!mapping)
1490                 return -ENOMEM;
1491
1492         r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
1493         if (r) {
1494                 kfree(mapping);
1495                 return r;
1496         }
1497
1498         saddr /= AMDGPU_GPU_PAGE_SIZE;
1499         eaddr /= AMDGPU_GPU_PAGE_SIZE;
1500
1501         mapping->start = saddr;
1502         mapping->last = eaddr;
1503         mapping->offset = offset;
1504         mapping->flags = flags;
1505
1506         amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
1507
1508         return 0;
1509 }
1510
1511 /**
1512  * amdgpu_vm_bo_unmap - remove bo mapping from vm
1513  *
1514  * @adev: amdgpu_device pointer
1515  * @bo_va: bo_va to remove the address from
1516  * @saddr: where to the BO is mapped
1517  *
1518  * Remove a mapping of the BO at the specefied addr from the VM.
1519  *
1520  * Returns:
1521  * 0 for success, error for failure.
1522  *
1523  * Object has to be reserved and unreserved outside!
1524  */
1525 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
1526                        struct amdgpu_bo_va *bo_va,
1527                        uint64_t saddr)
1528 {
1529         struct amdgpu_bo_va_mapping *mapping;
1530         struct amdgpu_vm *vm = bo_va->base.vm;
1531         bool valid = true;
1532
1533         saddr /= AMDGPU_GPU_PAGE_SIZE;
1534
1535         list_for_each_entry(mapping, &bo_va->valids, list) {
1536                 if (mapping->start == saddr)
1537                         break;
1538         }
1539
1540         if (&mapping->list == &bo_va->valids) {
1541                 valid = false;
1542
1543                 list_for_each_entry(mapping, &bo_va->invalids, list) {
1544                         if (mapping->start == saddr)
1545                                 break;
1546                 }
1547
1548                 if (&mapping->list == &bo_va->invalids)
1549                         return -ENOENT;
1550         }
1551
1552         list_del(&mapping->list);
1553         amdgpu_vm_it_remove(mapping, &vm->va);
1554         mapping->bo_va = NULL;
1555         trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1556
1557         if (valid)
1558                 list_add(&mapping->list, &vm->freed);
1559         else
1560                 amdgpu_vm_free_mapping(adev, vm, mapping,
1561                                        bo_va->last_pt_update);
1562
1563         return 0;
1564 }
1565
1566 /**
1567  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
1568  *
1569  * @adev: amdgpu_device pointer
1570  * @vm: VM structure to use
1571  * @saddr: start of the range
1572  * @size: size of the range
1573  *
1574  * Remove all mappings in a range, split them as appropriate.
1575  *
1576  * Returns:
1577  * 0 for success, error for failure.
1578  */
1579 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
1580                                 struct amdgpu_vm *vm,
1581                                 uint64_t saddr, uint64_t size)
1582 {
1583         struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
1584         LIST_HEAD(removed);
1585         uint64_t eaddr;
1586
1587         eaddr = saddr + size - 1;
1588         saddr /= AMDGPU_GPU_PAGE_SIZE;
1589         eaddr /= AMDGPU_GPU_PAGE_SIZE;
1590
1591         /* Allocate all the needed memory */
1592         before = kzalloc(sizeof(*before), GFP_KERNEL);
1593         if (!before)
1594                 return -ENOMEM;
1595         INIT_LIST_HEAD(&before->list);
1596
1597         after = kzalloc(sizeof(*after), GFP_KERNEL);
1598         if (!after) {
1599                 kfree(before);
1600                 return -ENOMEM;
1601         }
1602         INIT_LIST_HEAD(&after->list);
1603
1604         /* Now gather all removed mappings */
1605         tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
1606         while (tmp) {
1607                 /* Remember mapping split at the start */
1608                 if (tmp->start < saddr) {
1609                         before->start = tmp->start;
1610                         before->last = saddr - 1;
1611                         before->offset = tmp->offset;
1612                         before->flags = tmp->flags;
1613                         before->bo_va = tmp->bo_va;
1614                         list_add(&before->list, &tmp->bo_va->invalids);
1615                 }
1616
1617                 /* Remember mapping split at the end */
1618                 if (tmp->last > eaddr) {
1619                         after->start = eaddr + 1;
1620                         after->last = tmp->last;
1621                         after->offset = tmp->offset;
1622                         after->offset += (after->start - tmp->start) << PAGE_SHIFT;
1623                         after->flags = tmp->flags;
1624                         after->bo_va = tmp->bo_va;
1625                         list_add(&after->list, &tmp->bo_va->invalids);
1626                 }
1627
1628                 list_del(&tmp->list);
1629                 list_add(&tmp->list, &removed);
1630
1631                 tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
1632         }
1633
1634         /* And free them up */
1635         list_for_each_entry_safe(tmp, next, &removed, list) {
1636                 amdgpu_vm_it_remove(tmp, &vm->va);
1637                 list_del(&tmp->list);
1638
1639                 if (tmp->start < saddr)
1640                     tmp->start = saddr;
1641                 if (tmp->last > eaddr)
1642                     tmp->last = eaddr;
1643
1644                 tmp->bo_va = NULL;
1645                 list_add(&tmp->list, &vm->freed);
1646                 trace_amdgpu_vm_bo_unmap(NULL, tmp);
1647         }
1648
1649         /* Insert partial mapping before the range */
1650         if (!list_empty(&before->list)) {
1651                 amdgpu_vm_it_insert(before, &vm->va);
1652                 if (before->flags & AMDGPU_PTE_PRT)
1653                         amdgpu_vm_prt_get(adev);
1654         } else {
1655                 kfree(before);
1656         }
1657
1658         /* Insert partial mapping after the range */
1659         if (!list_empty(&after->list)) {
1660                 amdgpu_vm_it_insert(after, &vm->va);
1661                 if (after->flags & AMDGPU_PTE_PRT)
1662                         amdgpu_vm_prt_get(adev);
1663         } else {
1664                 kfree(after);
1665         }
1666
1667         return 0;
1668 }
1669
1670 /**
1671  * amdgpu_vm_bo_lookup_mapping - find mapping by address
1672  *
1673  * @vm: the requested VM
1674  * @addr: the address
1675  *
1676  * Find a mapping by it's address.
1677  *
1678  * Returns:
1679  * The amdgpu_bo_va_mapping matching for addr or NULL
1680  *
1681  */
1682 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
1683                                                          uint64_t addr)
1684 {
1685         return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
1686 }
1687
1688 /**
1689  * amdgpu_vm_bo_trace_cs - trace all reserved mappings
1690  *
1691  * @vm: the requested vm
1692  * @ticket: CS ticket
1693  *
1694  * Trace all mappings of BOs reserved during a command submission.
1695  */
1696 void amdgpu_vm_bo_trace_cs(struct amdgpu_vm *vm, struct ww_acquire_ctx *ticket)
1697 {
1698         struct amdgpu_bo_va_mapping *mapping;
1699
1700         if (!trace_amdgpu_vm_bo_cs_enabled())
1701                 return;
1702
1703         for (mapping = amdgpu_vm_it_iter_first(&vm->va, 0, U64_MAX); mapping;
1704              mapping = amdgpu_vm_it_iter_next(mapping, 0, U64_MAX)) {
1705                 if (mapping->bo_va && mapping->bo_va->base.bo) {
1706                         struct amdgpu_bo *bo;
1707
1708                         bo = mapping->bo_va->base.bo;
1709                         if (dma_resv_locking_ctx(bo->tbo.base.resv) !=
1710                             ticket)
1711                                 continue;
1712                 }
1713
1714                 trace_amdgpu_vm_bo_cs(mapping);
1715         }
1716 }
1717
1718 /**
1719  * amdgpu_vm_bo_del - remove a bo from a specific vm
1720  *
1721  * @adev: amdgpu_device pointer
1722  * @bo_va: requested bo_va
1723  *
1724  * Remove @bo_va->bo from the requested vm.
1725  *
1726  * Object have to be reserved!
1727  */
1728 void amdgpu_vm_bo_del(struct amdgpu_device *adev,
1729                       struct amdgpu_bo_va *bo_va)
1730 {
1731         struct amdgpu_bo_va_mapping *mapping, *next;
1732         struct amdgpu_bo *bo = bo_va->base.bo;
1733         struct amdgpu_vm *vm = bo_va->base.vm;
1734         struct amdgpu_vm_bo_base **base;
1735
1736         dma_resv_assert_held(vm->root.bo->tbo.base.resv);
1737
1738         if (bo) {
1739                 dma_resv_assert_held(bo->tbo.base.resv);
1740                 if (bo->tbo.base.resv == vm->root.bo->tbo.base.resv)
1741                         ttm_bo_set_bulk_move(&bo->tbo, NULL);
1742
1743                 for (base = &bo_va->base.bo->vm_bo; *base;
1744                      base = &(*base)->next) {
1745                         if (*base != &bo_va->base)
1746                                 continue;
1747
1748                         *base = bo_va->base.next;
1749                         break;
1750                 }
1751         }
1752
1753         spin_lock(&vm->invalidated_lock);
1754         list_del(&bo_va->base.vm_status);
1755         spin_unlock(&vm->invalidated_lock);
1756
1757         list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
1758                 list_del(&mapping->list);
1759                 amdgpu_vm_it_remove(mapping, &vm->va);
1760                 mapping->bo_va = NULL;
1761                 trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1762                 list_add(&mapping->list, &vm->freed);
1763         }
1764         list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
1765                 list_del(&mapping->list);
1766                 amdgpu_vm_it_remove(mapping, &vm->va);
1767                 amdgpu_vm_free_mapping(adev, vm, mapping,
1768                                        bo_va->last_pt_update);
1769         }
1770
1771         dma_fence_put(bo_va->last_pt_update);
1772
1773         if (bo && bo_va->is_xgmi)
1774                 amdgpu_xgmi_set_pstate(adev, AMDGPU_XGMI_PSTATE_MIN);
1775
1776         kfree(bo_va);
1777 }
1778
1779 /**
1780  * amdgpu_vm_evictable - check if we can evict a VM
1781  *
1782  * @bo: A page table of the VM.
1783  *
1784  * Check if it is possible to evict a VM.
1785  */
1786 bool amdgpu_vm_evictable(struct amdgpu_bo *bo)
1787 {
1788         struct amdgpu_vm_bo_base *bo_base = bo->vm_bo;
1789
1790         /* Page tables of a destroyed VM can go away immediately */
1791         if (!bo_base || !bo_base->vm)
1792                 return true;
1793
1794         /* Don't evict VM page tables while they are busy */
1795         if (!dma_resv_test_signaled(bo->tbo.base.resv, DMA_RESV_USAGE_BOOKKEEP))
1796                 return false;
1797
1798         /* Try to block ongoing updates */
1799         if (!amdgpu_vm_eviction_trylock(bo_base->vm))
1800                 return false;
1801
1802         /* Don't evict VM page tables while they are updated */
1803         if (!dma_fence_is_signaled(bo_base->vm->last_unlocked)) {
1804                 amdgpu_vm_eviction_unlock(bo_base->vm);
1805                 return false;
1806         }
1807
1808         bo_base->vm->evicting = true;
1809         amdgpu_vm_eviction_unlock(bo_base->vm);
1810         return true;
1811 }
1812
1813 /**
1814  * amdgpu_vm_bo_invalidate - mark the bo as invalid
1815  *
1816  * @adev: amdgpu_device pointer
1817  * @bo: amdgpu buffer object
1818  * @evicted: is the BO evicted
1819  *
1820  * Mark @bo as invalid.
1821  */
1822 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
1823                              struct amdgpu_bo *bo, bool evicted)
1824 {
1825         struct amdgpu_vm_bo_base *bo_base;
1826
1827         /* shadow bo doesn't have bo base, its validation needs its parent */
1828         if (bo->parent && (amdgpu_bo_shadowed(bo->parent) == bo))
1829                 bo = bo->parent;
1830
1831         for (bo_base = bo->vm_bo; bo_base; bo_base = bo_base->next) {
1832                 struct amdgpu_vm *vm = bo_base->vm;
1833
1834                 if (evicted && bo->tbo.base.resv == vm->root.bo->tbo.base.resv) {
1835                         amdgpu_vm_bo_evicted(bo_base);
1836                         continue;
1837                 }
1838
1839                 if (bo_base->moved)
1840                         continue;
1841                 bo_base->moved = true;
1842
1843                 if (bo->tbo.type == ttm_bo_type_kernel)
1844                         amdgpu_vm_bo_relocated(bo_base);
1845                 else if (bo->tbo.base.resv == vm->root.bo->tbo.base.resv)
1846                         amdgpu_vm_bo_moved(bo_base);
1847                 else
1848                         amdgpu_vm_bo_invalidated(bo_base);
1849         }
1850 }
1851
1852 /**
1853  * amdgpu_vm_get_block_size - calculate VM page table size as power of two
1854  *
1855  * @vm_size: VM size
1856  *
1857  * Returns:
1858  * VM page table as power of two
1859  */
1860 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
1861 {
1862         /* Total bits covered by PD + PTs */
1863         unsigned bits = ilog2(vm_size) + 18;
1864
1865         /* Make sure the PD is 4K in size up to 8GB address space.
1866            Above that split equal between PD and PTs */
1867         if (vm_size <= 8)
1868                 return (bits - 9);
1869         else
1870                 return ((bits + 3) / 2);
1871 }
1872
1873 /**
1874  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
1875  *
1876  * @adev: amdgpu_device pointer
1877  * @min_vm_size: the minimum vm size in GB if it's set auto
1878  * @fragment_size_default: Default PTE fragment size
1879  * @max_level: max VMPT level
1880  * @max_bits: max address space size in bits
1881  *
1882  */
1883 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint32_t min_vm_size,
1884                            uint32_t fragment_size_default, unsigned max_level,
1885                            unsigned max_bits)
1886 {
1887         unsigned int max_size = 1 << (max_bits - 30);
1888         unsigned int vm_size;
1889         uint64_t tmp;
1890
1891         /* adjust vm size first */
1892         if (amdgpu_vm_size != -1) {
1893                 vm_size = amdgpu_vm_size;
1894                 if (vm_size > max_size) {
1895                         dev_warn(adev->dev, "VM size (%d) too large, max is %u GB\n",
1896                                  amdgpu_vm_size, max_size);
1897                         vm_size = max_size;
1898                 }
1899         } else {
1900                 struct sysinfo si;
1901                 unsigned int phys_ram_gb;
1902
1903                 /* Optimal VM size depends on the amount of physical
1904                  * RAM available. Underlying requirements and
1905                  * assumptions:
1906                  *
1907                  *  - Need to map system memory and VRAM from all GPUs
1908                  *     - VRAM from other GPUs not known here
1909                  *     - Assume VRAM <= system memory
1910                  *  - On GFX8 and older, VM space can be segmented for
1911                  *    different MTYPEs
1912                  *  - Need to allow room for fragmentation, guard pages etc.
1913                  *
1914                  * This adds up to a rough guess of system memory x3.
1915                  * Round up to power of two to maximize the available
1916                  * VM size with the given page table size.
1917                  */
1918                 si_meminfo(&si);
1919                 phys_ram_gb = ((uint64_t)si.totalram * si.mem_unit +
1920                                (1 << 30) - 1) >> 30;
1921                 vm_size = roundup_pow_of_two(
1922                         min(max(phys_ram_gb * 3, min_vm_size), max_size));
1923         }
1924
1925         adev->vm_manager.max_pfn = (uint64_t)vm_size << 18;
1926
1927         tmp = roundup_pow_of_two(adev->vm_manager.max_pfn);
1928         if (amdgpu_vm_block_size != -1)
1929                 tmp >>= amdgpu_vm_block_size - 9;
1930         tmp = DIV_ROUND_UP(fls64(tmp) - 1, 9) - 1;
1931         adev->vm_manager.num_level = min(max_level, (unsigned)tmp);
1932         switch (adev->vm_manager.num_level) {
1933         case 3:
1934                 adev->vm_manager.root_level = AMDGPU_VM_PDB2;
1935                 break;
1936         case 2:
1937                 adev->vm_manager.root_level = AMDGPU_VM_PDB1;
1938                 break;
1939         case 1:
1940                 adev->vm_manager.root_level = AMDGPU_VM_PDB0;
1941                 break;
1942         default:
1943                 dev_err(adev->dev, "VMPT only supports 2~4+1 levels\n");
1944         }
1945         /* block size depends on vm size and hw setup*/
1946         if (amdgpu_vm_block_size != -1)
1947                 adev->vm_manager.block_size =
1948                         min((unsigned)amdgpu_vm_block_size, max_bits
1949                             - AMDGPU_GPU_PAGE_SHIFT
1950                             - 9 * adev->vm_manager.num_level);
1951         else if (adev->vm_manager.num_level > 1)
1952                 adev->vm_manager.block_size = 9;
1953         else
1954                 adev->vm_manager.block_size = amdgpu_vm_get_block_size(tmp);
1955
1956         if (amdgpu_vm_fragment_size == -1)
1957                 adev->vm_manager.fragment_size = fragment_size_default;
1958         else
1959                 adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
1960
1961         DRM_INFO("vm size is %u GB, %u levels, block size is %u-bit, fragment size is %u-bit\n",
1962                  vm_size, adev->vm_manager.num_level + 1,
1963                  adev->vm_manager.block_size,
1964                  adev->vm_manager.fragment_size);
1965 }
1966
1967 /**
1968  * amdgpu_vm_wait_idle - wait for the VM to become idle
1969  *
1970  * @vm: VM object to wait for
1971  * @timeout: timeout to wait for VM to become idle
1972  */
1973 long amdgpu_vm_wait_idle(struct amdgpu_vm *vm, long timeout)
1974 {
1975         timeout = dma_resv_wait_timeout(vm->root.bo->tbo.base.resv,
1976                                         DMA_RESV_USAGE_BOOKKEEP,
1977                                         true, timeout);
1978         if (timeout <= 0)
1979                 return timeout;
1980
1981         return dma_fence_wait_timeout(vm->last_unlocked, true, timeout);
1982 }
1983
1984 /**
1985  * amdgpu_vm_init - initialize a vm instance
1986  *
1987  * @adev: amdgpu_device pointer
1988  * @vm: requested vm
1989  *
1990  * Init @vm fields.
1991  *
1992  * Returns:
1993  * 0 for success, error for failure.
1994  */
1995 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1996 {
1997         struct amdgpu_bo *root_bo;
1998         struct amdgpu_bo_vm *root;
1999         int r, i;
2000
2001         vm->va = RB_ROOT_CACHED;
2002         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2003                 vm->reserved_vmid[i] = NULL;
2004         INIT_LIST_HEAD(&vm->evicted);
2005         INIT_LIST_HEAD(&vm->relocated);
2006         INIT_LIST_HEAD(&vm->moved);
2007         INIT_LIST_HEAD(&vm->idle);
2008         INIT_LIST_HEAD(&vm->invalidated);
2009         spin_lock_init(&vm->invalidated_lock);
2010         INIT_LIST_HEAD(&vm->freed);
2011         INIT_LIST_HEAD(&vm->done);
2012
2013         /* create scheduler entities for page table updates */
2014         r = drm_sched_entity_init(&vm->immediate, DRM_SCHED_PRIORITY_NORMAL,
2015                                   adev->vm_manager.vm_pte_scheds,
2016                                   adev->vm_manager.vm_pte_num_scheds, NULL);
2017         if (r)
2018                 return r;
2019
2020         r = drm_sched_entity_init(&vm->delayed, DRM_SCHED_PRIORITY_NORMAL,
2021                                   adev->vm_manager.vm_pte_scheds,
2022                                   adev->vm_manager.vm_pte_num_scheds, NULL);
2023         if (r)
2024                 goto error_free_immediate;
2025
2026         vm->pte_support_ats = false;
2027         vm->is_compute_context = false;
2028
2029         vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2030                                     AMDGPU_VM_USE_CPU_FOR_GFX);
2031
2032         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2033                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2034         WARN_ONCE((vm->use_cpu_for_update &&
2035                    !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2036                   "CPU update of VM recommended only for large BAR system\n");
2037
2038         if (vm->use_cpu_for_update)
2039                 vm->update_funcs = &amdgpu_vm_cpu_funcs;
2040         else
2041                 vm->update_funcs = &amdgpu_vm_sdma_funcs;
2042         vm->last_update = NULL;
2043         vm->last_unlocked = dma_fence_get_stub();
2044         vm->last_tlb_flush = dma_fence_get_stub();
2045
2046         mutex_init(&vm->eviction_lock);
2047         vm->evicting = false;
2048
2049         r = amdgpu_vm_pt_create(adev, vm, adev->vm_manager.root_level,
2050                                 false, &root);
2051         if (r)
2052                 goto error_free_delayed;
2053         root_bo = &root->bo;
2054         r = amdgpu_bo_reserve(root_bo, true);
2055         if (r)
2056                 goto error_free_root;
2057
2058         r = dma_resv_reserve_fences(root_bo->tbo.base.resv, 1);
2059         if (r)
2060                 goto error_unreserve;
2061
2062         amdgpu_vm_bo_base_init(&vm->root, vm, root_bo);
2063
2064         r = amdgpu_vm_pt_clear(adev, vm, root, false);
2065         if (r)
2066                 goto error_unreserve;
2067
2068         amdgpu_bo_unreserve(vm->root.bo);
2069
2070         INIT_KFIFO(vm->faults);
2071
2072         return 0;
2073
2074 error_unreserve:
2075         amdgpu_bo_unreserve(vm->root.bo);
2076
2077 error_free_root:
2078         amdgpu_bo_unref(&root->shadow);
2079         amdgpu_bo_unref(&root_bo);
2080         vm->root.bo = NULL;
2081
2082 error_free_delayed:
2083         dma_fence_put(vm->last_tlb_flush);
2084         dma_fence_put(vm->last_unlocked);
2085         drm_sched_entity_destroy(&vm->delayed);
2086
2087 error_free_immediate:
2088         drm_sched_entity_destroy(&vm->immediate);
2089
2090         return r;
2091 }
2092
2093 /**
2094  * amdgpu_vm_make_compute - Turn a GFX VM into a compute VM
2095  *
2096  * @adev: amdgpu_device pointer
2097  * @vm: requested vm
2098  *
2099  * This only works on GFX VMs that don't have any BOs added and no
2100  * page tables allocated yet.
2101  *
2102  * Changes the following VM parameters:
2103  * - use_cpu_for_update
2104  * - pte_supports_ats
2105  *
2106  * Reinitializes the page directory to reflect the changed ATS
2107  * setting.
2108  *
2109  * Returns:
2110  * 0 for success, -errno for errors.
2111  */
2112 int amdgpu_vm_make_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2113 {
2114         bool pte_support_ats = (adev->asic_type == CHIP_RAVEN);
2115         int r;
2116
2117         r = amdgpu_bo_reserve(vm->root.bo, true);
2118         if (r)
2119                 return r;
2120
2121         /* Sanity checks */
2122         if (!amdgpu_vm_pt_is_root_clean(adev, vm)) {
2123                 r = -EINVAL;
2124                 goto unreserve_bo;
2125         }
2126
2127         /* Check if PD needs to be reinitialized and do it before
2128          * changing any other state, in case it fails.
2129          */
2130         if (pte_support_ats != vm->pte_support_ats) {
2131                 vm->pte_support_ats = pte_support_ats;
2132                 r = amdgpu_vm_pt_clear(adev, vm, to_amdgpu_bo_vm(vm->root.bo),
2133                                        false);
2134                 if (r)
2135                         goto unreserve_bo;
2136         }
2137
2138         /* Update VM state */
2139         vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2140                                     AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2141         DRM_DEBUG_DRIVER("VM update mode is %s\n",
2142                          vm->use_cpu_for_update ? "CPU" : "SDMA");
2143         WARN_ONCE((vm->use_cpu_for_update &&
2144                    !amdgpu_gmc_vram_full_visible(&adev->gmc)),
2145                   "CPU update of VM recommended only for large BAR system\n");
2146
2147         if (vm->use_cpu_for_update) {
2148                 /* Sync with last SDMA update/clear before switching to CPU */
2149                 r = amdgpu_bo_sync_wait(vm->root.bo,
2150                                         AMDGPU_FENCE_OWNER_UNDEFINED, true);
2151                 if (r)
2152                         goto unreserve_bo;
2153
2154                 vm->update_funcs = &amdgpu_vm_cpu_funcs;
2155         } else {
2156                 vm->update_funcs = &amdgpu_vm_sdma_funcs;
2157         }
2158         dma_fence_put(vm->last_update);
2159         vm->last_update = NULL;
2160         vm->is_compute_context = true;
2161
2162         /* Free the shadow bo for compute VM */
2163         amdgpu_bo_unref(&to_amdgpu_bo_vm(vm->root.bo)->shadow);
2164
2165         goto unreserve_bo;
2166
2167 unreserve_bo:
2168         amdgpu_bo_unreserve(vm->root.bo);
2169         return r;
2170 }
2171
2172 /**
2173  * amdgpu_vm_release_compute - release a compute vm
2174  * @adev: amdgpu_device pointer
2175  * @vm: a vm turned into compute vm by calling amdgpu_vm_make_compute
2176  *
2177  * This is a correspondant of amdgpu_vm_make_compute. It decouples compute
2178  * pasid from vm. Compute should stop use of vm after this call.
2179  */
2180 void amdgpu_vm_release_compute(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2181 {
2182         amdgpu_vm_set_pasid(adev, vm, 0);
2183         vm->is_compute_context = false;
2184 }
2185
2186 /**
2187  * amdgpu_vm_fini - tear down a vm instance
2188  *
2189  * @adev: amdgpu_device pointer
2190  * @vm: requested vm
2191  *
2192  * Tear down @vm.
2193  * Unbind the VM and remove all bos from the vm bo list
2194  */
2195 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2196 {
2197         struct amdgpu_bo_va_mapping *mapping, *tmp;
2198         bool prt_fini_needed = !!adev->gmc.gmc_funcs->set_prt;
2199         struct amdgpu_bo *root;
2200         unsigned long flags;
2201         int i;
2202
2203         amdgpu_amdkfd_gpuvm_destroy_cb(adev, vm);
2204
2205         root = amdgpu_bo_ref(vm->root.bo);
2206         amdgpu_bo_reserve(root, true);
2207         amdgpu_vm_set_pasid(adev, vm, 0);
2208         dma_fence_wait(vm->last_unlocked, false);
2209         dma_fence_put(vm->last_unlocked);
2210         dma_fence_wait(vm->last_tlb_flush, false);
2211         /* Make sure that all fence callbacks have completed */
2212         spin_lock_irqsave(vm->last_tlb_flush->lock, flags);
2213         spin_unlock_irqrestore(vm->last_tlb_flush->lock, flags);
2214         dma_fence_put(vm->last_tlb_flush);
2215
2216         list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2217                 if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
2218                         amdgpu_vm_prt_fini(adev, vm);
2219                         prt_fini_needed = false;
2220                 }
2221
2222                 list_del(&mapping->list);
2223                 amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2224         }
2225
2226         amdgpu_vm_pt_free_root(adev, vm);
2227         amdgpu_bo_unreserve(root);
2228         amdgpu_bo_unref(&root);
2229         WARN_ON(vm->root.bo);
2230
2231         drm_sched_entity_destroy(&vm->immediate);
2232         drm_sched_entity_destroy(&vm->delayed);
2233
2234         if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
2235                 dev_err(adev->dev, "still active bo inside vm\n");
2236         }
2237         rbtree_postorder_for_each_entry_safe(mapping, tmp,
2238                                              &vm->va.rb_root, rb) {
2239                 /* Don't remove the mapping here, we don't want to trigger a
2240                  * rebalance and the tree is about to be destroyed anyway.
2241                  */
2242                 list_del(&mapping->list);
2243                 kfree(mapping);
2244         }
2245
2246         dma_fence_put(vm->last_update);
2247         for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2248                 amdgpu_vmid_free_reserved(adev, vm, i);
2249 }
2250
2251 /**
2252  * amdgpu_vm_manager_init - init the VM manager
2253  *
2254  * @adev: amdgpu_device pointer
2255  *
2256  * Initialize the VM manager structures
2257  */
2258 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
2259 {
2260         unsigned i;
2261
2262         /* Concurrent flushes are only possible starting with Vega10 and
2263          * are broken on Navi10 and Navi14.
2264          */
2265         adev->vm_manager.concurrent_flush = !(adev->asic_type < CHIP_VEGA10 ||
2266                                               adev->asic_type == CHIP_NAVI10 ||
2267                                               adev->asic_type == CHIP_NAVI14);
2268         amdgpu_vmid_mgr_init(adev);
2269
2270         adev->vm_manager.fence_context =
2271                 dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2272         for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
2273                 adev->vm_manager.seqno[i] = 0;
2274
2275         spin_lock_init(&adev->vm_manager.prt_lock);
2276         atomic_set(&adev->vm_manager.num_prt_users, 0);
2277
2278         /* If not overridden by the user, by default, only in large BAR systems
2279          * Compute VM tables will be updated by CPU
2280          */
2281 #ifdef CONFIG_X86_64
2282         if (amdgpu_vm_update_mode == -1) {
2283                 if (amdgpu_gmc_vram_full_visible(&adev->gmc))
2284                         adev->vm_manager.vm_update_mode =
2285                                 AMDGPU_VM_USE_CPU_FOR_COMPUTE;
2286                 else
2287                         adev->vm_manager.vm_update_mode = 0;
2288         } else
2289                 adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
2290 #else
2291         adev->vm_manager.vm_update_mode = 0;
2292 #endif
2293
2294         xa_init_flags(&adev->vm_manager.pasids, XA_FLAGS_LOCK_IRQ);
2295 }
2296
2297 /**
2298  * amdgpu_vm_manager_fini - cleanup VM manager
2299  *
2300  * @adev: amdgpu_device pointer
2301  *
2302  * Cleanup the VM manager and free resources.
2303  */
2304 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
2305 {
2306         WARN_ON(!xa_empty(&adev->vm_manager.pasids));
2307         xa_destroy(&adev->vm_manager.pasids);
2308
2309         amdgpu_vmid_mgr_fini(adev);
2310 }
2311
2312 /**
2313  * amdgpu_vm_ioctl - Manages VMID reservation for vm hubs.
2314  *
2315  * @dev: drm device pointer
2316  * @data: drm_amdgpu_vm
2317  * @filp: drm file pointer
2318  *
2319  * Returns:
2320  * 0 for success, -errno for errors.
2321  */
2322 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
2323 {
2324         union drm_amdgpu_vm *args = data;
2325         struct amdgpu_device *adev = drm_to_adev(dev);
2326         struct amdgpu_fpriv *fpriv = filp->driver_priv;
2327         long timeout = msecs_to_jiffies(2000);
2328         int r;
2329
2330         switch (args->in.op) {
2331         case AMDGPU_VM_OP_RESERVE_VMID:
2332                 /* We only have requirement to reserve vmid from gfxhub */
2333                 r = amdgpu_vmid_alloc_reserved(adev, &fpriv->vm,
2334                                                AMDGPU_GFXHUB_0);
2335                 if (r)
2336                         return r;
2337                 break;
2338         case AMDGPU_VM_OP_UNRESERVE_VMID:
2339                 if (amdgpu_sriov_runtime(adev))
2340                         timeout = 8 * timeout;
2341
2342                 /* Wait vm idle to make sure the vmid set in SPM_VMID is
2343                  * not referenced anymore.
2344                  */
2345                 r = amdgpu_bo_reserve(fpriv->vm.root.bo, true);
2346                 if (r)
2347                         return r;
2348
2349                 r = amdgpu_vm_wait_idle(&fpriv->vm, timeout);
2350                 if (r < 0)
2351                         return r;
2352
2353                 amdgpu_bo_unreserve(fpriv->vm.root.bo);
2354                 amdgpu_vmid_free_reserved(adev, &fpriv->vm, AMDGPU_GFXHUB_0);
2355                 break;
2356         default:
2357                 return -EINVAL;
2358         }
2359
2360         return 0;
2361 }
2362
2363 /**
2364  * amdgpu_vm_get_task_info - Extracts task info for a PASID.
2365  *
2366  * @adev: drm device pointer
2367  * @pasid: PASID identifier for VM
2368  * @task_info: task_info to fill.
2369  */
2370 void amdgpu_vm_get_task_info(struct amdgpu_device *adev, u32 pasid,
2371                          struct amdgpu_task_info *task_info)
2372 {
2373         struct amdgpu_vm *vm;
2374         unsigned long flags;
2375
2376         xa_lock_irqsave(&adev->vm_manager.pasids, flags);
2377
2378         vm = xa_load(&adev->vm_manager.pasids, pasid);
2379         if (vm)
2380                 *task_info = vm->task_info;
2381
2382         xa_unlock_irqrestore(&adev->vm_manager.pasids, flags);
2383 }
2384
2385 /**
2386  * amdgpu_vm_set_task_info - Sets VMs task info.
2387  *
2388  * @vm: vm for which to set the info
2389  */
2390 void amdgpu_vm_set_task_info(struct amdgpu_vm *vm)
2391 {
2392         if (vm->task_info.pid)
2393                 return;
2394
2395         vm->task_info.pid = current->pid;
2396         get_task_comm(vm->task_info.task_name, current);
2397
2398         if (current->group_leader->mm != current->mm)
2399                 return;
2400
2401         vm->task_info.tgid = current->group_leader->pid;
2402         get_task_comm(vm->task_info.process_name, current->group_leader);
2403 }
2404
2405 /**
2406  * amdgpu_vm_handle_fault - graceful handling of VM faults.
2407  * @adev: amdgpu device pointer
2408  * @pasid: PASID of the VM
2409  * @addr: Address of the fault
2410  * @write_fault: true is write fault, false is read fault
2411  *
2412  * Try to gracefully handle a VM fault. Return true if the fault was handled and
2413  * shouldn't be reported any more.
2414  */
2415 bool amdgpu_vm_handle_fault(struct amdgpu_device *adev, u32 pasid,
2416                             uint64_t addr, bool write_fault)
2417 {
2418         bool is_compute_context = false;
2419         struct amdgpu_bo *root;
2420         unsigned long irqflags;
2421         uint64_t value, flags;
2422         struct amdgpu_vm *vm;
2423         int r;
2424
2425         xa_lock_irqsave(&adev->vm_manager.pasids, irqflags);
2426         vm = xa_load(&adev->vm_manager.pasids, pasid);
2427         if (vm) {
2428                 root = amdgpu_bo_ref(vm->root.bo);
2429                 is_compute_context = vm->is_compute_context;
2430         } else {
2431                 root = NULL;
2432         }
2433         xa_unlock_irqrestore(&adev->vm_manager.pasids, irqflags);
2434
2435         if (!root)
2436                 return false;
2437
2438         addr /= AMDGPU_GPU_PAGE_SIZE;
2439
2440         if (is_compute_context &&
2441             !svm_range_restore_pages(adev, pasid, addr, write_fault)) {
2442                 amdgpu_bo_unref(&root);
2443                 return true;
2444         }
2445
2446         r = amdgpu_bo_reserve(root, true);
2447         if (r)
2448                 goto error_unref;
2449
2450         /* Double check that the VM still exists */
2451         xa_lock_irqsave(&adev->vm_manager.pasids, irqflags);
2452         vm = xa_load(&adev->vm_manager.pasids, pasid);
2453         if (vm && vm->root.bo != root)
2454                 vm = NULL;
2455         xa_unlock_irqrestore(&adev->vm_manager.pasids, irqflags);
2456         if (!vm)
2457                 goto error_unlock;
2458
2459         flags = AMDGPU_PTE_VALID | AMDGPU_PTE_SNOOPED |
2460                 AMDGPU_PTE_SYSTEM;
2461
2462         if (is_compute_context) {
2463                 /* Intentionally setting invalid PTE flag
2464                  * combination to force a no-retry-fault
2465                  */
2466                 flags = AMDGPU_PTE_EXECUTABLE | AMDGPU_PDE_PTE |
2467                         AMDGPU_PTE_TF;
2468                 value = 0;
2469         } else if (amdgpu_vm_fault_stop == AMDGPU_VM_FAULT_STOP_NEVER) {
2470                 /* Redirect the access to the dummy page */
2471                 value = adev->dummy_page_addr;
2472                 flags |= AMDGPU_PTE_EXECUTABLE | AMDGPU_PTE_READABLE |
2473                         AMDGPU_PTE_WRITEABLE;
2474
2475         } else {
2476                 /* Let the hw retry silently on the PTE */
2477                 value = 0;
2478         }
2479
2480         r = dma_resv_reserve_fences(root->tbo.base.resv, 1);
2481         if (r) {
2482                 pr_debug("failed %d to reserve fence slot\n", r);
2483                 goto error_unlock;
2484         }
2485
2486         r = amdgpu_vm_update_range(adev, vm, true, false, false, NULL, addr,
2487                                    addr, flags, value, 0, NULL, NULL, NULL);
2488         if (r)
2489                 goto error_unlock;
2490
2491         r = amdgpu_vm_update_pdes(adev, vm, true);
2492
2493 error_unlock:
2494         amdgpu_bo_unreserve(root);
2495         if (r < 0)
2496                 DRM_ERROR("Can't handle page fault (%d)\n", r);
2497
2498 error_unref:
2499         amdgpu_bo_unref(&root);
2500
2501         return false;
2502 }
2503
2504 #if defined(CONFIG_DEBUG_FS)
2505 /**
2506  * amdgpu_debugfs_vm_bo_info  - print BO info for the VM
2507  *
2508  * @vm: Requested VM for printing BO info
2509  * @m: debugfs file
2510  *
2511  * Print BO information in debugfs file for the VM
2512  */
2513 void amdgpu_debugfs_vm_bo_info(struct amdgpu_vm *vm, struct seq_file *m)
2514 {
2515         struct amdgpu_bo_va *bo_va, *tmp;
2516         u64 total_idle = 0;
2517         u64 total_evicted = 0;
2518         u64 total_relocated = 0;
2519         u64 total_moved = 0;
2520         u64 total_invalidated = 0;
2521         u64 total_done = 0;
2522         unsigned int total_idle_objs = 0;
2523         unsigned int total_evicted_objs = 0;
2524         unsigned int total_relocated_objs = 0;
2525         unsigned int total_moved_objs = 0;
2526         unsigned int total_invalidated_objs = 0;
2527         unsigned int total_done_objs = 0;
2528         unsigned int id = 0;
2529
2530         seq_puts(m, "\tIdle BOs:\n");
2531         list_for_each_entry_safe(bo_va, tmp, &vm->idle, base.vm_status) {
2532                 if (!bo_va->base.bo)
2533                         continue;
2534                 total_idle += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2535         }
2536         total_idle_objs = id;
2537         id = 0;
2538
2539         seq_puts(m, "\tEvicted BOs:\n");
2540         list_for_each_entry_safe(bo_va, tmp, &vm->evicted, base.vm_status) {
2541                 if (!bo_va->base.bo)
2542                         continue;
2543                 total_evicted += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2544         }
2545         total_evicted_objs = id;
2546         id = 0;
2547
2548         seq_puts(m, "\tRelocated BOs:\n");
2549         list_for_each_entry_safe(bo_va, tmp, &vm->relocated, base.vm_status) {
2550                 if (!bo_va->base.bo)
2551                         continue;
2552                 total_relocated += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2553         }
2554         total_relocated_objs = id;
2555         id = 0;
2556
2557         seq_puts(m, "\tMoved BOs:\n");
2558         list_for_each_entry_safe(bo_va, tmp, &vm->moved, base.vm_status) {
2559                 if (!bo_va->base.bo)
2560                         continue;
2561                 total_moved += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2562         }
2563         total_moved_objs = id;
2564         id = 0;
2565
2566         seq_puts(m, "\tInvalidated BOs:\n");
2567         spin_lock(&vm->invalidated_lock);
2568         list_for_each_entry_safe(bo_va, tmp, &vm->invalidated, base.vm_status) {
2569                 if (!bo_va->base.bo)
2570                         continue;
2571                 total_invalidated += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2572         }
2573         total_invalidated_objs = id;
2574         id = 0;
2575
2576         seq_puts(m, "\tDone BOs:\n");
2577         list_for_each_entry_safe(bo_va, tmp, &vm->done, base.vm_status) {
2578                 if (!bo_va->base.bo)
2579                         continue;
2580                 total_done += amdgpu_bo_print_info(id++, bo_va->base.bo, m);
2581         }
2582         spin_unlock(&vm->invalidated_lock);
2583         total_done_objs = id;
2584
2585         seq_printf(m, "\tTotal idle size:        %12lld\tobjs:\t%d\n", total_idle,
2586                    total_idle_objs);
2587         seq_printf(m, "\tTotal evicted size:     %12lld\tobjs:\t%d\n", total_evicted,
2588                    total_evicted_objs);
2589         seq_printf(m, "\tTotal relocated size:   %12lld\tobjs:\t%d\n", total_relocated,
2590                    total_relocated_objs);
2591         seq_printf(m, "\tTotal moved size:       %12lld\tobjs:\t%d\n", total_moved,
2592                    total_moved_objs);
2593         seq_printf(m, "\tTotal invalidated size: %12lld\tobjs:\t%d\n", total_invalidated,
2594                    total_invalidated_objs);
2595         seq_printf(m, "\tTotal done size:        %12lld\tobjs:\t%d\n", total_done,
2596                    total_done_objs);
2597 }
2598 #endif