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