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