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