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