drm/amdgpu: switch to cached fw flags for mem training cap
[linux-2.6-microblaze.git] / drivers / gpu / drm / amd / amdgpu / amdgpu_ttm.c
1 /*
2  * Copyright 2009 Jerome Glisse.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sub license, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
16  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
17  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19  * USE OR OTHER DEALINGS IN THE SOFTWARE.
20  *
21  * The above copyright notice and this permission notice (including the
22  * next paragraph) shall be included in all copies or substantial portions
23  * of the Software.
24  *
25  */
26 /*
27  * Authors:
28  *    Jerome Glisse <glisse@freedesktop.org>
29  *    Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
30  *    Dave Airlie
31  */
32
33 #include <linux/dma-mapping.h>
34 #include <linux/iommu.h>
35 #include <linux/pagemap.h>
36 #include <linux/sched/task.h>
37 #include <linux/sched/mm.h>
38 #include <linux/seq_file.h>
39 #include <linux/slab.h>
40 #include <linux/swap.h>
41 #include <linux/swiotlb.h>
42 #include <linux/dma-buf.h>
43 #include <linux/sizes.h>
44
45 #include <drm/ttm/ttm_bo_api.h>
46 #include <drm/ttm/ttm_bo_driver.h>
47 #include <drm/ttm/ttm_placement.h>
48
49 #include <drm/amdgpu_drm.h>
50
51 #include "amdgpu.h"
52 #include "amdgpu_object.h"
53 #include "amdgpu_trace.h"
54 #include "amdgpu_amdkfd.h"
55 #include "amdgpu_sdma.h"
56 #include "amdgpu_ras.h"
57 #include "amdgpu_atomfirmware.h"
58 #include "amdgpu_res_cursor.h"
59 #include "bif/bif_4_1_d.h"
60
61 #define AMDGPU_TTM_VRAM_MAX_DW_READ     (size_t)128
62
63 static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
64                                    struct ttm_tt *ttm,
65                                    struct ttm_resource *bo_mem);
66 static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
67                                       struct ttm_tt *ttm);
68
69 static int amdgpu_ttm_init_on_chip(struct amdgpu_device *adev,
70                                     unsigned int type,
71                                     uint64_t size_in_page)
72 {
73         return ttm_range_man_init(&adev->mman.bdev, type,
74                                   false, size_in_page);
75 }
76
77 /**
78  * amdgpu_evict_flags - Compute placement flags
79  *
80  * @bo: The buffer object to evict
81  * @placement: Possible destination(s) for evicted BO
82  *
83  * Fill in placement data when ttm_bo_evict() is called
84  */
85 static void amdgpu_evict_flags(struct ttm_buffer_object *bo,
86                                 struct ttm_placement *placement)
87 {
88         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
89         struct amdgpu_bo *abo;
90         static const struct ttm_place placements = {
91                 .fpfn = 0,
92                 .lpfn = 0,
93                 .mem_type = TTM_PL_SYSTEM,
94                 .flags = 0
95         };
96
97         /* Don't handle scatter gather BOs */
98         if (bo->type == ttm_bo_type_sg) {
99                 placement->num_placement = 0;
100                 placement->num_busy_placement = 0;
101                 return;
102         }
103
104         /* Object isn't an AMDGPU object so ignore */
105         if (!amdgpu_bo_is_amdgpu_bo(bo)) {
106                 placement->placement = &placements;
107                 placement->busy_placement = &placements;
108                 placement->num_placement = 1;
109                 placement->num_busy_placement = 1;
110                 return;
111         }
112
113         abo = ttm_to_amdgpu_bo(bo);
114         if (abo->flags & AMDGPU_AMDKFD_CREATE_SVM_BO) {
115                 struct dma_fence *fence;
116                 struct dma_resv *resv = &bo->base._resv;
117
118                 rcu_read_lock();
119                 fence = rcu_dereference(resv->fence_excl);
120                 if (fence && !fence->ops->signaled)
121                         dma_fence_enable_sw_signaling(fence);
122
123                 placement->num_placement = 0;
124                 placement->num_busy_placement = 0;
125                 rcu_read_unlock();
126                 return;
127         }
128         switch (bo->mem.mem_type) {
129         case AMDGPU_PL_GDS:
130         case AMDGPU_PL_GWS:
131         case AMDGPU_PL_OA:
132                 placement->num_placement = 0;
133                 placement->num_busy_placement = 0;
134                 return;
135
136         case TTM_PL_VRAM:
137                 if (!adev->mman.buffer_funcs_enabled) {
138                         /* Move to system memory */
139                         amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
140                 } else if (!amdgpu_gmc_vram_full_visible(&adev->gmc) &&
141                            !(abo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED) &&
142                            amdgpu_bo_in_cpu_visible_vram(abo)) {
143
144                         /* Try evicting to the CPU inaccessible part of VRAM
145                          * first, but only set GTT as busy placement, so this
146                          * BO will be evicted to GTT rather than causing other
147                          * BOs to be evicted from VRAM
148                          */
149                         amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
150                                                          AMDGPU_GEM_DOMAIN_GTT);
151                         abo->placements[0].fpfn = adev->gmc.visible_vram_size >> PAGE_SHIFT;
152                         abo->placements[0].lpfn = 0;
153                         abo->placement.busy_placement = &abo->placements[1];
154                         abo->placement.num_busy_placement = 1;
155                 } else {
156                         /* Move to GTT memory */
157                         amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_GTT);
158                 }
159                 break;
160         case TTM_PL_TT:
161         default:
162                 amdgpu_bo_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
163                 break;
164         }
165         *placement = abo->placement;
166 }
167
168 /**
169  * amdgpu_verify_access - Verify access for a mmap call
170  *
171  * @bo: The buffer object to map
172  * @filp: The file pointer from the process performing the mmap
173  *
174  * This is called by ttm_bo_mmap() to verify whether a process
175  * has the right to mmap a BO to their process space.
176  */
177 static int amdgpu_verify_access(struct ttm_buffer_object *bo, struct file *filp)
178 {
179         struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
180
181         if (amdgpu_ttm_tt_get_usermm(bo->ttm))
182                 return -EPERM;
183         return drm_vma_node_verify_access(&abo->tbo.base.vma_node,
184                                           filp->private_data);
185 }
186
187 /**
188  * amdgpu_ttm_map_buffer - Map memory into the GART windows
189  * @bo: buffer object to map
190  * @mem: memory object to map
191  * @mm_cur: range to map
192  * @num_pages: number of pages to map
193  * @window: which GART window to use
194  * @ring: DMA ring to use for the copy
195  * @tmz: if we should setup a TMZ enabled mapping
196  * @addr: resulting address inside the MC address space
197  *
198  * Setup one of the GART windows to access a specific piece of memory or return
199  * the physical address for local memory.
200  */
201 static int amdgpu_ttm_map_buffer(struct ttm_buffer_object *bo,
202                                  struct ttm_resource *mem,
203                                  struct amdgpu_res_cursor *mm_cur,
204                                  unsigned num_pages, unsigned window,
205                                  struct amdgpu_ring *ring, bool tmz,
206                                  uint64_t *addr)
207 {
208         struct amdgpu_device *adev = ring->adev;
209         struct amdgpu_job *job;
210         unsigned num_dw, num_bytes;
211         struct dma_fence *fence;
212         uint64_t src_addr, dst_addr;
213         void *cpu_addr;
214         uint64_t flags;
215         unsigned int i;
216         int r;
217
218         BUG_ON(adev->mman.buffer_funcs->copy_max_bytes <
219                AMDGPU_GTT_MAX_TRANSFER_SIZE * 8);
220
221         /* Map only what can't be accessed directly */
222         if (!tmz && mem->start != AMDGPU_BO_INVALID_OFFSET) {
223                 *addr = amdgpu_ttm_domain_start(adev, mem->mem_type) +
224                         mm_cur->start;
225                 return 0;
226         }
227
228         *addr = adev->gmc.gart_start;
229         *addr += (u64)window * AMDGPU_GTT_MAX_TRANSFER_SIZE *
230                 AMDGPU_GPU_PAGE_SIZE;
231         *addr += mm_cur->start & ~PAGE_MASK;
232
233         num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
234         num_bytes = num_pages * 8;
235
236         r = amdgpu_job_alloc_with_ib(adev, num_dw * 4 + num_bytes,
237                                      AMDGPU_IB_POOL_DELAYED, &job);
238         if (r)
239                 return r;
240
241         src_addr = num_dw * 4;
242         src_addr += job->ibs[0].gpu_addr;
243
244         dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
245         dst_addr += window * AMDGPU_GTT_MAX_TRANSFER_SIZE * 8;
246         amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
247                                 dst_addr, num_bytes, false);
248
249         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
250         WARN_ON(job->ibs[0].length_dw > num_dw);
251
252         flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, mem);
253         if (tmz)
254                 flags |= AMDGPU_PTE_TMZ;
255
256         cpu_addr = &job->ibs[0].ptr[num_dw];
257
258         if (mem->mem_type == TTM_PL_TT) {
259                 dma_addr_t *dma_addr;
260
261                 dma_addr = &bo->ttm->dma_address[mm_cur->start >> PAGE_SHIFT];
262                 r = amdgpu_gart_map(adev, 0, num_pages, dma_addr, flags,
263                                     cpu_addr);
264                 if (r)
265                         goto error_free;
266         } else {
267                 dma_addr_t dma_address;
268
269                 dma_address = mm_cur->start;
270                 dma_address += adev->vm_manager.vram_base_offset;
271
272                 for (i = 0; i < num_pages; ++i) {
273                         r = amdgpu_gart_map(adev, i << PAGE_SHIFT, 1,
274                                             &dma_address, flags, cpu_addr);
275                         if (r)
276                                 goto error_free;
277
278                         dma_address += PAGE_SIZE;
279                 }
280         }
281
282         r = amdgpu_job_submit(job, &adev->mman.entity,
283                               AMDGPU_FENCE_OWNER_UNDEFINED, &fence);
284         if (r)
285                 goto error_free;
286
287         dma_fence_put(fence);
288
289         return r;
290
291 error_free:
292         amdgpu_job_free(job);
293         return r;
294 }
295
296 /**
297  * amdgpu_ttm_copy_mem_to_mem - Helper function for copy
298  * @adev: amdgpu device
299  * @src: buffer/address where to read from
300  * @dst: buffer/address where to write to
301  * @size: number of bytes to copy
302  * @tmz: if a secure copy should be used
303  * @resv: resv object to sync to
304  * @f: Returns the last fence if multiple jobs are submitted.
305  *
306  * The function copies @size bytes from {src->mem + src->offset} to
307  * {dst->mem + dst->offset}. src->bo and dst->bo could be same BO for a
308  * move and different for a BO to BO copy.
309  *
310  */
311 int amdgpu_ttm_copy_mem_to_mem(struct amdgpu_device *adev,
312                                const struct amdgpu_copy_mem *src,
313                                const struct amdgpu_copy_mem *dst,
314                                uint64_t size, bool tmz,
315                                struct dma_resv *resv,
316                                struct dma_fence **f)
317 {
318         const uint32_t GTT_MAX_BYTES = (AMDGPU_GTT_MAX_TRANSFER_SIZE *
319                                         AMDGPU_GPU_PAGE_SIZE);
320
321         struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
322         struct amdgpu_res_cursor src_mm, dst_mm;
323         struct dma_fence *fence = NULL;
324         int r = 0;
325
326         if (!adev->mman.buffer_funcs_enabled) {
327                 DRM_ERROR("Trying to move memory with ring turned off.\n");
328                 return -EINVAL;
329         }
330
331         amdgpu_res_first(src->mem, src->offset, size, &src_mm);
332         amdgpu_res_first(dst->mem, dst->offset, size, &dst_mm);
333
334         mutex_lock(&adev->mman.gtt_window_lock);
335         while (src_mm.remaining) {
336                 uint32_t src_page_offset = src_mm.start & ~PAGE_MASK;
337                 uint32_t dst_page_offset = dst_mm.start & ~PAGE_MASK;
338                 struct dma_fence *next;
339                 uint32_t cur_size;
340                 uint64_t from, to;
341
342                 /* Copy size cannot exceed GTT_MAX_BYTES. So if src or dst
343                  * begins at an offset, then adjust the size accordingly
344                  */
345                 cur_size = max(src_page_offset, dst_page_offset);
346                 cur_size = min(min3(src_mm.size, dst_mm.size, size),
347                                (uint64_t)(GTT_MAX_BYTES - cur_size));
348
349                 /* Map src to window 0 and dst to window 1. */
350                 r = amdgpu_ttm_map_buffer(src->bo, src->mem, &src_mm,
351                                           PFN_UP(cur_size + src_page_offset),
352                                           0, ring, tmz, &from);
353                 if (r)
354                         goto error;
355
356                 r = amdgpu_ttm_map_buffer(dst->bo, dst->mem, &dst_mm,
357                                           PFN_UP(cur_size + dst_page_offset),
358                                           1, ring, tmz, &to);
359                 if (r)
360                         goto error;
361
362                 r = amdgpu_copy_buffer(ring, from, to, cur_size,
363                                        resv, &next, false, true, tmz);
364                 if (r)
365                         goto error;
366
367                 dma_fence_put(fence);
368                 fence = next;
369
370                 amdgpu_res_next(&src_mm, cur_size);
371                 amdgpu_res_next(&dst_mm, cur_size);
372         }
373 error:
374         mutex_unlock(&adev->mman.gtt_window_lock);
375         if (f)
376                 *f = dma_fence_get(fence);
377         dma_fence_put(fence);
378         return r;
379 }
380
381 /*
382  * amdgpu_move_blit - Copy an entire buffer to another buffer
383  *
384  * This is a helper called by amdgpu_bo_move() and amdgpu_move_vram_ram() to
385  * help move buffers to and from VRAM.
386  */
387 static int amdgpu_move_blit(struct ttm_buffer_object *bo,
388                             bool evict,
389                             struct ttm_resource *new_mem,
390                             struct ttm_resource *old_mem)
391 {
392         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
393         struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
394         struct amdgpu_copy_mem src, dst;
395         struct dma_fence *fence = NULL;
396         int r;
397
398         src.bo = bo;
399         dst.bo = bo;
400         src.mem = old_mem;
401         dst.mem = new_mem;
402         src.offset = 0;
403         dst.offset = 0;
404
405         r = amdgpu_ttm_copy_mem_to_mem(adev, &src, &dst,
406                                        new_mem->num_pages << PAGE_SHIFT,
407                                        amdgpu_bo_encrypted(abo),
408                                        bo->base.resv, &fence);
409         if (r)
410                 goto error;
411
412         /* clear the space being freed */
413         if (old_mem->mem_type == TTM_PL_VRAM &&
414             (abo->flags & AMDGPU_GEM_CREATE_VRAM_WIPE_ON_RELEASE)) {
415                 struct dma_fence *wipe_fence = NULL;
416
417                 r = amdgpu_fill_buffer(ttm_to_amdgpu_bo(bo), AMDGPU_POISON,
418                                        NULL, &wipe_fence);
419                 if (r) {
420                         goto error;
421                 } else if (wipe_fence) {
422                         dma_fence_put(fence);
423                         fence = wipe_fence;
424                 }
425         }
426
427         /* Always block for VM page tables before committing the new location */
428         if (bo->type == ttm_bo_type_kernel)
429                 r = ttm_bo_move_accel_cleanup(bo, fence, true, false, new_mem);
430         else
431                 r = ttm_bo_move_accel_cleanup(bo, fence, evict, true, new_mem);
432         dma_fence_put(fence);
433         return r;
434
435 error:
436         if (fence)
437                 dma_fence_wait(fence, false);
438         dma_fence_put(fence);
439         return r;
440 }
441
442 /*
443  * amdgpu_mem_visible - Check that memory can be accessed by ttm_bo_move_memcpy
444  *
445  * Called by amdgpu_bo_move()
446  */
447 static bool amdgpu_mem_visible(struct amdgpu_device *adev,
448                                struct ttm_resource *mem)
449 {
450         uint64_t mem_size = (u64)mem->num_pages << PAGE_SHIFT;
451         struct amdgpu_res_cursor cursor;
452
453         if (mem->mem_type == TTM_PL_SYSTEM ||
454             mem->mem_type == TTM_PL_TT)
455                 return true;
456         if (mem->mem_type != TTM_PL_VRAM)
457                 return false;
458
459         amdgpu_res_first(mem, 0, mem_size, &cursor);
460
461         /* ttm_resource_ioremap only supports contiguous memory */
462         if (cursor.size != mem_size)
463                 return false;
464
465         return cursor.start + cursor.size <= adev->gmc.visible_vram_size;
466 }
467
468 /*
469  * amdgpu_bo_move - Move a buffer object to a new memory location
470  *
471  * Called by ttm_bo_handle_move_mem()
472  */
473 static int amdgpu_bo_move(struct ttm_buffer_object *bo, bool evict,
474                           struct ttm_operation_ctx *ctx,
475                           struct ttm_resource *new_mem,
476                           struct ttm_place *hop)
477 {
478         struct amdgpu_device *adev;
479         struct amdgpu_bo *abo;
480         struct ttm_resource *old_mem = &bo->mem;
481         int r;
482
483         if (new_mem->mem_type == TTM_PL_TT) {
484                 r = amdgpu_ttm_backend_bind(bo->bdev, bo->ttm, new_mem);
485                 if (r)
486                         return r;
487         }
488
489         /* Can't move a pinned BO */
490         abo = ttm_to_amdgpu_bo(bo);
491         if (WARN_ON_ONCE(abo->tbo.pin_count > 0))
492                 return -EINVAL;
493
494         adev = amdgpu_ttm_adev(bo->bdev);
495
496         if (old_mem->mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
497                 ttm_bo_move_null(bo, new_mem);
498                 goto out;
499         }
500         if (old_mem->mem_type == TTM_PL_SYSTEM &&
501             new_mem->mem_type == TTM_PL_TT) {
502                 ttm_bo_move_null(bo, new_mem);
503                 goto out;
504         }
505         if (old_mem->mem_type == TTM_PL_TT &&
506             new_mem->mem_type == TTM_PL_SYSTEM) {
507                 r = ttm_bo_wait_ctx(bo, ctx);
508                 if (r)
509                         return r;
510
511                 amdgpu_ttm_backend_unbind(bo->bdev, bo->ttm);
512                 ttm_resource_free(bo, &bo->mem);
513                 ttm_bo_assign_mem(bo, new_mem);
514                 goto out;
515         }
516
517         if (old_mem->mem_type == AMDGPU_PL_GDS ||
518             old_mem->mem_type == AMDGPU_PL_GWS ||
519             old_mem->mem_type == AMDGPU_PL_OA ||
520             new_mem->mem_type == AMDGPU_PL_GDS ||
521             new_mem->mem_type == AMDGPU_PL_GWS ||
522             new_mem->mem_type == AMDGPU_PL_OA) {
523                 /* Nothing to save here */
524                 ttm_bo_move_null(bo, new_mem);
525                 goto out;
526         }
527
528         if (adev->mman.buffer_funcs_enabled) {
529                 if (((old_mem->mem_type == TTM_PL_SYSTEM &&
530                       new_mem->mem_type == TTM_PL_VRAM) ||
531                      (old_mem->mem_type == TTM_PL_VRAM &&
532                       new_mem->mem_type == TTM_PL_SYSTEM))) {
533                         hop->fpfn = 0;
534                         hop->lpfn = 0;
535                         hop->mem_type = TTM_PL_TT;
536                         hop->flags = 0;
537                         return -EMULTIHOP;
538                 }
539
540                 r = amdgpu_move_blit(bo, evict, new_mem, old_mem);
541         } else {
542                 r = -ENODEV;
543         }
544
545         if (r) {
546                 /* Check that all memory is CPU accessible */
547                 if (!amdgpu_mem_visible(adev, old_mem) ||
548                     !amdgpu_mem_visible(adev, new_mem)) {
549                         pr_err("Move buffer fallback to memcpy unavailable\n");
550                         return r;
551                 }
552
553                 r = ttm_bo_move_memcpy(bo, ctx, new_mem);
554                 if (r)
555                         return r;
556         }
557
558         if (bo->type == ttm_bo_type_device &&
559             new_mem->mem_type == TTM_PL_VRAM &&
560             old_mem->mem_type != TTM_PL_VRAM) {
561                 /* amdgpu_bo_fault_reserve_notify will re-set this if the CPU
562                  * accesses the BO after it's moved.
563                  */
564                 abo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
565         }
566
567 out:
568         /* update statistics */
569         atomic64_add(bo->base.size, &adev->num_bytes_moved);
570         amdgpu_bo_move_notify(bo, evict, new_mem);
571         return 0;
572 }
573
574 /*
575  * amdgpu_ttm_io_mem_reserve - Reserve a block of memory during a fault
576  *
577  * Called by ttm_mem_io_reserve() ultimately via ttm_bo_vm_fault()
578  */
579 static int amdgpu_ttm_io_mem_reserve(struct ttm_device *bdev, struct ttm_resource *mem)
580 {
581         struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
582         struct drm_mm_node *mm_node = mem->mm_node;
583         size_t bus_size = (size_t)mem->num_pages << PAGE_SHIFT;
584
585         switch (mem->mem_type) {
586         case TTM_PL_SYSTEM:
587                 /* system memory */
588                 return 0;
589         case TTM_PL_TT:
590                 break;
591         case TTM_PL_VRAM:
592                 mem->bus.offset = mem->start << PAGE_SHIFT;
593                 /* check if it's visible */
594                 if ((mem->bus.offset + bus_size) > adev->gmc.visible_vram_size)
595                         return -EINVAL;
596                 /* Only physically contiguous buffers apply. In a contiguous
597                  * buffer, size of the first mm_node would match the number of
598                  * pages in ttm_resource.
599                  */
600                 if (adev->mman.aper_base_kaddr &&
601                     (mm_node->size == mem->num_pages))
602                         mem->bus.addr = (u8 *)adev->mman.aper_base_kaddr +
603                                         mem->bus.offset;
604
605                 mem->bus.offset += adev->gmc.aper_base;
606                 mem->bus.is_iomem = true;
607                 if (adev->gmc.xgmi.connected_to_cpu)
608                         mem->bus.caching = ttm_cached;
609                 else
610                         mem->bus.caching = ttm_write_combined;
611                 break;
612         default:
613                 return -EINVAL;
614         }
615         return 0;
616 }
617
618 static unsigned long amdgpu_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
619                                            unsigned long page_offset)
620 {
621         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
622         struct amdgpu_res_cursor cursor;
623
624         amdgpu_res_first(&bo->mem, (u64)page_offset << PAGE_SHIFT, 0, &cursor);
625         return (adev->gmc.aper_base + cursor.start) >> PAGE_SHIFT;
626 }
627
628 /**
629  * amdgpu_ttm_domain_start - Returns GPU start address
630  * @adev: amdgpu device object
631  * @type: type of the memory
632  *
633  * Returns:
634  * GPU start address of a memory domain
635  */
636
637 uint64_t amdgpu_ttm_domain_start(struct amdgpu_device *adev, uint32_t type)
638 {
639         switch (type) {
640         case TTM_PL_TT:
641                 return adev->gmc.gart_start;
642         case TTM_PL_VRAM:
643                 return adev->gmc.vram_start;
644         }
645
646         return 0;
647 }
648
649 /*
650  * TTM backend functions.
651  */
652 struct amdgpu_ttm_tt {
653         struct ttm_tt   ttm;
654         struct drm_gem_object   *gobj;
655         u64                     offset;
656         uint64_t                userptr;
657         struct task_struct      *usertask;
658         uint32_t                userflags;
659         bool                    bound;
660 #if IS_ENABLED(CONFIG_DRM_AMDGPU_USERPTR)
661         struct hmm_range        *range;
662 #endif
663 };
664
665 #ifdef CONFIG_DRM_AMDGPU_USERPTR
666 /*
667  * amdgpu_ttm_tt_get_user_pages - get device accessible pages that back user
668  * memory and start HMM tracking CPU page table update
669  *
670  * Calling function must call amdgpu_ttm_tt_userptr_range_done() once and only
671  * once afterwards to stop HMM tracking
672  */
673 int amdgpu_ttm_tt_get_user_pages(struct amdgpu_bo *bo, struct page **pages)
674 {
675         struct ttm_tt *ttm = bo->tbo.ttm;
676         struct amdgpu_ttm_tt *gtt = (void *)ttm;
677         unsigned long start = gtt->userptr;
678         struct vm_area_struct *vma;
679         struct mm_struct *mm;
680         bool readonly;
681         int r = 0;
682
683         mm = bo->notifier.mm;
684         if (unlikely(!mm)) {
685                 DRM_DEBUG_DRIVER("BO is not registered?\n");
686                 return -EFAULT;
687         }
688
689         /* Another get_user_pages is running at the same time?? */
690         if (WARN_ON(gtt->range))
691                 return -EFAULT;
692
693         if (!mmget_not_zero(mm)) /* Happens during process shutdown */
694                 return -ESRCH;
695
696         mmap_read_lock(mm);
697         vma = find_vma(mm, start);
698         mmap_read_unlock(mm);
699         if (unlikely(!vma || start < vma->vm_start)) {
700                 r = -EFAULT;
701                 goto out_putmm;
702         }
703         if (unlikely((gtt->userflags & AMDGPU_GEM_USERPTR_ANONONLY) &&
704                 vma->vm_file)) {
705                 r = -EPERM;
706                 goto out_putmm;
707         }
708
709         readonly = amdgpu_ttm_tt_is_readonly(ttm);
710         r = amdgpu_hmm_range_get_pages(&bo->notifier, mm, pages, start,
711                                        ttm->num_pages, &gtt->range, readonly,
712                                        false);
713 out_putmm:
714         mmput(mm);
715
716         return r;
717 }
718
719 /*
720  * amdgpu_ttm_tt_userptr_range_done - stop HMM track the CPU page table change
721  * Check if the pages backing this ttm range have been invalidated
722  *
723  * Returns: true if pages are still valid
724  */
725 bool amdgpu_ttm_tt_get_user_pages_done(struct ttm_tt *ttm)
726 {
727         struct amdgpu_ttm_tt *gtt = (void *)ttm;
728         bool r = false;
729
730         if (!gtt || !gtt->userptr)
731                 return false;
732
733         DRM_DEBUG_DRIVER("user_pages_done 0x%llx pages 0x%x\n",
734                 gtt->userptr, ttm->num_pages);
735
736         WARN_ONCE(!gtt->range || !gtt->range->hmm_pfns,
737                 "No user pages to check\n");
738
739         if (gtt->range) {
740                 /*
741                  * FIXME: Must always hold notifier_lock for this, and must
742                  * not ignore the return code.
743                  */
744                 r = amdgpu_hmm_range_get_pages_done(gtt->range);
745                 gtt->range = NULL;
746         }
747
748         return !r;
749 }
750 #endif
751
752 /*
753  * amdgpu_ttm_tt_set_user_pages - Copy pages in, putting old pages as necessary.
754  *
755  * Called by amdgpu_cs_list_validate(). This creates the page list
756  * that backs user memory and will ultimately be mapped into the device
757  * address space.
758  */
759 void amdgpu_ttm_tt_set_user_pages(struct ttm_tt *ttm, struct page **pages)
760 {
761         unsigned long i;
762
763         for (i = 0; i < ttm->num_pages; ++i)
764                 ttm->pages[i] = pages ? pages[i] : NULL;
765 }
766
767 /*
768  * amdgpu_ttm_tt_pin_userptr - prepare the sg table with the user pages
769  *
770  * Called by amdgpu_ttm_backend_bind()
771  **/
772 static int amdgpu_ttm_tt_pin_userptr(struct ttm_device *bdev,
773                                      struct ttm_tt *ttm)
774 {
775         struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
776         struct amdgpu_ttm_tt *gtt = (void *)ttm;
777         int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
778         enum dma_data_direction direction = write ?
779                 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
780         int r;
781
782         /* Allocate an SG array and squash pages into it */
783         r = sg_alloc_table_from_pages(ttm->sg, ttm->pages, ttm->num_pages, 0,
784                                       (u64)ttm->num_pages << PAGE_SHIFT,
785                                       GFP_KERNEL);
786         if (r)
787                 goto release_sg;
788
789         /* Map SG to device */
790         r = dma_map_sgtable(adev->dev, ttm->sg, direction, 0);
791         if (r)
792                 goto release_sg;
793
794         /* convert SG to linear array of pages and dma addresses */
795         drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
796                                        ttm->num_pages);
797
798         return 0;
799
800 release_sg:
801         kfree(ttm->sg);
802         ttm->sg = NULL;
803         return r;
804 }
805
806 /*
807  * amdgpu_ttm_tt_unpin_userptr - Unpin and unmap userptr pages
808  */
809 static void amdgpu_ttm_tt_unpin_userptr(struct ttm_device *bdev,
810                                         struct ttm_tt *ttm)
811 {
812         struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
813         struct amdgpu_ttm_tt *gtt = (void *)ttm;
814         int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
815         enum dma_data_direction direction = write ?
816                 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
817
818         /* double check that we don't free the table twice */
819         if (!ttm->sg || !ttm->sg->sgl)
820                 return;
821
822         /* unmap the pages mapped to the device */
823         dma_unmap_sgtable(adev->dev, ttm->sg, direction, 0);
824         sg_free_table(ttm->sg);
825
826 #if IS_ENABLED(CONFIG_DRM_AMDGPU_USERPTR)
827         if (gtt->range) {
828                 unsigned long i;
829
830                 for (i = 0; i < ttm->num_pages; i++) {
831                         if (ttm->pages[i] !=
832                             hmm_pfn_to_page(gtt->range->hmm_pfns[i]))
833                                 break;
834                 }
835
836                 WARN((i == ttm->num_pages), "Missing get_user_page_done\n");
837         }
838 #endif
839 }
840
841 static int amdgpu_ttm_gart_bind(struct amdgpu_device *adev,
842                                 struct ttm_buffer_object *tbo,
843                                 uint64_t flags)
844 {
845         struct amdgpu_bo *abo = ttm_to_amdgpu_bo(tbo);
846         struct ttm_tt *ttm = tbo->ttm;
847         struct amdgpu_ttm_tt *gtt = (void *)ttm;
848         int r;
849
850         if (amdgpu_bo_encrypted(abo))
851                 flags |= AMDGPU_PTE_TMZ;
852
853         if (abo->flags & AMDGPU_GEM_CREATE_CP_MQD_GFX9) {
854                 uint64_t page_idx = 1;
855
856                 r = amdgpu_gart_bind(adev, gtt->offset, page_idx,
857                                 ttm->pages, gtt->ttm.dma_address, flags);
858                 if (r)
859                         goto gart_bind_fail;
860
861                 /* The memory type of the first page defaults to UC. Now
862                  * modify the memory type to NC from the second page of
863                  * the BO onward.
864                  */
865                 flags &= ~AMDGPU_PTE_MTYPE_VG10_MASK;
866                 flags |= AMDGPU_PTE_MTYPE_VG10(AMDGPU_MTYPE_NC);
867
868                 r = amdgpu_gart_bind(adev,
869                                 gtt->offset + (page_idx << PAGE_SHIFT),
870                                 ttm->num_pages - page_idx,
871                                 &ttm->pages[page_idx],
872                                 &(gtt->ttm.dma_address[page_idx]), flags);
873         } else {
874                 r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
875                                      ttm->pages, gtt->ttm.dma_address, flags);
876         }
877
878 gart_bind_fail:
879         if (r)
880                 DRM_ERROR("failed to bind %u pages at 0x%08llX\n",
881                           ttm->num_pages, gtt->offset);
882
883         return r;
884 }
885
886 /*
887  * amdgpu_ttm_backend_bind - Bind GTT memory
888  *
889  * Called by ttm_tt_bind() on behalf of ttm_bo_handle_move_mem().
890  * This handles binding GTT memory to the device address space.
891  */
892 static int amdgpu_ttm_backend_bind(struct ttm_device *bdev,
893                                    struct ttm_tt *ttm,
894                                    struct ttm_resource *bo_mem)
895 {
896         struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
897         struct amdgpu_ttm_tt *gtt = (void*)ttm;
898         uint64_t flags;
899         int r = 0;
900
901         if (!bo_mem)
902                 return -EINVAL;
903
904         if (gtt->bound)
905                 return 0;
906
907         if (gtt->userptr) {
908                 r = amdgpu_ttm_tt_pin_userptr(bdev, ttm);
909                 if (r) {
910                         DRM_ERROR("failed to pin userptr\n");
911                         return r;
912                 }
913         }
914         if (!ttm->num_pages) {
915                 WARN(1, "nothing to bind %u pages for mreg %p back %p!\n",
916                      ttm->num_pages, bo_mem, ttm);
917         }
918
919         if (bo_mem->mem_type == AMDGPU_PL_GDS ||
920             bo_mem->mem_type == AMDGPU_PL_GWS ||
921             bo_mem->mem_type == AMDGPU_PL_OA)
922                 return -EINVAL;
923
924         if (!amdgpu_gtt_mgr_has_gart_addr(bo_mem)) {
925                 gtt->offset = AMDGPU_BO_INVALID_OFFSET;
926                 return 0;
927         }
928
929         /* compute PTE flags relevant to this BO memory */
930         flags = amdgpu_ttm_tt_pte_flags(adev, ttm, bo_mem);
931
932         /* bind pages into GART page tables */
933         gtt->offset = (u64)bo_mem->start << PAGE_SHIFT;
934         r = amdgpu_gart_bind(adev, gtt->offset, ttm->num_pages,
935                 ttm->pages, gtt->ttm.dma_address, flags);
936
937         if (r)
938                 DRM_ERROR("failed to bind %u pages at 0x%08llX\n",
939                           ttm->num_pages, gtt->offset);
940         gtt->bound = true;
941         return r;
942 }
943
944 /*
945  * amdgpu_ttm_alloc_gart - Make sure buffer object is accessible either
946  * through AGP or GART aperture.
947  *
948  * If bo is accessible through AGP aperture, then use AGP aperture
949  * to access bo; otherwise allocate logical space in GART aperture
950  * and map bo to GART aperture.
951  */
952 int amdgpu_ttm_alloc_gart(struct ttm_buffer_object *bo)
953 {
954         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
955         struct ttm_operation_ctx ctx = { false, false };
956         struct amdgpu_ttm_tt *gtt = (void *)bo->ttm;
957         struct ttm_resource tmp;
958         struct ttm_placement placement;
959         struct ttm_place placements;
960         uint64_t addr, flags;
961         int r;
962
963         if (bo->mem.start != AMDGPU_BO_INVALID_OFFSET)
964                 return 0;
965
966         addr = amdgpu_gmc_agp_addr(bo);
967         if (addr != AMDGPU_BO_INVALID_OFFSET) {
968                 bo->mem.start = addr >> PAGE_SHIFT;
969         } else {
970
971                 /* allocate GART space */
972                 tmp = bo->mem;
973                 tmp.mm_node = NULL;
974                 placement.num_placement = 1;
975                 placement.placement = &placements;
976                 placement.num_busy_placement = 1;
977                 placement.busy_placement = &placements;
978                 placements.fpfn = 0;
979                 placements.lpfn = adev->gmc.gart_size >> PAGE_SHIFT;
980                 placements.mem_type = TTM_PL_TT;
981                 placements.flags = bo->mem.placement;
982
983                 r = ttm_bo_mem_space(bo, &placement, &tmp, &ctx);
984                 if (unlikely(r))
985                         return r;
986
987                 /* compute PTE flags for this buffer object */
988                 flags = amdgpu_ttm_tt_pte_flags(adev, bo->ttm, &tmp);
989
990                 /* Bind pages */
991                 gtt->offset = (u64)tmp.start << PAGE_SHIFT;
992                 r = amdgpu_ttm_gart_bind(adev, bo, flags);
993                 if (unlikely(r)) {
994                         ttm_resource_free(bo, &tmp);
995                         return r;
996                 }
997
998                 ttm_resource_free(bo, &bo->mem);
999                 bo->mem = tmp;
1000         }
1001
1002         return 0;
1003 }
1004
1005 /*
1006  * amdgpu_ttm_recover_gart - Rebind GTT pages
1007  *
1008  * Called by amdgpu_gtt_mgr_recover() from amdgpu_device_reset() to
1009  * rebind GTT pages during a GPU reset.
1010  */
1011 int amdgpu_ttm_recover_gart(struct ttm_buffer_object *tbo)
1012 {
1013         struct amdgpu_device *adev = amdgpu_ttm_adev(tbo->bdev);
1014         uint64_t flags;
1015         int r;
1016
1017         if (!tbo->ttm)
1018                 return 0;
1019
1020         flags = amdgpu_ttm_tt_pte_flags(adev, tbo->ttm, &tbo->mem);
1021         r = amdgpu_ttm_gart_bind(adev, tbo, flags);
1022
1023         return r;
1024 }
1025
1026 /*
1027  * amdgpu_ttm_backend_unbind - Unbind GTT mapped pages
1028  *
1029  * Called by ttm_tt_unbind() on behalf of ttm_bo_move_ttm() and
1030  * ttm_tt_destroy().
1031  */
1032 static void amdgpu_ttm_backend_unbind(struct ttm_device *bdev,
1033                                       struct ttm_tt *ttm)
1034 {
1035         struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1036         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1037         int r;
1038
1039         /* if the pages have userptr pinning then clear that first */
1040         if (gtt->userptr)
1041                 amdgpu_ttm_tt_unpin_userptr(bdev, ttm);
1042
1043         if (!gtt->bound)
1044                 return;
1045
1046         if (gtt->offset == AMDGPU_BO_INVALID_OFFSET)
1047                 return;
1048
1049         /* unbind shouldn't be done for GDS/GWS/OA in ttm_bo_clean_mm */
1050         r = amdgpu_gart_unbind(adev, gtt->offset, ttm->num_pages);
1051         if (r)
1052                 DRM_ERROR("failed to unbind %u pages at 0x%08llX\n",
1053                           gtt->ttm.num_pages, gtt->offset);
1054         gtt->bound = false;
1055 }
1056
1057 static void amdgpu_ttm_backend_destroy(struct ttm_device *bdev,
1058                                        struct ttm_tt *ttm)
1059 {
1060         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1061
1062         amdgpu_ttm_backend_unbind(bdev, ttm);
1063         ttm_tt_destroy_common(bdev, ttm);
1064         if (gtt->usertask)
1065                 put_task_struct(gtt->usertask);
1066
1067         ttm_tt_fini(&gtt->ttm);
1068         kfree(gtt);
1069 }
1070
1071 /**
1072  * amdgpu_ttm_tt_create - Create a ttm_tt object for a given BO
1073  *
1074  * @bo: The buffer object to create a GTT ttm_tt object around
1075  * @page_flags: Page flags to be added to the ttm_tt object
1076  *
1077  * Called by ttm_tt_create().
1078  */
1079 static struct ttm_tt *amdgpu_ttm_tt_create(struct ttm_buffer_object *bo,
1080                                            uint32_t page_flags)
1081 {
1082         struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1083         struct amdgpu_ttm_tt *gtt;
1084         enum ttm_caching caching;
1085
1086         gtt = kzalloc(sizeof(struct amdgpu_ttm_tt), GFP_KERNEL);
1087         if (gtt == NULL) {
1088                 return NULL;
1089         }
1090         gtt->gobj = &bo->base;
1091
1092         if (abo->flags & AMDGPU_GEM_CREATE_CPU_GTT_USWC)
1093                 caching = ttm_write_combined;
1094         else
1095                 caching = ttm_cached;
1096
1097         /* allocate space for the uninitialized page entries */
1098         if (ttm_sg_tt_init(&gtt->ttm, bo, page_flags, caching)) {
1099                 kfree(gtt);
1100                 return NULL;
1101         }
1102         return &gtt->ttm;
1103 }
1104
1105 /*
1106  * amdgpu_ttm_tt_populate - Map GTT pages visible to the device
1107  *
1108  * Map the pages of a ttm_tt object to an address space visible
1109  * to the underlying device.
1110  */
1111 static int amdgpu_ttm_tt_populate(struct ttm_device *bdev,
1112                                   struct ttm_tt *ttm,
1113                                   struct ttm_operation_ctx *ctx)
1114 {
1115         struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
1116         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1117
1118         /* user pages are bound by amdgpu_ttm_tt_pin_userptr() */
1119         if (gtt && gtt->userptr) {
1120                 ttm->sg = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
1121                 if (!ttm->sg)
1122                         return -ENOMEM;
1123
1124                 ttm->page_flags |= TTM_PAGE_FLAG_SG;
1125                 return 0;
1126         }
1127
1128         if (ttm->page_flags & TTM_PAGE_FLAG_SG) {
1129                 if (!ttm->sg) {
1130                         struct dma_buf_attachment *attach;
1131                         struct sg_table *sgt;
1132
1133                         attach = gtt->gobj->import_attach;
1134                         sgt = dma_buf_map_attachment(attach, DMA_BIDIRECTIONAL);
1135                         if (IS_ERR(sgt))
1136                                 return PTR_ERR(sgt);
1137
1138                         ttm->sg = sgt;
1139                 }
1140
1141                 drm_prime_sg_to_dma_addr_array(ttm->sg, gtt->ttm.dma_address,
1142                                                ttm->num_pages);
1143                 return 0;
1144         }
1145
1146         return ttm_pool_alloc(&adev->mman.bdev.pool, ttm, ctx);
1147 }
1148
1149 /*
1150  * amdgpu_ttm_tt_unpopulate - unmap GTT pages and unpopulate page arrays
1151  *
1152  * Unmaps pages of a ttm_tt object from the device address space and
1153  * unpopulates the page array backing it.
1154  */
1155 static void amdgpu_ttm_tt_unpopulate(struct ttm_device *bdev,
1156                                      struct ttm_tt *ttm)
1157 {
1158         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1159         struct amdgpu_device *adev;
1160
1161         if (gtt && gtt->userptr) {
1162                 amdgpu_ttm_tt_set_user_pages(ttm, NULL);
1163                 kfree(ttm->sg);
1164                 ttm->page_flags &= ~TTM_PAGE_FLAG_SG;
1165                 return;
1166         }
1167
1168         if (ttm->sg && gtt->gobj->import_attach) {
1169                 struct dma_buf_attachment *attach;
1170
1171                 attach = gtt->gobj->import_attach;
1172                 dma_buf_unmap_attachment(attach, ttm->sg, DMA_BIDIRECTIONAL);
1173                 ttm->sg = NULL;
1174                 return;
1175         }
1176
1177         if (ttm->page_flags & TTM_PAGE_FLAG_SG)
1178                 return;
1179
1180         adev = amdgpu_ttm_adev(bdev);
1181         return ttm_pool_free(&adev->mman.bdev.pool, ttm);
1182 }
1183
1184 /**
1185  * amdgpu_ttm_tt_set_userptr - Initialize userptr GTT ttm_tt for the current
1186  * task
1187  *
1188  * @bo: The ttm_buffer_object to bind this userptr to
1189  * @addr:  The address in the current tasks VM space to use
1190  * @flags: Requirements of userptr object.
1191  *
1192  * Called by amdgpu_gem_userptr_ioctl() to bind userptr pages
1193  * to current task
1194  */
1195 int amdgpu_ttm_tt_set_userptr(struct ttm_buffer_object *bo,
1196                               uint64_t addr, uint32_t flags)
1197 {
1198         struct amdgpu_ttm_tt *gtt;
1199
1200         if (!bo->ttm) {
1201                 /* TODO: We want a separate TTM object type for userptrs */
1202                 bo->ttm = amdgpu_ttm_tt_create(bo, 0);
1203                 if (bo->ttm == NULL)
1204                         return -ENOMEM;
1205         }
1206
1207         gtt = (void *)bo->ttm;
1208         gtt->userptr = addr;
1209         gtt->userflags = flags;
1210
1211         if (gtt->usertask)
1212                 put_task_struct(gtt->usertask);
1213         gtt->usertask = current->group_leader;
1214         get_task_struct(gtt->usertask);
1215
1216         return 0;
1217 }
1218
1219 /*
1220  * amdgpu_ttm_tt_get_usermm - Return memory manager for ttm_tt object
1221  */
1222 struct mm_struct *amdgpu_ttm_tt_get_usermm(struct ttm_tt *ttm)
1223 {
1224         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1225
1226         if (gtt == NULL)
1227                 return NULL;
1228
1229         if (gtt->usertask == NULL)
1230                 return NULL;
1231
1232         return gtt->usertask->mm;
1233 }
1234
1235 /*
1236  * amdgpu_ttm_tt_affect_userptr - Determine if a ttm_tt object lays inside an
1237  * address range for the current task.
1238  *
1239  */
1240 bool amdgpu_ttm_tt_affect_userptr(struct ttm_tt *ttm, unsigned long start,
1241                                   unsigned long end)
1242 {
1243         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1244         unsigned long size;
1245
1246         if (gtt == NULL || !gtt->userptr)
1247                 return false;
1248
1249         /* Return false if no part of the ttm_tt object lies within
1250          * the range
1251          */
1252         size = (unsigned long)gtt->ttm.num_pages * PAGE_SIZE;
1253         if (gtt->userptr > end || gtt->userptr + size <= start)
1254                 return false;
1255
1256         return true;
1257 }
1258
1259 /*
1260  * amdgpu_ttm_tt_is_userptr - Have the pages backing by userptr?
1261  */
1262 bool amdgpu_ttm_tt_is_userptr(struct ttm_tt *ttm)
1263 {
1264         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1265
1266         if (gtt == NULL || !gtt->userptr)
1267                 return false;
1268
1269         return true;
1270 }
1271
1272 /*
1273  * amdgpu_ttm_tt_is_readonly - Is the ttm_tt object read only?
1274  */
1275 bool amdgpu_ttm_tt_is_readonly(struct ttm_tt *ttm)
1276 {
1277         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1278
1279         if (gtt == NULL)
1280                 return false;
1281
1282         return !!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1283 }
1284
1285 /**
1286  * amdgpu_ttm_tt_pde_flags - Compute PDE flags for ttm_tt object
1287  *
1288  * @ttm: The ttm_tt object to compute the flags for
1289  * @mem: The memory registry backing this ttm_tt object
1290  *
1291  * Figure out the flags to use for a VM PDE (Page Directory Entry).
1292  */
1293 uint64_t amdgpu_ttm_tt_pde_flags(struct ttm_tt *ttm, struct ttm_resource *mem)
1294 {
1295         uint64_t flags = 0;
1296
1297         if (mem && mem->mem_type != TTM_PL_SYSTEM)
1298                 flags |= AMDGPU_PTE_VALID;
1299
1300         if (mem && mem->mem_type == TTM_PL_TT) {
1301                 flags |= AMDGPU_PTE_SYSTEM;
1302
1303                 if (ttm->caching == ttm_cached)
1304                         flags |= AMDGPU_PTE_SNOOPED;
1305         }
1306
1307         if (mem && mem->mem_type == TTM_PL_VRAM &&
1308                         mem->bus.caching == ttm_cached)
1309                 flags |= AMDGPU_PTE_SNOOPED;
1310
1311         return flags;
1312 }
1313
1314 /**
1315  * amdgpu_ttm_tt_pte_flags - Compute PTE flags for ttm_tt object
1316  *
1317  * @adev: amdgpu_device pointer
1318  * @ttm: The ttm_tt object to compute the flags for
1319  * @mem: The memory registry backing this ttm_tt object
1320  *
1321  * Figure out the flags to use for a VM PTE (Page Table Entry).
1322  */
1323 uint64_t amdgpu_ttm_tt_pte_flags(struct amdgpu_device *adev, struct ttm_tt *ttm,
1324                                  struct ttm_resource *mem)
1325 {
1326         uint64_t flags = amdgpu_ttm_tt_pde_flags(ttm, mem);
1327
1328         flags |= adev->gart.gart_pte_flags;
1329         flags |= AMDGPU_PTE_READABLE;
1330
1331         if (!amdgpu_ttm_tt_is_readonly(ttm))
1332                 flags |= AMDGPU_PTE_WRITEABLE;
1333
1334         return flags;
1335 }
1336
1337 /*
1338  * amdgpu_ttm_bo_eviction_valuable - Check to see if we can evict a buffer
1339  * object.
1340  *
1341  * Return true if eviction is sensible. Called by ttm_mem_evict_first() on
1342  * behalf of ttm_bo_mem_force_space() which tries to evict buffer objects until
1343  * it can find space for a new object and by ttm_bo_force_list_clean() which is
1344  * used to clean out a memory space.
1345  */
1346 static bool amdgpu_ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
1347                                             const struct ttm_place *place)
1348 {
1349         unsigned long num_pages = bo->mem.num_pages;
1350         struct amdgpu_res_cursor cursor;
1351         struct dma_resv_list *flist;
1352         struct dma_fence *f;
1353         int i;
1354
1355         if (bo->type == ttm_bo_type_kernel &&
1356             !amdgpu_vm_evictable(ttm_to_amdgpu_bo(bo)))
1357                 return false;
1358
1359         /* If bo is a KFD BO, check if the bo belongs to the current process.
1360          * If true, then return false as any KFD process needs all its BOs to
1361          * be resident to run successfully
1362          */
1363         flist = dma_resv_get_list(bo->base.resv);
1364         if (flist) {
1365                 for (i = 0; i < flist->shared_count; ++i) {
1366                         f = rcu_dereference_protected(flist->shared[i],
1367                                 dma_resv_held(bo->base.resv));
1368                         if (amdkfd_fence_check_mm(f, current->mm))
1369                                 return false;
1370                 }
1371         }
1372
1373         switch (bo->mem.mem_type) {
1374         case TTM_PL_TT:
1375                 if (amdgpu_bo_is_amdgpu_bo(bo) &&
1376                     amdgpu_bo_encrypted(ttm_to_amdgpu_bo(bo)))
1377                         return false;
1378                 return true;
1379
1380         case TTM_PL_VRAM:
1381                 /* Check each drm MM node individually */
1382                 amdgpu_res_first(&bo->mem, 0, (u64)num_pages << PAGE_SHIFT,
1383                                  &cursor);
1384                 while (cursor.remaining) {
1385                         if (place->fpfn < PFN_DOWN(cursor.start + cursor.size)
1386                             && !(place->lpfn &&
1387                                  place->lpfn <= PFN_DOWN(cursor.start)))
1388                                 return true;
1389
1390                         amdgpu_res_next(&cursor, cursor.size);
1391                 }
1392                 return false;
1393
1394         default:
1395                 break;
1396         }
1397
1398         return ttm_bo_eviction_valuable(bo, place);
1399 }
1400
1401 /**
1402  * amdgpu_ttm_access_memory - Read or Write memory that backs a buffer object.
1403  *
1404  * @bo:  The buffer object to read/write
1405  * @offset:  Offset into buffer object
1406  * @buf:  Secondary buffer to write/read from
1407  * @len: Length in bytes of access
1408  * @write:  true if writing
1409  *
1410  * This is used to access VRAM that backs a buffer object via MMIO
1411  * access for debugging purposes.
1412  */
1413 static int amdgpu_ttm_access_memory(struct ttm_buffer_object *bo,
1414                                     unsigned long offset, void *buf, int len,
1415                                     int write)
1416 {
1417         struct amdgpu_bo *abo = ttm_to_amdgpu_bo(bo);
1418         struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1419         struct amdgpu_res_cursor cursor;
1420         unsigned long flags;
1421         uint32_t value = 0;
1422         int ret = 0;
1423
1424         if (bo->mem.mem_type != TTM_PL_VRAM)
1425                 return -EIO;
1426
1427         amdgpu_res_first(&bo->mem, offset, len, &cursor);
1428         while (cursor.remaining) {
1429                 uint64_t aligned_pos = cursor.start & ~(uint64_t)3;
1430                 uint64_t bytes = 4 - (cursor.start & 3);
1431                 uint32_t shift = (cursor.start & 3) * 8;
1432                 uint32_t mask = 0xffffffff << shift;
1433
1434                 if (cursor.size < bytes) {
1435                         mask &= 0xffffffff >> (bytes - cursor.size) * 8;
1436                         bytes = cursor.size;
1437                 }
1438
1439                 if (mask != 0xffffffff) {
1440                         spin_lock_irqsave(&adev->mmio_idx_lock, flags);
1441                         WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)aligned_pos) | 0x80000000);
1442                         WREG32_NO_KIQ(mmMM_INDEX_HI, aligned_pos >> 31);
1443                         value = RREG32_NO_KIQ(mmMM_DATA);
1444                         if (write) {
1445                                 value &= ~mask;
1446                                 value |= (*(uint32_t *)buf << shift) & mask;
1447                                 WREG32_NO_KIQ(mmMM_DATA, value);
1448                         }
1449                         spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
1450                         if (!write) {
1451                                 value = (value & mask) >> shift;
1452                                 memcpy(buf, &value, bytes);
1453                         }
1454                 } else {
1455                         bytes = cursor.size & ~0x3ULL;
1456                         amdgpu_device_vram_access(adev, cursor.start,
1457                                                   (uint32_t *)buf, bytes,
1458                                                   write);
1459                 }
1460
1461                 ret += bytes;
1462                 buf = (uint8_t *)buf + bytes;
1463                 amdgpu_res_next(&cursor, bytes);
1464         }
1465
1466         return ret;
1467 }
1468
1469 static void
1470 amdgpu_bo_delete_mem_notify(struct ttm_buffer_object *bo)
1471 {
1472         amdgpu_bo_move_notify(bo, false, NULL);
1473 }
1474
1475 static struct ttm_device_funcs amdgpu_bo_driver = {
1476         .ttm_tt_create = &amdgpu_ttm_tt_create,
1477         .ttm_tt_populate = &amdgpu_ttm_tt_populate,
1478         .ttm_tt_unpopulate = &amdgpu_ttm_tt_unpopulate,
1479         .ttm_tt_destroy = &amdgpu_ttm_backend_destroy,
1480         .eviction_valuable = amdgpu_ttm_bo_eviction_valuable,
1481         .evict_flags = &amdgpu_evict_flags,
1482         .move = &amdgpu_bo_move,
1483         .verify_access = &amdgpu_verify_access,
1484         .delete_mem_notify = &amdgpu_bo_delete_mem_notify,
1485         .release_notify = &amdgpu_bo_release_notify,
1486         .io_mem_reserve = &amdgpu_ttm_io_mem_reserve,
1487         .io_mem_pfn = amdgpu_ttm_io_mem_pfn,
1488         .access_memory = &amdgpu_ttm_access_memory,
1489         .del_from_lru_notify = &amdgpu_vm_del_from_lru_notify
1490 };
1491
1492 /*
1493  * Firmware Reservation functions
1494  */
1495 /**
1496  * amdgpu_ttm_fw_reserve_vram_fini - free fw reserved vram
1497  *
1498  * @adev: amdgpu_device pointer
1499  *
1500  * free fw reserved vram if it has been reserved.
1501  */
1502 static void amdgpu_ttm_fw_reserve_vram_fini(struct amdgpu_device *adev)
1503 {
1504         amdgpu_bo_free_kernel(&adev->mman.fw_vram_usage_reserved_bo,
1505                 NULL, &adev->mman.fw_vram_usage_va);
1506 }
1507
1508 /**
1509  * amdgpu_ttm_fw_reserve_vram_init - create bo vram reservation from fw
1510  *
1511  * @adev: amdgpu_device pointer
1512  *
1513  * create bo vram reservation from fw.
1514  */
1515 static int amdgpu_ttm_fw_reserve_vram_init(struct amdgpu_device *adev)
1516 {
1517         uint64_t vram_size = adev->gmc.visible_vram_size;
1518
1519         adev->mman.fw_vram_usage_va = NULL;
1520         adev->mman.fw_vram_usage_reserved_bo = NULL;
1521
1522         if (adev->mman.fw_vram_usage_size == 0 ||
1523             adev->mman.fw_vram_usage_size > vram_size)
1524                 return 0;
1525
1526         return amdgpu_bo_create_kernel_at(adev,
1527                                           adev->mman.fw_vram_usage_start_offset,
1528                                           adev->mman.fw_vram_usage_size,
1529                                           AMDGPU_GEM_DOMAIN_VRAM,
1530                                           &adev->mman.fw_vram_usage_reserved_bo,
1531                                           &adev->mman.fw_vram_usage_va);
1532 }
1533
1534 /*
1535  * Memoy training reservation functions
1536  */
1537
1538 /**
1539  * amdgpu_ttm_training_reserve_vram_fini - free memory training reserved vram
1540  *
1541  * @adev: amdgpu_device pointer
1542  *
1543  * free memory training reserved vram if it has been reserved.
1544  */
1545 static int amdgpu_ttm_training_reserve_vram_fini(struct amdgpu_device *adev)
1546 {
1547         struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1548
1549         ctx->init = PSP_MEM_TRAIN_NOT_SUPPORT;
1550         amdgpu_bo_free_kernel(&ctx->c2p_bo, NULL, NULL);
1551         ctx->c2p_bo = NULL;
1552
1553         return 0;
1554 }
1555
1556 static void amdgpu_ttm_training_data_block_init(struct amdgpu_device *adev)
1557 {
1558         struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1559
1560         memset(ctx, 0, sizeof(*ctx));
1561
1562         ctx->c2p_train_data_offset =
1563                 ALIGN((adev->gmc.mc_vram_size - adev->mman.discovery_tmr_size - SZ_1M), SZ_1M);
1564         ctx->p2c_train_data_offset =
1565                 (adev->gmc.mc_vram_size - GDDR6_MEM_TRAINING_OFFSET);
1566         ctx->train_data_size =
1567                 GDDR6_MEM_TRAINING_DATA_SIZE_IN_BYTES;
1568
1569         DRM_DEBUG("train_data_size:%llx,p2c_train_data_offset:%llx,c2p_train_data_offset:%llx.\n",
1570                         ctx->train_data_size,
1571                         ctx->p2c_train_data_offset,
1572                         ctx->c2p_train_data_offset);
1573 }
1574
1575 /*
1576  * reserve TMR memory at the top of VRAM which holds
1577  * IP Discovery data and is protected by PSP.
1578  */
1579 static int amdgpu_ttm_reserve_tmr(struct amdgpu_device *adev)
1580 {
1581         int ret;
1582         struct psp_memory_training_context *ctx = &adev->psp.mem_train_ctx;
1583         bool mem_train_support = false;
1584
1585         if (!amdgpu_sriov_vf(adev)) {
1586                 if (amdgpu_atomfirmware_mem_training_supported(adev))
1587                         mem_train_support = true;
1588                 else
1589                         DRM_DEBUG("memory training does not support!\n");
1590         }
1591
1592         /*
1593          * Query reserved tmr size through atom firmwareinfo for Sienna_Cichlid and onwards for all
1594          * the use cases (IP discovery/G6 memory training/profiling/diagnostic data.etc)
1595          *
1596          * Otherwise, fallback to legacy approach to check and reserve tmr block for ip
1597          * discovery data and G6 memory training data respectively
1598          */
1599         adev->mman.discovery_tmr_size =
1600                 amdgpu_atomfirmware_get_fw_reserved_fb_size(adev);
1601         if (!adev->mman.discovery_tmr_size)
1602                 adev->mman.discovery_tmr_size = DISCOVERY_TMR_OFFSET;
1603
1604         if (mem_train_support) {
1605                 /* reserve vram for mem train according to TMR location */
1606                 amdgpu_ttm_training_data_block_init(adev);
1607                 ret = amdgpu_bo_create_kernel_at(adev,
1608                                          ctx->c2p_train_data_offset,
1609                                          ctx->train_data_size,
1610                                          AMDGPU_GEM_DOMAIN_VRAM,
1611                                          &ctx->c2p_bo,
1612                                          NULL);
1613                 if (ret) {
1614                         DRM_ERROR("alloc c2p_bo failed(%d)!\n", ret);
1615                         amdgpu_ttm_training_reserve_vram_fini(adev);
1616                         return ret;
1617                 }
1618                 ctx->init = PSP_MEM_TRAIN_RESERVE_SUCCESS;
1619         }
1620
1621         ret = amdgpu_bo_create_kernel_at(adev,
1622                                 adev->gmc.real_vram_size - adev->mman.discovery_tmr_size,
1623                                 adev->mman.discovery_tmr_size,
1624                                 AMDGPU_GEM_DOMAIN_VRAM,
1625                                 &adev->mman.discovery_memory,
1626                                 NULL);
1627         if (ret) {
1628                 DRM_ERROR("alloc tmr failed(%d)!\n", ret);
1629                 amdgpu_bo_free_kernel(&adev->mman.discovery_memory, NULL, NULL);
1630                 return ret;
1631         }
1632
1633         return 0;
1634 }
1635
1636 /*
1637  * amdgpu_ttm_init - Init the memory management (ttm) as well as various
1638  * gtt/vram related fields.
1639  *
1640  * This initializes all of the memory space pools that the TTM layer
1641  * will need such as the GTT space (system memory mapped to the device),
1642  * VRAM (on-board memory), and on-chip memories (GDS, GWS, OA) which
1643  * can be mapped per VMID.
1644  */
1645 int amdgpu_ttm_init(struct amdgpu_device *adev)
1646 {
1647         uint64_t gtt_size;
1648         int r;
1649         u64 vis_vram_limit;
1650
1651         mutex_init(&adev->mman.gtt_window_lock);
1652
1653         /* No others user of address space so set it to 0 */
1654         r = ttm_device_init(&adev->mman.bdev, &amdgpu_bo_driver, adev->dev,
1655                                adev_to_drm(adev)->anon_inode->i_mapping,
1656                                adev_to_drm(adev)->vma_offset_manager,
1657                                adev->need_swiotlb,
1658                                dma_addressing_limited(adev->dev));
1659         if (r) {
1660                 DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
1661                 return r;
1662         }
1663         adev->mman.initialized = true;
1664
1665         /* Initialize VRAM pool with all of VRAM divided into pages */
1666         r = amdgpu_vram_mgr_init(adev);
1667         if (r) {
1668                 DRM_ERROR("Failed initializing VRAM heap.\n");
1669                 return r;
1670         }
1671
1672         /* Reduce size of CPU-visible VRAM if requested */
1673         vis_vram_limit = (u64)amdgpu_vis_vram_limit * 1024 * 1024;
1674         if (amdgpu_vis_vram_limit > 0 &&
1675             vis_vram_limit <= adev->gmc.visible_vram_size)
1676                 adev->gmc.visible_vram_size = vis_vram_limit;
1677
1678         /* Change the size here instead of the init above so only lpfn is affected */
1679         amdgpu_ttm_set_buffer_funcs_status(adev, false);
1680 #ifdef CONFIG_64BIT
1681 #ifdef CONFIG_X86
1682         if (adev->gmc.xgmi.connected_to_cpu)
1683                 adev->mman.aper_base_kaddr = ioremap_cache(adev->gmc.aper_base,
1684                                 adev->gmc.visible_vram_size);
1685
1686         else
1687 #endif
1688                 adev->mman.aper_base_kaddr = ioremap_wc(adev->gmc.aper_base,
1689                                 adev->gmc.visible_vram_size);
1690 #endif
1691
1692         /*
1693          *The reserved vram for firmware must be pinned to the specified
1694          *place on the VRAM, so reserve it early.
1695          */
1696         r = amdgpu_ttm_fw_reserve_vram_init(adev);
1697         if (r) {
1698                 return r;
1699         }
1700
1701         /*
1702          * only NAVI10 and onwards ASIC support for IP discovery.
1703          * If IP discovery enabled, a block of memory should be
1704          * reserved for IP discovey.
1705          */
1706         if (adev->mman.discovery_bin) {
1707                 r = amdgpu_ttm_reserve_tmr(adev);
1708                 if (r)
1709                         return r;
1710         }
1711
1712         /* allocate memory as required for VGA
1713          * This is used for VGA emulation and pre-OS scanout buffers to
1714          * avoid display artifacts while transitioning between pre-OS
1715          * and driver.  */
1716         r = amdgpu_bo_create_kernel_at(adev, 0, adev->mman.stolen_vga_size,
1717                                        AMDGPU_GEM_DOMAIN_VRAM,
1718                                        &adev->mman.stolen_vga_memory,
1719                                        NULL);
1720         if (r)
1721                 return r;
1722         r = amdgpu_bo_create_kernel_at(adev, adev->mman.stolen_vga_size,
1723                                        adev->mman.stolen_extended_size,
1724                                        AMDGPU_GEM_DOMAIN_VRAM,
1725                                        &adev->mman.stolen_extended_memory,
1726                                        NULL);
1727         if (r)
1728                 return r;
1729
1730         DRM_INFO("amdgpu: %uM of VRAM memory ready\n",
1731                  (unsigned) (adev->gmc.real_vram_size / (1024 * 1024)));
1732
1733         /* Compute GTT size, either bsaed on 3/4th the size of RAM size
1734          * or whatever the user passed on module init */
1735         if (amdgpu_gtt_size == -1) {
1736                 struct sysinfo si;
1737
1738                 si_meminfo(&si);
1739                 gtt_size = min(max((AMDGPU_DEFAULT_GTT_SIZE_MB << 20),
1740                                adev->gmc.mc_vram_size),
1741                                ((uint64_t)si.totalram * si.mem_unit * 3/4));
1742         }
1743         else
1744                 gtt_size = (uint64_t)amdgpu_gtt_size << 20;
1745
1746         /* Initialize GTT memory pool */
1747         r = amdgpu_gtt_mgr_init(adev, gtt_size);
1748         if (r) {
1749                 DRM_ERROR("Failed initializing GTT heap.\n");
1750                 return r;
1751         }
1752         DRM_INFO("amdgpu: %uM of GTT memory ready.\n",
1753                  (unsigned)(gtt_size / (1024 * 1024)));
1754
1755         /* Initialize various on-chip memory pools */
1756         r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GDS, adev->gds.gds_size);
1757         if (r) {
1758                 DRM_ERROR("Failed initializing GDS heap.\n");
1759                 return r;
1760         }
1761
1762         r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_GWS, adev->gds.gws_size);
1763         if (r) {
1764                 DRM_ERROR("Failed initializing gws heap.\n");
1765                 return r;
1766         }
1767
1768         r = amdgpu_ttm_init_on_chip(adev, AMDGPU_PL_OA, adev->gds.oa_size);
1769         if (r) {
1770                 DRM_ERROR("Failed initializing oa heap.\n");
1771                 return r;
1772         }
1773
1774         return 0;
1775 }
1776
1777 /*
1778  * amdgpu_ttm_fini - De-initialize the TTM memory pools
1779  */
1780 void amdgpu_ttm_fini(struct amdgpu_device *adev)
1781 {
1782         if (!adev->mman.initialized)
1783                 return;
1784
1785         amdgpu_ttm_training_reserve_vram_fini(adev);
1786         /* return the stolen vga memory back to VRAM */
1787         amdgpu_bo_free_kernel(&adev->mman.stolen_vga_memory, NULL, NULL);
1788         amdgpu_bo_free_kernel(&adev->mman.stolen_extended_memory, NULL, NULL);
1789         /* return the IP Discovery TMR memory back to VRAM */
1790         amdgpu_bo_free_kernel(&adev->mman.discovery_memory, NULL, NULL);
1791         amdgpu_ttm_fw_reserve_vram_fini(adev);
1792
1793         if (adev->mman.aper_base_kaddr)
1794                 iounmap(adev->mman.aper_base_kaddr);
1795         adev->mman.aper_base_kaddr = NULL;
1796
1797         amdgpu_vram_mgr_fini(adev);
1798         amdgpu_gtt_mgr_fini(adev);
1799         ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GDS);
1800         ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_GWS);
1801         ttm_range_man_fini(&adev->mman.bdev, AMDGPU_PL_OA);
1802         ttm_device_fini(&adev->mman.bdev);
1803         adev->mman.initialized = false;
1804         DRM_INFO("amdgpu: ttm finalized\n");
1805 }
1806
1807 /**
1808  * amdgpu_ttm_set_buffer_funcs_status - enable/disable use of buffer functions
1809  *
1810  * @adev: amdgpu_device pointer
1811  * @enable: true when we can use buffer functions.
1812  *
1813  * Enable/disable use of buffer functions during suspend/resume. This should
1814  * only be called at bootup or when userspace isn't running.
1815  */
1816 void amdgpu_ttm_set_buffer_funcs_status(struct amdgpu_device *adev, bool enable)
1817 {
1818         struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev, TTM_PL_VRAM);
1819         uint64_t size;
1820         int r;
1821
1822         if (!adev->mman.initialized || amdgpu_in_reset(adev) ||
1823             adev->mman.buffer_funcs_enabled == enable)
1824                 return;
1825
1826         if (enable) {
1827                 struct amdgpu_ring *ring;
1828                 struct drm_gpu_scheduler *sched;
1829
1830                 ring = adev->mman.buffer_funcs_ring;
1831                 sched = &ring->sched;
1832                 r = drm_sched_entity_init(&adev->mman.entity,
1833                                           DRM_SCHED_PRIORITY_KERNEL, &sched,
1834                                           1, NULL);
1835                 if (r) {
1836                         DRM_ERROR("Failed setting up TTM BO move entity (%d)\n",
1837                                   r);
1838                         return;
1839                 }
1840         } else {
1841                 drm_sched_entity_destroy(&adev->mman.entity);
1842                 dma_fence_put(man->move);
1843                 man->move = NULL;
1844         }
1845
1846         /* this just adjusts TTM size idea, which sets lpfn to the correct value */
1847         if (enable)
1848                 size = adev->gmc.real_vram_size;
1849         else
1850                 size = adev->gmc.visible_vram_size;
1851         man->size = size >> PAGE_SHIFT;
1852         adev->mman.buffer_funcs_enabled = enable;
1853 }
1854
1855 static vm_fault_t amdgpu_ttm_fault(struct vm_fault *vmf)
1856 {
1857         struct ttm_buffer_object *bo = vmf->vma->vm_private_data;
1858         vm_fault_t ret;
1859
1860         ret = ttm_bo_vm_reserve(bo, vmf);
1861         if (ret)
1862                 return ret;
1863
1864         ret = amdgpu_bo_fault_reserve_notify(bo);
1865         if (ret)
1866                 goto unlock;
1867
1868         ret = ttm_bo_vm_fault_reserved(vmf, vmf->vma->vm_page_prot,
1869                                        TTM_BO_VM_NUM_PREFAULT, 1);
1870         if (ret == VM_FAULT_RETRY && !(vmf->flags & FAULT_FLAG_RETRY_NOWAIT))
1871                 return ret;
1872
1873 unlock:
1874         dma_resv_unlock(bo->base.resv);
1875         return ret;
1876 }
1877
1878 static const struct vm_operations_struct amdgpu_ttm_vm_ops = {
1879         .fault = amdgpu_ttm_fault,
1880         .open = ttm_bo_vm_open,
1881         .close = ttm_bo_vm_close,
1882         .access = ttm_bo_vm_access
1883 };
1884
1885 int amdgpu_mmap(struct file *filp, struct vm_area_struct *vma)
1886 {
1887         struct drm_file *file_priv = filp->private_data;
1888         struct amdgpu_device *adev = drm_to_adev(file_priv->minor->dev);
1889         int r;
1890
1891         r = ttm_bo_mmap(filp, vma, &adev->mman.bdev);
1892         if (unlikely(r != 0))
1893                 return r;
1894
1895         vma->vm_ops = &amdgpu_ttm_vm_ops;
1896         return 0;
1897 }
1898
1899 int amdgpu_copy_buffer(struct amdgpu_ring *ring, uint64_t src_offset,
1900                        uint64_t dst_offset, uint32_t byte_count,
1901                        struct dma_resv *resv,
1902                        struct dma_fence **fence, bool direct_submit,
1903                        bool vm_needs_flush, bool tmz)
1904 {
1905         enum amdgpu_ib_pool_type pool = direct_submit ? AMDGPU_IB_POOL_DIRECT :
1906                 AMDGPU_IB_POOL_DELAYED;
1907         struct amdgpu_device *adev = ring->adev;
1908         struct amdgpu_job *job;
1909
1910         uint32_t max_bytes;
1911         unsigned num_loops, num_dw;
1912         unsigned i;
1913         int r;
1914
1915         if (direct_submit && !ring->sched.ready) {
1916                 DRM_ERROR("Trying to move memory with ring turned off.\n");
1917                 return -EINVAL;
1918         }
1919
1920         max_bytes = adev->mman.buffer_funcs->copy_max_bytes;
1921         num_loops = DIV_ROUND_UP(byte_count, max_bytes);
1922         num_dw = ALIGN(num_loops * adev->mman.buffer_funcs->copy_num_dw, 8);
1923
1924         r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, pool, &job);
1925         if (r)
1926                 return r;
1927
1928         if (vm_needs_flush) {
1929                 job->vm_pd_addr = amdgpu_gmc_pd_addr(adev->gmc.pdb0_bo ?
1930                                         adev->gmc.pdb0_bo : adev->gart.bo);
1931                 job->vm_needs_flush = true;
1932         }
1933         if (resv) {
1934                 r = amdgpu_sync_resv(adev, &job->sync, resv,
1935                                      AMDGPU_SYNC_ALWAYS,
1936                                      AMDGPU_FENCE_OWNER_UNDEFINED);
1937                 if (r) {
1938                         DRM_ERROR("sync failed (%d).\n", r);
1939                         goto error_free;
1940                 }
1941         }
1942
1943         for (i = 0; i < num_loops; i++) {
1944                 uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
1945
1946                 amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
1947                                         dst_offset, cur_size_in_bytes, tmz);
1948
1949                 src_offset += cur_size_in_bytes;
1950                 dst_offset += cur_size_in_bytes;
1951                 byte_count -= cur_size_in_bytes;
1952         }
1953
1954         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
1955         WARN_ON(job->ibs[0].length_dw > num_dw);
1956         if (direct_submit)
1957                 r = amdgpu_job_submit_direct(job, ring, fence);
1958         else
1959                 r = amdgpu_job_submit(job, &adev->mman.entity,
1960                                       AMDGPU_FENCE_OWNER_UNDEFINED, fence);
1961         if (r)
1962                 goto error_free;
1963
1964         return r;
1965
1966 error_free:
1967         amdgpu_job_free(job);
1968         DRM_ERROR("Error scheduling IBs (%d)\n", r);
1969         return r;
1970 }
1971
1972 int amdgpu_fill_buffer(struct amdgpu_bo *bo,
1973                        uint32_t src_data,
1974                        struct dma_resv *resv,
1975                        struct dma_fence **fence)
1976 {
1977         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1978         uint32_t max_bytes = adev->mman.buffer_funcs->fill_max_bytes;
1979         struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
1980
1981         struct amdgpu_res_cursor cursor;
1982         unsigned int num_loops, num_dw;
1983         uint64_t num_bytes;
1984
1985         struct amdgpu_job *job;
1986         int r;
1987
1988         if (!adev->mman.buffer_funcs_enabled) {
1989                 DRM_ERROR("Trying to clear memory with ring turned off.\n");
1990                 return -EINVAL;
1991         }
1992
1993         if (bo->tbo.mem.mem_type == TTM_PL_TT) {
1994                 r = amdgpu_ttm_alloc_gart(&bo->tbo);
1995                 if (r)
1996                         return r;
1997         }
1998
1999         num_bytes = bo->tbo.mem.num_pages << PAGE_SHIFT;
2000         num_loops = 0;
2001
2002         amdgpu_res_first(&bo->tbo.mem, 0, num_bytes, &cursor);
2003         while (cursor.remaining) {
2004                 num_loops += DIV_ROUND_UP_ULL(cursor.size, max_bytes);
2005                 amdgpu_res_next(&cursor, cursor.size);
2006         }
2007         num_dw = num_loops * adev->mman.buffer_funcs->fill_num_dw;
2008
2009         /* for IB padding */
2010         num_dw += 64;
2011
2012         r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, AMDGPU_IB_POOL_DELAYED,
2013                                      &job);
2014         if (r)
2015                 return r;
2016
2017         if (resv) {
2018                 r = amdgpu_sync_resv(adev, &job->sync, resv,
2019                                      AMDGPU_SYNC_ALWAYS,
2020                                      AMDGPU_FENCE_OWNER_UNDEFINED);
2021                 if (r) {
2022                         DRM_ERROR("sync failed (%d).\n", r);
2023                         goto error_free;
2024                 }
2025         }
2026
2027         amdgpu_res_first(&bo->tbo.mem, 0, num_bytes, &cursor);
2028         while (cursor.remaining) {
2029                 uint32_t cur_size = min_t(uint64_t, cursor.size, max_bytes);
2030                 uint64_t dst_addr = cursor.start;
2031
2032                 dst_addr += amdgpu_ttm_domain_start(adev, bo->tbo.mem.mem_type);
2033                 amdgpu_emit_fill_buffer(adev, &job->ibs[0], src_data, dst_addr,
2034                                         cur_size);
2035
2036                 amdgpu_res_next(&cursor, cur_size);
2037         }
2038
2039         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
2040         WARN_ON(job->ibs[0].length_dw > num_dw);
2041         r = amdgpu_job_submit(job, &adev->mman.entity,
2042                               AMDGPU_FENCE_OWNER_UNDEFINED, fence);
2043         if (r)
2044                 goto error_free;
2045
2046         return 0;
2047
2048 error_free:
2049         amdgpu_job_free(job);
2050         return r;
2051 }
2052
2053 #if defined(CONFIG_DEBUG_FS)
2054
2055 static int amdgpu_mm_vram_table_show(struct seq_file *m, void *unused)
2056 {
2057         struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2058         struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2059                                                             TTM_PL_VRAM);
2060         struct drm_printer p = drm_seq_file_printer(m);
2061
2062         man->func->debug(man, &p);
2063         return 0;
2064 }
2065
2066 static int amdgpu_ttm_page_pool_show(struct seq_file *m, void *unused)
2067 {
2068         struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2069
2070         return ttm_pool_debugfs(&adev->mman.bdev.pool, m);
2071 }
2072
2073 static int amdgpu_mm_tt_table_show(struct seq_file *m, void *unused)
2074 {
2075         struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2076         struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2077                                                             TTM_PL_TT);
2078         struct drm_printer p = drm_seq_file_printer(m);
2079
2080         man->func->debug(man, &p);
2081         return 0;
2082 }
2083
2084 static int amdgpu_mm_gds_table_show(struct seq_file *m, void *unused)
2085 {
2086         struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2087         struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2088                                                             AMDGPU_PL_GDS);
2089         struct drm_printer p = drm_seq_file_printer(m);
2090
2091         man->func->debug(man, &p);
2092         return 0;
2093 }
2094
2095 static int amdgpu_mm_gws_table_show(struct seq_file *m, void *unused)
2096 {
2097         struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2098         struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2099                                                             AMDGPU_PL_GWS);
2100         struct drm_printer p = drm_seq_file_printer(m);
2101
2102         man->func->debug(man, &p);
2103         return 0;
2104 }
2105
2106 static int amdgpu_mm_oa_table_show(struct seq_file *m, void *unused)
2107 {
2108         struct amdgpu_device *adev = (struct amdgpu_device *)m->private;
2109         struct ttm_resource_manager *man = ttm_manager_type(&adev->mman.bdev,
2110                                                             AMDGPU_PL_OA);
2111         struct drm_printer p = drm_seq_file_printer(m);
2112
2113         man->func->debug(man, &p);
2114         return 0;
2115 }
2116
2117 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_vram_table);
2118 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_tt_table);
2119 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_gds_table);
2120 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_gws_table);
2121 DEFINE_SHOW_ATTRIBUTE(amdgpu_mm_oa_table);
2122 DEFINE_SHOW_ATTRIBUTE(amdgpu_ttm_page_pool);
2123
2124 /*
2125  * amdgpu_ttm_vram_read - Linear read access to VRAM
2126  *
2127  * Accesses VRAM via MMIO for debugging purposes.
2128  */
2129 static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
2130                                     size_t size, loff_t *pos)
2131 {
2132         struct amdgpu_device *adev = file_inode(f)->i_private;
2133         ssize_t result = 0;
2134
2135         if (size & 0x3 || *pos & 0x3)
2136                 return -EINVAL;
2137
2138         if (*pos >= adev->gmc.mc_vram_size)
2139                 return -ENXIO;
2140
2141         size = min(size, (size_t)(adev->gmc.mc_vram_size - *pos));
2142         while (size) {
2143                 size_t bytes = min(size, AMDGPU_TTM_VRAM_MAX_DW_READ * 4);
2144                 uint32_t value[AMDGPU_TTM_VRAM_MAX_DW_READ];
2145
2146                 amdgpu_device_vram_access(adev, *pos, value, bytes, false);
2147                 if (copy_to_user(buf, value, bytes))
2148                         return -EFAULT;
2149
2150                 result += bytes;
2151                 buf += bytes;
2152                 *pos += bytes;
2153                 size -= bytes;
2154         }
2155
2156         return result;
2157 }
2158
2159 /*
2160  * amdgpu_ttm_vram_write - Linear write access to VRAM
2161  *
2162  * Accesses VRAM via MMIO for debugging purposes.
2163  */
2164 static ssize_t amdgpu_ttm_vram_write(struct file *f, const char __user *buf,
2165                                     size_t size, loff_t *pos)
2166 {
2167         struct amdgpu_device *adev = file_inode(f)->i_private;
2168         ssize_t result = 0;
2169         int r;
2170
2171         if (size & 0x3 || *pos & 0x3)
2172                 return -EINVAL;
2173
2174         if (*pos >= adev->gmc.mc_vram_size)
2175                 return -ENXIO;
2176
2177         while (size) {
2178                 unsigned long flags;
2179                 uint32_t value;
2180
2181                 if (*pos >= adev->gmc.mc_vram_size)
2182                         return result;
2183
2184                 r = get_user(value, (uint32_t *)buf);
2185                 if (r)
2186                         return r;
2187
2188                 spin_lock_irqsave(&adev->mmio_idx_lock, flags);
2189                 WREG32_NO_KIQ(mmMM_INDEX, ((uint32_t)*pos) | 0x80000000);
2190                 WREG32_NO_KIQ(mmMM_INDEX_HI, *pos >> 31);
2191                 WREG32_NO_KIQ(mmMM_DATA, value);
2192                 spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
2193
2194                 result += 4;
2195                 buf += 4;
2196                 *pos += 4;
2197                 size -= 4;
2198         }
2199
2200         return result;
2201 }
2202
2203 static const struct file_operations amdgpu_ttm_vram_fops = {
2204         .owner = THIS_MODULE,
2205         .read = amdgpu_ttm_vram_read,
2206         .write = amdgpu_ttm_vram_write,
2207         .llseek = default_llseek,
2208 };
2209
2210 /*
2211  * amdgpu_iomem_read - Virtual read access to GPU mapped memory
2212  *
2213  * This function is used to read memory that has been mapped to the
2214  * GPU and the known addresses are not physical addresses but instead
2215  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2216  */
2217 static ssize_t amdgpu_iomem_read(struct file *f, char __user *buf,
2218                                  size_t size, loff_t *pos)
2219 {
2220         struct amdgpu_device *adev = file_inode(f)->i_private;
2221         struct iommu_domain *dom;
2222         ssize_t result = 0;
2223         int r;
2224
2225         /* retrieve the IOMMU domain if any for this device */
2226         dom = iommu_get_domain_for_dev(adev->dev);
2227
2228         while (size) {
2229                 phys_addr_t addr = *pos & PAGE_MASK;
2230                 loff_t off = *pos & ~PAGE_MASK;
2231                 size_t bytes = PAGE_SIZE - off;
2232                 unsigned long pfn;
2233                 struct page *p;
2234                 void *ptr;
2235
2236                 bytes = bytes < size ? bytes : size;
2237
2238                 /* Translate the bus address to a physical address.  If
2239                  * the domain is NULL it means there is no IOMMU active
2240                  * and the address translation is the identity
2241                  */
2242                 addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2243
2244                 pfn = addr >> PAGE_SHIFT;
2245                 if (!pfn_valid(pfn))
2246                         return -EPERM;
2247
2248                 p = pfn_to_page(pfn);
2249                 if (p->mapping != adev->mman.bdev.dev_mapping)
2250                         return -EPERM;
2251
2252                 ptr = kmap(p);
2253                 r = copy_to_user(buf, ptr + off, bytes);
2254                 kunmap(p);
2255                 if (r)
2256                         return -EFAULT;
2257
2258                 size -= bytes;
2259                 *pos += bytes;
2260                 result += bytes;
2261         }
2262
2263         return result;
2264 }
2265
2266 /*
2267  * amdgpu_iomem_write - Virtual write access to GPU mapped memory
2268  *
2269  * This function is used to write memory that has been mapped to the
2270  * GPU and the known addresses are not physical addresses but instead
2271  * bus addresses (e.g., what you'd put in an IB or ring buffer).
2272  */
2273 static ssize_t amdgpu_iomem_write(struct file *f, const char __user *buf,
2274                                  size_t size, loff_t *pos)
2275 {
2276         struct amdgpu_device *adev = file_inode(f)->i_private;
2277         struct iommu_domain *dom;
2278         ssize_t result = 0;
2279         int r;
2280
2281         dom = iommu_get_domain_for_dev(adev->dev);
2282
2283         while (size) {
2284                 phys_addr_t addr = *pos & PAGE_MASK;
2285                 loff_t off = *pos & ~PAGE_MASK;
2286                 size_t bytes = PAGE_SIZE - off;
2287                 unsigned long pfn;
2288                 struct page *p;
2289                 void *ptr;
2290
2291                 bytes = bytes < size ? bytes : size;
2292
2293                 addr = dom ? iommu_iova_to_phys(dom, addr) : addr;
2294
2295                 pfn = addr >> PAGE_SHIFT;
2296                 if (!pfn_valid(pfn))
2297                         return -EPERM;
2298
2299                 p = pfn_to_page(pfn);
2300                 if (p->mapping != adev->mman.bdev.dev_mapping)
2301                         return -EPERM;
2302
2303                 ptr = kmap(p);
2304                 r = copy_from_user(ptr + off, buf, bytes);
2305                 kunmap(p);
2306                 if (r)
2307                         return -EFAULT;
2308
2309                 size -= bytes;
2310                 *pos += bytes;
2311                 result += bytes;
2312         }
2313
2314         return result;
2315 }
2316
2317 static const struct file_operations amdgpu_ttm_iomem_fops = {
2318         .owner = THIS_MODULE,
2319         .read = amdgpu_iomem_read,
2320         .write = amdgpu_iomem_write,
2321         .llseek = default_llseek
2322 };
2323
2324 #endif
2325
2326 void amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
2327 {
2328 #if defined(CONFIG_DEBUG_FS)
2329         struct drm_minor *minor = adev_to_drm(adev)->primary;
2330         struct dentry *root = minor->debugfs_root;
2331
2332         debugfs_create_file_size("amdgpu_vram", 0444, root, adev,
2333                                  &amdgpu_ttm_vram_fops, adev->gmc.mc_vram_size);
2334         debugfs_create_file("amdgpu_iomem", 0444, root, adev,
2335                             &amdgpu_ttm_iomem_fops);
2336         debugfs_create_file("amdgpu_vram_mm", 0444, root, adev,
2337                             &amdgpu_mm_vram_table_fops);
2338         debugfs_create_file("amdgpu_gtt_mm", 0444, root, adev,
2339                             &amdgpu_mm_tt_table_fops);
2340         debugfs_create_file("amdgpu_gds_mm", 0444, root, adev,
2341                             &amdgpu_mm_gds_table_fops);
2342         debugfs_create_file("amdgpu_gws_mm", 0444, root, adev,
2343                             &amdgpu_mm_gws_table_fops);
2344         debugfs_create_file("amdgpu_oa_mm", 0444, root, adev,
2345                             &amdgpu_mm_oa_table_fops);
2346         debugfs_create_file("ttm_page_pool", 0444, root, adev,
2347                             &amdgpu_ttm_page_pool_fops);
2348 #endif
2349 }