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