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