Merge tag 'fbdev-v4.14' of git://github.com/bzolnier/linux
[sfrench/cifs-2.6.git] / drivers / gpu / drm / amd / amdgpu / amdgpu_ttm.c
1 /*
2  * Copyright 2009 Jerome Glisse.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sub license, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
16  * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM,
17  * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
18  * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
19  * USE OR OTHER DEALINGS IN THE SOFTWARE.
20  *
21  * The above copyright notice and this permission notice (including the
22  * next paragraph) shall be included in all copies or substantial portions
23  * of the Software.
24  *
25  */
26 /*
27  * Authors:
28  *    Jerome Glisse <glisse@freedesktop.org>
29  *    Thomas Hellstrom <thomas-at-tungstengraphics-dot-com>
30  *    Dave Airlie
31  */
32 #include <drm/ttm/ttm_bo_api.h>
33 #include <drm/ttm/ttm_bo_driver.h>
34 #include <drm/ttm/ttm_placement.h>
35 #include <drm/ttm/ttm_module.h>
36 #include <drm/ttm/ttm_page_alloc.h>
37 #include <drm/drmP.h>
38 #include <drm/amdgpu_drm.h>
39 #include <linux/seq_file.h>
40 #include <linux/slab.h>
41 #include <linux/swiotlb.h>
42 #include <linux/swap.h>
43 #include <linux/pagemap.h>
44 #include <linux/debugfs.h>
45 #include "amdgpu.h"
46 #include "amdgpu_trace.h"
47 #include "bif/bif_4_1_d.h"
48
49 #define DRM_FILE_PAGE_OFFSET (0x100000000ULL >> PAGE_SHIFT)
50
51 static int amdgpu_map_buffer(struct ttm_buffer_object *bo,
52                              struct ttm_mem_reg *mem, unsigned num_pages,
53                              uint64_t offset, unsigned window,
54                              struct amdgpu_ring *ring,
55                              uint64_t *addr);
56
57 static int amdgpu_ttm_debugfs_init(struct amdgpu_device *adev);
58 static void amdgpu_ttm_debugfs_fini(struct amdgpu_device *adev);
59
60 /*
61  * Global memory.
62  */
63 static int amdgpu_ttm_mem_global_init(struct drm_global_reference *ref)
64 {
65         return ttm_mem_global_init(ref->object);
66 }
67
68 static void amdgpu_ttm_mem_global_release(struct drm_global_reference *ref)
69 {
70         ttm_mem_global_release(ref->object);
71 }
72
73 static int amdgpu_ttm_global_init(struct amdgpu_device *adev)
74 {
75         struct drm_global_reference *global_ref;
76         struct amdgpu_ring *ring;
77         struct amd_sched_rq *rq;
78         int r;
79
80         adev->mman.mem_global_referenced = false;
81         global_ref = &adev->mman.mem_global_ref;
82         global_ref->global_type = DRM_GLOBAL_TTM_MEM;
83         global_ref->size = sizeof(struct ttm_mem_global);
84         global_ref->init = &amdgpu_ttm_mem_global_init;
85         global_ref->release = &amdgpu_ttm_mem_global_release;
86         r = drm_global_item_ref(global_ref);
87         if (r) {
88                 DRM_ERROR("Failed setting up TTM memory accounting "
89                           "subsystem.\n");
90                 goto error_mem;
91         }
92
93         adev->mman.bo_global_ref.mem_glob =
94                 adev->mman.mem_global_ref.object;
95         global_ref = &adev->mman.bo_global_ref.ref;
96         global_ref->global_type = DRM_GLOBAL_TTM_BO;
97         global_ref->size = sizeof(struct ttm_bo_global);
98         global_ref->init = &ttm_bo_global_init;
99         global_ref->release = &ttm_bo_global_release;
100         r = drm_global_item_ref(global_ref);
101         if (r) {
102                 DRM_ERROR("Failed setting up TTM BO subsystem.\n");
103                 goto error_bo;
104         }
105
106         mutex_init(&adev->mman.gtt_window_lock);
107
108         ring = adev->mman.buffer_funcs_ring;
109         rq = &ring->sched.sched_rq[AMD_SCHED_PRIORITY_KERNEL];
110         r = amd_sched_entity_init(&ring->sched, &adev->mman.entity,
111                                   rq, amdgpu_sched_jobs);
112         if (r) {
113                 DRM_ERROR("Failed setting up TTM BO move run queue.\n");
114                 goto error_entity;
115         }
116
117         adev->mman.mem_global_referenced = true;
118
119         return 0;
120
121 error_entity:
122         drm_global_item_unref(&adev->mman.bo_global_ref.ref);
123 error_bo:
124         drm_global_item_unref(&adev->mman.mem_global_ref);
125 error_mem:
126         return r;
127 }
128
129 static void amdgpu_ttm_global_fini(struct amdgpu_device *adev)
130 {
131         if (adev->mman.mem_global_referenced) {
132                 amd_sched_entity_fini(adev->mman.entity.sched,
133                                       &adev->mman.entity);
134                 mutex_destroy(&adev->mman.gtt_window_lock);
135                 drm_global_item_unref(&adev->mman.bo_global_ref.ref);
136                 drm_global_item_unref(&adev->mman.mem_global_ref);
137                 adev->mman.mem_global_referenced = false;
138         }
139 }
140
141 static int amdgpu_invalidate_caches(struct ttm_bo_device *bdev, uint32_t flags)
142 {
143         return 0;
144 }
145
146 static int amdgpu_init_mem_type(struct ttm_bo_device *bdev, uint32_t type,
147                                 struct ttm_mem_type_manager *man)
148 {
149         struct amdgpu_device *adev;
150
151         adev = amdgpu_ttm_adev(bdev);
152
153         switch (type) {
154         case TTM_PL_SYSTEM:
155                 /* System memory */
156                 man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
157                 man->available_caching = TTM_PL_MASK_CACHING;
158                 man->default_caching = TTM_PL_FLAG_CACHED;
159                 break;
160         case TTM_PL_TT:
161                 man->func = &amdgpu_gtt_mgr_func;
162                 man->gpu_offset = adev->mc.gart_start;
163                 man->available_caching = TTM_PL_MASK_CACHING;
164                 man->default_caching = TTM_PL_FLAG_CACHED;
165                 man->flags = TTM_MEMTYPE_FLAG_MAPPABLE | TTM_MEMTYPE_FLAG_CMA;
166                 break;
167         case TTM_PL_VRAM:
168                 /* "On-card" video ram */
169                 man->func = &amdgpu_vram_mgr_func;
170                 man->gpu_offset = adev->mc.vram_start;
171                 man->flags = TTM_MEMTYPE_FLAG_FIXED |
172                              TTM_MEMTYPE_FLAG_MAPPABLE;
173                 man->available_caching = TTM_PL_FLAG_UNCACHED | TTM_PL_FLAG_WC;
174                 man->default_caching = TTM_PL_FLAG_WC;
175                 break;
176         case AMDGPU_PL_GDS:
177         case AMDGPU_PL_GWS:
178         case AMDGPU_PL_OA:
179                 /* On-chip GDS memory*/
180                 man->func = &ttm_bo_manager_func;
181                 man->gpu_offset = 0;
182                 man->flags = TTM_MEMTYPE_FLAG_FIXED | TTM_MEMTYPE_FLAG_CMA;
183                 man->available_caching = TTM_PL_FLAG_UNCACHED;
184                 man->default_caching = TTM_PL_FLAG_UNCACHED;
185                 break;
186         default:
187                 DRM_ERROR("Unsupported memory type %u\n", (unsigned)type);
188                 return -EINVAL;
189         }
190         return 0;
191 }
192
193 static void amdgpu_evict_flags(struct ttm_buffer_object *bo,
194                                 struct ttm_placement *placement)
195 {
196         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
197         struct amdgpu_bo *abo;
198         static const struct ttm_place placements = {
199                 .fpfn = 0,
200                 .lpfn = 0,
201                 .flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_SYSTEM
202         };
203
204         if (!amdgpu_ttm_bo_is_amdgpu_bo(bo)) {
205                 placement->placement = &placements;
206                 placement->busy_placement = &placements;
207                 placement->num_placement = 1;
208                 placement->num_busy_placement = 1;
209                 return;
210         }
211         abo = container_of(bo, struct amdgpu_bo, tbo);
212         switch (bo->mem.mem_type) {
213         case TTM_PL_VRAM:
214                 if (adev->mman.buffer_funcs &&
215                     adev->mman.buffer_funcs_ring &&
216                     adev->mman.buffer_funcs_ring->ready == false) {
217                         amdgpu_ttm_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
218                 } else if (adev->mc.visible_vram_size < adev->mc.real_vram_size &&
219                            !(abo->flags & AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED)) {
220                         unsigned fpfn = adev->mc.visible_vram_size >> PAGE_SHIFT;
221                         struct drm_mm_node *node = bo->mem.mm_node;
222                         unsigned long pages_left;
223
224                         for (pages_left = bo->mem.num_pages;
225                              pages_left;
226                              pages_left -= node->size, node++) {
227                                 if (node->start < fpfn)
228                                         break;
229                         }
230
231                         if (!pages_left)
232                                 goto gtt;
233
234                         /* Try evicting to the CPU inaccessible part of VRAM
235                          * first, but only set GTT as busy placement, so this
236                          * BO will be evicted to GTT rather than causing other
237                          * BOs to be evicted from VRAM
238                          */
239                         amdgpu_ttm_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_VRAM |
240                                                          AMDGPU_GEM_DOMAIN_GTT);
241                         abo->placements[0].fpfn = fpfn;
242                         abo->placements[0].lpfn = 0;
243                         abo->placement.busy_placement = &abo->placements[1];
244                         abo->placement.num_busy_placement = 1;
245                 } else {
246 gtt:
247                         amdgpu_ttm_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_GTT);
248                 }
249                 break;
250         case TTM_PL_TT:
251         default:
252                 amdgpu_ttm_placement_from_domain(abo, AMDGPU_GEM_DOMAIN_CPU);
253         }
254         *placement = abo->placement;
255 }
256
257 static int amdgpu_verify_access(struct ttm_buffer_object *bo, struct file *filp)
258 {
259         struct amdgpu_bo *abo = container_of(bo, struct amdgpu_bo, tbo);
260
261         if (amdgpu_ttm_tt_get_usermm(bo->ttm))
262                 return -EPERM;
263         return drm_vma_node_verify_access(&abo->gem_base.vma_node,
264                                           filp->private_data);
265 }
266
267 static void amdgpu_move_null(struct ttm_buffer_object *bo,
268                              struct ttm_mem_reg *new_mem)
269 {
270         struct ttm_mem_reg *old_mem = &bo->mem;
271
272         BUG_ON(old_mem->mm_node != NULL);
273         *old_mem = *new_mem;
274         new_mem->mm_node = NULL;
275 }
276
277 static uint64_t amdgpu_mm_node_addr(struct ttm_buffer_object *bo,
278                                     struct drm_mm_node *mm_node,
279                                     struct ttm_mem_reg *mem)
280 {
281         uint64_t addr = 0;
282
283         if (mem->mem_type != TTM_PL_TT ||
284             amdgpu_gtt_mgr_is_allocated(mem)) {
285                 addr = mm_node->start << PAGE_SHIFT;
286                 addr += bo->bdev->man[mem->mem_type].gpu_offset;
287         }
288         return addr;
289 }
290
291 static int amdgpu_move_blit(struct ttm_buffer_object *bo,
292                             bool evict, bool no_wait_gpu,
293                             struct ttm_mem_reg *new_mem,
294                             struct ttm_mem_reg *old_mem)
295 {
296         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->bdev);
297         struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
298
299         struct drm_mm_node *old_mm, *new_mm;
300         uint64_t old_start, old_size, new_start, new_size;
301         unsigned long num_pages;
302         struct dma_fence *fence = NULL;
303         int r;
304
305         BUILD_BUG_ON((PAGE_SIZE % AMDGPU_GPU_PAGE_SIZE) != 0);
306
307         if (!ring->ready) {
308                 DRM_ERROR("Trying to move memory with ring turned off.\n");
309                 return -EINVAL;
310         }
311
312         old_mm = old_mem->mm_node;
313         old_size = old_mm->size;
314         old_start = amdgpu_mm_node_addr(bo, old_mm, old_mem);
315
316         new_mm = new_mem->mm_node;
317         new_size = new_mm->size;
318         new_start = amdgpu_mm_node_addr(bo, new_mm, new_mem);
319
320         num_pages = new_mem->num_pages;
321         mutex_lock(&adev->mman.gtt_window_lock);
322         while (num_pages) {
323                 unsigned long cur_pages = min(min(old_size, new_size),
324                                               (u64)AMDGPU_GTT_MAX_TRANSFER_SIZE);
325                 uint64_t from = old_start, to = new_start;
326                 struct dma_fence *next;
327
328                 if (old_mem->mem_type == TTM_PL_TT &&
329                     !amdgpu_gtt_mgr_is_allocated(old_mem)) {
330                         r = amdgpu_map_buffer(bo, old_mem, cur_pages,
331                                               old_start, 0, ring, &from);
332                         if (r)
333                                 goto error;
334                 }
335
336                 if (new_mem->mem_type == TTM_PL_TT &&
337                     !amdgpu_gtt_mgr_is_allocated(new_mem)) {
338                         r = amdgpu_map_buffer(bo, new_mem, cur_pages,
339                                               new_start, 1, ring, &to);
340                         if (r)
341                                 goto error;
342                 }
343
344                 r = amdgpu_copy_buffer(ring, from, to,
345                                        cur_pages * PAGE_SIZE,
346                                        bo->resv, &next, false, true);
347                 if (r)
348                         goto error;
349
350                 dma_fence_put(fence);
351                 fence = next;
352
353                 num_pages -= cur_pages;
354                 if (!num_pages)
355                         break;
356
357                 old_size -= cur_pages;
358                 if (!old_size) {
359                         old_start = amdgpu_mm_node_addr(bo, ++old_mm, old_mem);
360                         old_size = old_mm->size;
361                 } else {
362                         old_start += cur_pages * PAGE_SIZE;
363                 }
364
365                 new_size -= cur_pages;
366                 if (!new_size) {
367                         new_start = amdgpu_mm_node_addr(bo, ++new_mm, new_mem);
368                         new_size = new_mm->size;
369                 } else {
370                         new_start += cur_pages * PAGE_SIZE;
371                 }
372         }
373         mutex_unlock(&adev->mman.gtt_window_lock);
374
375         r = ttm_bo_pipeline_move(bo, fence, evict, new_mem);
376         dma_fence_put(fence);
377         return r;
378
379 error:
380         mutex_unlock(&adev->mman.gtt_window_lock);
381
382         if (fence)
383                 dma_fence_wait(fence, false);
384         dma_fence_put(fence);
385         return r;
386 }
387
388 static int amdgpu_move_vram_ram(struct ttm_buffer_object *bo,
389                                 bool evict, bool interruptible,
390                                 bool no_wait_gpu,
391                                 struct ttm_mem_reg *new_mem)
392 {
393         struct amdgpu_device *adev;
394         struct ttm_mem_reg *old_mem = &bo->mem;
395         struct ttm_mem_reg tmp_mem;
396         struct ttm_place placements;
397         struct ttm_placement placement;
398         int r;
399
400         adev = amdgpu_ttm_adev(bo->bdev);
401         tmp_mem = *new_mem;
402         tmp_mem.mm_node = NULL;
403         placement.num_placement = 1;
404         placement.placement = &placements;
405         placement.num_busy_placement = 1;
406         placement.busy_placement = &placements;
407         placements.fpfn = 0;
408         placements.lpfn = 0;
409         placements.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
410         r = ttm_bo_mem_space(bo, &placement, &tmp_mem,
411                              interruptible, no_wait_gpu);
412         if (unlikely(r)) {
413                 return r;
414         }
415
416         r = ttm_tt_set_placement_caching(bo->ttm, tmp_mem.placement);
417         if (unlikely(r)) {
418                 goto out_cleanup;
419         }
420
421         r = ttm_tt_bind(bo->ttm, &tmp_mem);
422         if (unlikely(r)) {
423                 goto out_cleanup;
424         }
425         r = amdgpu_move_blit(bo, true, no_wait_gpu, &tmp_mem, old_mem);
426         if (unlikely(r)) {
427                 goto out_cleanup;
428         }
429         r = ttm_bo_move_ttm(bo, interruptible, no_wait_gpu, new_mem);
430 out_cleanup:
431         ttm_bo_mem_put(bo, &tmp_mem);
432         return r;
433 }
434
435 static int amdgpu_move_ram_vram(struct ttm_buffer_object *bo,
436                                 bool evict, bool interruptible,
437                                 bool no_wait_gpu,
438                                 struct ttm_mem_reg *new_mem)
439 {
440         struct amdgpu_device *adev;
441         struct ttm_mem_reg *old_mem = &bo->mem;
442         struct ttm_mem_reg tmp_mem;
443         struct ttm_placement placement;
444         struct ttm_place placements;
445         int r;
446
447         adev = amdgpu_ttm_adev(bo->bdev);
448         tmp_mem = *new_mem;
449         tmp_mem.mm_node = NULL;
450         placement.num_placement = 1;
451         placement.placement = &placements;
452         placement.num_busy_placement = 1;
453         placement.busy_placement = &placements;
454         placements.fpfn = 0;
455         placements.lpfn = 0;
456         placements.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
457         r = ttm_bo_mem_space(bo, &placement, &tmp_mem,
458                              interruptible, no_wait_gpu);
459         if (unlikely(r)) {
460                 return r;
461         }
462         r = ttm_bo_move_ttm(bo, interruptible, no_wait_gpu, &tmp_mem);
463         if (unlikely(r)) {
464                 goto out_cleanup;
465         }
466         r = amdgpu_move_blit(bo, true, no_wait_gpu, new_mem, old_mem);
467         if (unlikely(r)) {
468                 goto out_cleanup;
469         }
470 out_cleanup:
471         ttm_bo_mem_put(bo, &tmp_mem);
472         return r;
473 }
474
475 static int amdgpu_bo_move(struct ttm_buffer_object *bo,
476                         bool evict, bool interruptible,
477                         bool no_wait_gpu,
478                         struct ttm_mem_reg *new_mem)
479 {
480         struct amdgpu_device *adev;
481         struct amdgpu_bo *abo;
482         struct ttm_mem_reg *old_mem = &bo->mem;
483         int r;
484
485         /* Can't move a pinned BO */
486         abo = container_of(bo, struct amdgpu_bo, tbo);
487         if (WARN_ON_ONCE(abo->pin_count > 0))
488                 return -EINVAL;
489
490         adev = amdgpu_ttm_adev(bo->bdev);
491
492         if (old_mem->mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
493                 amdgpu_move_null(bo, new_mem);
494                 return 0;
495         }
496         if ((old_mem->mem_type == TTM_PL_TT &&
497              new_mem->mem_type == TTM_PL_SYSTEM) ||
498             (old_mem->mem_type == TTM_PL_SYSTEM &&
499              new_mem->mem_type == TTM_PL_TT)) {
500                 /* bind is enough */
501                 amdgpu_move_null(bo, new_mem);
502                 return 0;
503         }
504         if (adev->mman.buffer_funcs == NULL ||
505             adev->mman.buffer_funcs_ring == NULL ||
506             !adev->mman.buffer_funcs_ring->ready) {
507                 /* use memcpy */
508                 goto memcpy;
509         }
510
511         if (old_mem->mem_type == TTM_PL_VRAM &&
512             new_mem->mem_type == TTM_PL_SYSTEM) {
513                 r = amdgpu_move_vram_ram(bo, evict, interruptible,
514                                         no_wait_gpu, new_mem);
515         } else if (old_mem->mem_type == TTM_PL_SYSTEM &&
516                    new_mem->mem_type == TTM_PL_VRAM) {
517                 r = amdgpu_move_ram_vram(bo, evict, interruptible,
518                                             no_wait_gpu, new_mem);
519         } else {
520                 r = amdgpu_move_blit(bo, evict, no_wait_gpu, new_mem, old_mem);
521         }
522
523         if (r) {
524 memcpy:
525                 r = ttm_bo_move_memcpy(bo, interruptible, no_wait_gpu, new_mem);
526                 if (r) {
527                         return r;
528                 }
529         }
530
531         if (bo->type == ttm_bo_type_device &&
532             new_mem->mem_type == TTM_PL_VRAM &&
533             old_mem->mem_type != TTM_PL_VRAM) {
534                 /* amdgpu_bo_fault_reserve_notify will re-set this if the CPU
535                  * accesses the BO after it's moved.
536                  */
537                 abo->flags &= ~AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
538         }
539
540         /* update statistics */
541         atomic64_add((u64)bo->num_pages << PAGE_SHIFT, &adev->num_bytes_moved);
542         return 0;
543 }
544
545 static int amdgpu_ttm_io_mem_reserve(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
546 {
547         struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
548         struct amdgpu_device *adev = amdgpu_ttm_adev(bdev);
549
550         mem->bus.addr = NULL;
551         mem->bus.offset = 0;
552         mem->bus.size = mem->num_pages << PAGE_SHIFT;
553         mem->bus.base = 0;
554         mem->bus.is_iomem = false;
555         if (!(man->flags & TTM_MEMTYPE_FLAG_MAPPABLE))
556                 return -EINVAL;
557         switch (mem->mem_type) {
558         case TTM_PL_SYSTEM:
559                 /* system memory */
560                 return 0;
561         case TTM_PL_TT:
562                 break;
563         case TTM_PL_VRAM:
564                 mem->bus.offset = mem->start << PAGE_SHIFT;
565                 /* check if it's visible */
566                 if ((mem->bus.offset + mem->bus.size) > adev->mc.visible_vram_size)
567                         return -EINVAL;
568                 mem->bus.base = adev->mc.aper_base;
569                 mem->bus.is_iomem = true;
570                 break;
571         default:
572                 return -EINVAL;
573         }
574         return 0;
575 }
576
577 static void amdgpu_ttm_io_mem_free(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
578 {
579 }
580
581 static unsigned long amdgpu_ttm_io_mem_pfn(struct ttm_buffer_object *bo,
582                                            unsigned long page_offset)
583 {
584         struct drm_mm_node *mm = bo->mem.mm_node;
585         uint64_t size = mm->size;
586         uint64_t offset = page_offset;
587
588         page_offset = do_div(offset, size);
589         mm += offset;
590         return (bo->mem.bus.base >> PAGE_SHIFT) + mm->start + page_offset;
591 }
592
593 /*
594  * TTM backend functions.
595  */
596 struct amdgpu_ttm_gup_task_list {
597         struct list_head        list;
598         struct task_struct      *task;
599 };
600
601 struct amdgpu_ttm_tt {
602         struct ttm_dma_tt       ttm;
603         struct amdgpu_device    *adev;
604         u64                     offset;
605         uint64_t                userptr;
606         struct mm_struct        *usermm;
607         uint32_t                userflags;
608         spinlock_t              guptasklock;
609         struct list_head        guptasks;
610         atomic_t                mmu_invalidations;
611         struct list_head        list;
612 };
613
614 int amdgpu_ttm_tt_get_user_pages(struct ttm_tt *ttm, struct page **pages)
615 {
616         struct amdgpu_ttm_tt *gtt = (void *)ttm;
617         unsigned int flags = 0;
618         unsigned pinned = 0;
619         int r;
620
621         if (!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY))
622                 flags |= FOLL_WRITE;
623
624         if (gtt->userflags & AMDGPU_GEM_USERPTR_ANONONLY) {
625                 /* check that we only use anonymous memory
626                    to prevent problems with writeback */
627                 unsigned long end = gtt->userptr + ttm->num_pages * PAGE_SIZE;
628                 struct vm_area_struct *vma;
629
630                 vma = find_vma(gtt->usermm, gtt->userptr);
631                 if (!vma || vma->vm_file || vma->vm_end < end)
632                         return -EPERM;
633         }
634
635         do {
636                 unsigned num_pages = ttm->num_pages - pinned;
637                 uint64_t userptr = gtt->userptr + pinned * PAGE_SIZE;
638                 struct page **p = pages + pinned;
639                 struct amdgpu_ttm_gup_task_list guptask;
640
641                 guptask.task = current;
642                 spin_lock(&gtt->guptasklock);
643                 list_add(&guptask.list, &gtt->guptasks);
644                 spin_unlock(&gtt->guptasklock);
645
646                 r = get_user_pages(userptr, num_pages, flags, p, NULL);
647
648                 spin_lock(&gtt->guptasklock);
649                 list_del(&guptask.list);
650                 spin_unlock(&gtt->guptasklock);
651
652                 if (r < 0)
653                         goto release_pages;
654
655                 pinned += r;
656
657         } while (pinned < ttm->num_pages);
658
659         return 0;
660
661 release_pages:
662         release_pages(pages, pinned, 0);
663         return r;
664 }
665
666 static void amdgpu_trace_dma_map(struct ttm_tt *ttm)
667 {
668         struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
669         struct amdgpu_ttm_tt *gtt = (void *)ttm;
670         unsigned i;
671
672         if (unlikely(trace_amdgpu_ttm_tt_populate_enabled())) {
673                 for (i = 0; i < ttm->num_pages; i++) {
674                         trace_amdgpu_ttm_tt_populate(
675                                 adev,
676                                 gtt->ttm.dma_address[i],
677                                 page_to_phys(ttm->pages[i]));
678                 }
679         }
680 }
681
682 static void amdgpu_trace_dma_unmap(struct ttm_tt *ttm)
683 {
684         struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
685         struct amdgpu_ttm_tt *gtt = (void *)ttm;
686         unsigned i;
687
688         if (unlikely(trace_amdgpu_ttm_tt_unpopulate_enabled())) {
689                 for (i = 0; i < ttm->num_pages; i++) {
690                         trace_amdgpu_ttm_tt_unpopulate(
691                                 adev,
692                                 gtt->ttm.dma_address[i],
693                                 page_to_phys(ttm->pages[i]));
694                 }
695         }
696 }
697
698 /* prepare the sg table with the user pages */
699 static int amdgpu_ttm_tt_pin_userptr(struct ttm_tt *ttm)
700 {
701         struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
702         struct amdgpu_ttm_tt *gtt = (void *)ttm;
703         unsigned nents;
704         int r;
705
706         int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
707         enum dma_data_direction direction = write ?
708                 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
709
710         r = sg_alloc_table_from_pages(ttm->sg, ttm->pages, ttm->num_pages, 0,
711                                       ttm->num_pages << PAGE_SHIFT,
712                                       GFP_KERNEL);
713         if (r)
714                 goto release_sg;
715
716         r = -ENOMEM;
717         nents = dma_map_sg(adev->dev, ttm->sg->sgl, ttm->sg->nents, direction);
718         if (nents != ttm->sg->nents)
719                 goto release_sg;
720
721         drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
722                                          gtt->ttm.dma_address, ttm->num_pages);
723
724         amdgpu_trace_dma_map(ttm);
725
726         return 0;
727
728 release_sg:
729         kfree(ttm->sg);
730         return r;
731 }
732
733 static void amdgpu_ttm_tt_unpin_userptr(struct ttm_tt *ttm)
734 {
735         struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
736         struct amdgpu_ttm_tt *gtt = (void *)ttm;
737         struct sg_page_iter sg_iter;
738
739         int write = !(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
740         enum dma_data_direction direction = write ?
741                 DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
742
743         /* double check that we don't free the table twice */
744         if (!ttm->sg->sgl)
745                 return;
746
747         /* free the sg table and pages again */
748         dma_unmap_sg(adev->dev, ttm->sg->sgl, ttm->sg->nents, direction);
749
750         for_each_sg_page(ttm->sg->sgl, &sg_iter, ttm->sg->nents, 0) {
751                 struct page *page = sg_page_iter_page(&sg_iter);
752                 if (!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY))
753                         set_page_dirty(page);
754
755                 mark_page_accessed(page);
756                 put_page(page);
757         }
758
759         amdgpu_trace_dma_unmap(ttm);
760
761         sg_free_table(ttm->sg);
762 }
763
764 static int amdgpu_ttm_do_bind(struct ttm_tt *ttm, struct ttm_mem_reg *mem)
765 {
766         struct amdgpu_ttm_tt *gtt = (void *)ttm;
767         uint64_t flags;
768         int r;
769
770         spin_lock(&gtt->adev->gtt_list_lock);
771         flags = amdgpu_ttm_tt_pte_flags(gtt->adev, ttm, mem);
772         gtt->offset = (u64)mem->start << PAGE_SHIFT;
773         r = amdgpu_gart_bind(gtt->adev, gtt->offset, ttm->num_pages,
774                 ttm->pages, gtt->ttm.dma_address, flags);
775
776         if (r) {
777                 DRM_ERROR("failed to bind %lu pages at 0x%08llX\n",
778                           ttm->num_pages, gtt->offset);
779                 goto error_gart_bind;
780         }
781
782         list_add_tail(&gtt->list, &gtt->adev->gtt_list);
783 error_gart_bind:
784         spin_unlock(&gtt->adev->gtt_list_lock);
785         return r;
786
787 }
788
789 static int amdgpu_ttm_backend_bind(struct ttm_tt *ttm,
790                                    struct ttm_mem_reg *bo_mem)
791 {
792         struct amdgpu_ttm_tt *gtt = (void*)ttm;
793         int r = 0;
794
795         if (gtt->userptr) {
796                 r = amdgpu_ttm_tt_pin_userptr(ttm);
797                 if (r) {
798                         DRM_ERROR("failed to pin userptr\n");
799                         return r;
800                 }
801         }
802         if (!ttm->num_pages) {
803                 WARN(1, "nothing to bind %lu pages for mreg %p back %p!\n",
804                      ttm->num_pages, bo_mem, ttm);
805         }
806
807         if (bo_mem->mem_type == AMDGPU_PL_GDS ||
808             bo_mem->mem_type == AMDGPU_PL_GWS ||
809             bo_mem->mem_type == AMDGPU_PL_OA)
810                 return -EINVAL;
811
812         if (amdgpu_gtt_mgr_is_allocated(bo_mem))
813             r = amdgpu_ttm_do_bind(ttm, bo_mem);
814
815         return r;
816 }
817
818 bool amdgpu_ttm_is_bound(struct ttm_tt *ttm)
819 {
820         struct amdgpu_ttm_tt *gtt = (void *)ttm;
821
822         return gtt && !list_empty(&gtt->list);
823 }
824
825 int amdgpu_ttm_bind(struct ttm_buffer_object *bo, struct ttm_mem_reg *bo_mem)
826 {
827         struct ttm_tt *ttm = bo->ttm;
828         int r;
829
830         if (!ttm || amdgpu_ttm_is_bound(ttm))
831                 return 0;
832
833         r = amdgpu_gtt_mgr_alloc(&bo->bdev->man[TTM_PL_TT], bo,
834                                  NULL, bo_mem);
835         if (r) {
836                 DRM_ERROR("Failed to allocate GTT address space (%d)\n", r);
837                 return r;
838         }
839
840         return amdgpu_ttm_do_bind(ttm, bo_mem);
841 }
842
843 int amdgpu_ttm_recover_gart(struct amdgpu_device *adev)
844 {
845         struct amdgpu_ttm_tt *gtt, *tmp;
846         struct ttm_mem_reg bo_mem;
847         uint64_t flags;
848         int r;
849
850         bo_mem.mem_type = TTM_PL_TT;
851         spin_lock(&adev->gtt_list_lock);
852         list_for_each_entry_safe(gtt, tmp, &adev->gtt_list, list) {
853                 flags = amdgpu_ttm_tt_pte_flags(gtt->adev, &gtt->ttm.ttm, &bo_mem);
854                 r = amdgpu_gart_bind(adev, gtt->offset, gtt->ttm.ttm.num_pages,
855                                      gtt->ttm.ttm.pages, gtt->ttm.dma_address,
856                                      flags);
857                 if (r) {
858                         spin_unlock(&adev->gtt_list_lock);
859                         DRM_ERROR("failed to bind %lu pages at 0x%08llX\n",
860                                   gtt->ttm.ttm.num_pages, gtt->offset);
861                         return r;
862                 }
863         }
864         spin_unlock(&adev->gtt_list_lock);
865         return 0;
866 }
867
868 static int amdgpu_ttm_backend_unbind(struct ttm_tt *ttm)
869 {
870         struct amdgpu_ttm_tt *gtt = (void *)ttm;
871         int r;
872
873         if (gtt->userptr)
874                 amdgpu_ttm_tt_unpin_userptr(ttm);
875
876         if (!amdgpu_ttm_is_bound(ttm))
877                 return 0;
878
879         /* unbind shouldn't be done for GDS/GWS/OA in ttm_bo_clean_mm */
880         spin_lock(&gtt->adev->gtt_list_lock);
881         r = amdgpu_gart_unbind(gtt->adev, gtt->offset, ttm->num_pages);
882         if (r) {
883                 DRM_ERROR("failed to unbind %lu pages at 0x%08llX\n",
884                           gtt->ttm.ttm.num_pages, gtt->offset);
885                 goto error_unbind;
886         }
887         list_del_init(&gtt->list);
888 error_unbind:
889         spin_unlock(&gtt->adev->gtt_list_lock);
890         return r;
891 }
892
893 static void amdgpu_ttm_backend_destroy(struct ttm_tt *ttm)
894 {
895         struct amdgpu_ttm_tt *gtt = (void *)ttm;
896
897         ttm_dma_tt_fini(&gtt->ttm);
898         kfree(gtt);
899 }
900
901 static struct ttm_backend_func amdgpu_backend_func = {
902         .bind = &amdgpu_ttm_backend_bind,
903         .unbind = &amdgpu_ttm_backend_unbind,
904         .destroy = &amdgpu_ttm_backend_destroy,
905 };
906
907 static struct ttm_tt *amdgpu_ttm_tt_create(struct ttm_bo_device *bdev,
908                                     unsigned long size, uint32_t page_flags,
909                                     struct page *dummy_read_page)
910 {
911         struct amdgpu_device *adev;
912         struct amdgpu_ttm_tt *gtt;
913
914         adev = amdgpu_ttm_adev(bdev);
915
916         gtt = kzalloc(sizeof(struct amdgpu_ttm_tt), GFP_KERNEL);
917         if (gtt == NULL) {
918                 return NULL;
919         }
920         gtt->ttm.ttm.func = &amdgpu_backend_func;
921         gtt->adev = adev;
922         if (ttm_dma_tt_init(&gtt->ttm, bdev, size, page_flags, dummy_read_page)) {
923                 kfree(gtt);
924                 return NULL;
925         }
926         INIT_LIST_HEAD(&gtt->list);
927         return &gtt->ttm.ttm;
928 }
929
930 static int amdgpu_ttm_tt_populate(struct ttm_tt *ttm)
931 {
932         struct amdgpu_device *adev = amdgpu_ttm_adev(ttm->bdev);
933         struct amdgpu_ttm_tt *gtt = (void *)ttm;
934         unsigned i;
935         int r;
936         bool slave = !!(ttm->page_flags & TTM_PAGE_FLAG_SG);
937
938         if (ttm->state != tt_unpopulated)
939                 return 0;
940
941         if (gtt && gtt->userptr) {
942                 ttm->sg = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
943                 if (!ttm->sg)
944                         return -ENOMEM;
945
946                 ttm->page_flags |= TTM_PAGE_FLAG_SG;
947                 ttm->state = tt_unbound;
948                 return 0;
949         }
950
951         if (slave && ttm->sg) {
952                 drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
953                                                  gtt->ttm.dma_address, ttm->num_pages);
954                 ttm->state = tt_unbound;
955                 r = 0;
956                 goto trace_mappings;
957         }
958
959 #ifdef CONFIG_SWIOTLB
960         if (swiotlb_nr_tbl()) {
961                 r = ttm_dma_populate(&gtt->ttm, adev->dev);
962                 goto trace_mappings;
963         }
964 #endif
965
966         r = ttm_pool_populate(ttm);
967         if (r) {
968                 return r;
969         }
970
971         for (i = 0; i < ttm->num_pages; i++) {
972                 gtt->ttm.dma_address[i] = pci_map_page(adev->pdev, ttm->pages[i],
973                                                        0, PAGE_SIZE,
974                                                        PCI_DMA_BIDIRECTIONAL);
975                 if (pci_dma_mapping_error(adev->pdev, gtt->ttm.dma_address[i])) {
976                         while (i--) {
977                                 pci_unmap_page(adev->pdev, gtt->ttm.dma_address[i],
978                                                PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
979                                 gtt->ttm.dma_address[i] = 0;
980                         }
981                         ttm_pool_unpopulate(ttm);
982                         return -EFAULT;
983                 }
984         }
985
986         r = 0;
987 trace_mappings:
988         if (likely(!r))
989                 amdgpu_trace_dma_map(ttm);
990         return r;
991 }
992
993 static void amdgpu_ttm_tt_unpopulate(struct ttm_tt *ttm)
994 {
995         struct amdgpu_device *adev;
996         struct amdgpu_ttm_tt *gtt = (void *)ttm;
997         unsigned i;
998         bool slave = !!(ttm->page_flags & TTM_PAGE_FLAG_SG);
999
1000         if (gtt && gtt->userptr) {
1001                 kfree(ttm->sg);
1002                 ttm->page_flags &= ~TTM_PAGE_FLAG_SG;
1003                 return;
1004         }
1005
1006         if (slave)
1007                 return;
1008
1009         adev = amdgpu_ttm_adev(ttm->bdev);
1010
1011         amdgpu_trace_dma_unmap(ttm);
1012
1013 #ifdef CONFIG_SWIOTLB
1014         if (swiotlb_nr_tbl()) {
1015                 ttm_dma_unpopulate(&gtt->ttm, adev->dev);
1016                 return;
1017         }
1018 #endif
1019
1020         for (i = 0; i < ttm->num_pages; i++) {
1021                 if (gtt->ttm.dma_address[i]) {
1022                         pci_unmap_page(adev->pdev, gtt->ttm.dma_address[i],
1023                                        PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
1024                 }
1025         }
1026
1027         ttm_pool_unpopulate(ttm);
1028 }
1029
1030 int amdgpu_ttm_tt_set_userptr(struct ttm_tt *ttm, uint64_t addr,
1031                               uint32_t flags)
1032 {
1033         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1034
1035         if (gtt == NULL)
1036                 return -EINVAL;
1037
1038         gtt->userptr = addr;
1039         gtt->usermm = current->mm;
1040         gtt->userflags = flags;
1041         spin_lock_init(&gtt->guptasklock);
1042         INIT_LIST_HEAD(&gtt->guptasks);
1043         atomic_set(&gtt->mmu_invalidations, 0);
1044
1045         return 0;
1046 }
1047
1048 struct mm_struct *amdgpu_ttm_tt_get_usermm(struct ttm_tt *ttm)
1049 {
1050         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1051
1052         if (gtt == NULL)
1053                 return NULL;
1054
1055         return gtt->usermm;
1056 }
1057
1058 bool amdgpu_ttm_tt_affect_userptr(struct ttm_tt *ttm, unsigned long start,
1059                                   unsigned long end)
1060 {
1061         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1062         struct amdgpu_ttm_gup_task_list *entry;
1063         unsigned long size;
1064
1065         if (gtt == NULL || !gtt->userptr)
1066                 return false;
1067
1068         size = (unsigned long)gtt->ttm.ttm.num_pages * PAGE_SIZE;
1069         if (gtt->userptr > end || gtt->userptr + size <= start)
1070                 return false;
1071
1072         spin_lock(&gtt->guptasklock);
1073         list_for_each_entry(entry, &gtt->guptasks, list) {
1074                 if (entry->task == current) {
1075                         spin_unlock(&gtt->guptasklock);
1076                         return false;
1077                 }
1078         }
1079         spin_unlock(&gtt->guptasklock);
1080
1081         atomic_inc(&gtt->mmu_invalidations);
1082
1083         return true;
1084 }
1085
1086 bool amdgpu_ttm_tt_userptr_invalidated(struct ttm_tt *ttm,
1087                                        int *last_invalidated)
1088 {
1089         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1090         int prev_invalidated = *last_invalidated;
1091
1092         *last_invalidated = atomic_read(&gtt->mmu_invalidations);
1093         return prev_invalidated != *last_invalidated;
1094 }
1095
1096 bool amdgpu_ttm_tt_is_readonly(struct ttm_tt *ttm)
1097 {
1098         struct amdgpu_ttm_tt *gtt = (void *)ttm;
1099
1100         if (gtt == NULL)
1101                 return false;
1102
1103         return !!(gtt->userflags & AMDGPU_GEM_USERPTR_READONLY);
1104 }
1105
1106 uint64_t amdgpu_ttm_tt_pte_flags(struct amdgpu_device *adev, struct ttm_tt *ttm,
1107                                  struct ttm_mem_reg *mem)
1108 {
1109         uint64_t flags = 0;
1110
1111         if (mem && mem->mem_type != TTM_PL_SYSTEM)
1112                 flags |= AMDGPU_PTE_VALID;
1113
1114         if (mem && mem->mem_type == TTM_PL_TT) {
1115                 flags |= AMDGPU_PTE_SYSTEM;
1116
1117                 if (ttm->caching_state == tt_cached)
1118                         flags |= AMDGPU_PTE_SNOOPED;
1119         }
1120
1121         flags |= adev->gart.gart_pte_flags;
1122         flags |= AMDGPU_PTE_READABLE;
1123
1124         if (!amdgpu_ttm_tt_is_readonly(ttm))
1125                 flags |= AMDGPU_PTE_WRITEABLE;
1126
1127         return flags;
1128 }
1129
1130 static bool amdgpu_ttm_bo_eviction_valuable(struct ttm_buffer_object *bo,
1131                                             const struct ttm_place *place)
1132 {
1133         unsigned long num_pages = bo->mem.num_pages;
1134         struct drm_mm_node *node = bo->mem.mm_node;
1135
1136         if (bo->mem.start != AMDGPU_BO_INVALID_OFFSET)
1137                 return ttm_bo_eviction_valuable(bo, place);
1138
1139         switch (bo->mem.mem_type) {
1140         case TTM_PL_TT:
1141                 return true;
1142
1143         case TTM_PL_VRAM:
1144                 /* Check each drm MM node individually */
1145                 while (num_pages) {
1146                         if (place->fpfn < (node->start + node->size) &&
1147                             !(place->lpfn && place->lpfn <= node->start))
1148                                 return true;
1149
1150                         num_pages -= node->size;
1151                         ++node;
1152                 }
1153                 break;
1154
1155         default:
1156                 break;
1157         }
1158
1159         return ttm_bo_eviction_valuable(bo, place);
1160 }
1161
1162 static int amdgpu_ttm_access_memory(struct ttm_buffer_object *bo,
1163                                     unsigned long offset,
1164                                     void *buf, int len, int write)
1165 {
1166         struct amdgpu_bo *abo = container_of(bo, struct amdgpu_bo, tbo);
1167         struct amdgpu_device *adev = amdgpu_ttm_adev(abo->tbo.bdev);
1168         struct drm_mm_node *nodes = abo->tbo.mem.mm_node;
1169         uint32_t value = 0;
1170         int ret = 0;
1171         uint64_t pos;
1172         unsigned long flags;
1173
1174         if (bo->mem.mem_type != TTM_PL_VRAM)
1175                 return -EIO;
1176
1177         while (offset >= (nodes->size << PAGE_SHIFT)) {
1178                 offset -= nodes->size << PAGE_SHIFT;
1179                 ++nodes;
1180         }
1181         pos = (nodes->start << PAGE_SHIFT) + offset;
1182
1183         while (len && pos < adev->mc.mc_vram_size) {
1184                 uint64_t aligned_pos = pos & ~(uint64_t)3;
1185                 uint32_t bytes = 4 - (pos & 3);
1186                 uint32_t shift = (pos & 3) * 8;
1187                 uint32_t mask = 0xffffffff << shift;
1188
1189                 if (len < bytes) {
1190                         mask &= 0xffffffff >> (bytes - len) * 8;
1191                         bytes = len;
1192                 }
1193
1194                 spin_lock_irqsave(&adev->mmio_idx_lock, flags);
1195                 WREG32(mmMM_INDEX, ((uint32_t)aligned_pos) | 0x80000000);
1196                 WREG32(mmMM_INDEX_HI, aligned_pos >> 31);
1197                 if (!write || mask != 0xffffffff)
1198                         value = RREG32(mmMM_DATA);
1199                 if (write) {
1200                         value &= ~mask;
1201                         value |= (*(uint32_t *)buf << shift) & mask;
1202                         WREG32(mmMM_DATA, value);
1203                 }
1204                 spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
1205                 if (!write) {
1206                         value = (value & mask) >> shift;
1207                         memcpy(buf, &value, bytes);
1208                 }
1209
1210                 ret += bytes;
1211                 buf = (uint8_t *)buf + bytes;
1212                 pos += bytes;
1213                 len -= bytes;
1214                 if (pos >= (nodes->start + nodes->size) << PAGE_SHIFT) {
1215                         ++nodes;
1216                         pos = (nodes->start << PAGE_SHIFT);
1217                 }
1218         }
1219
1220         return ret;
1221 }
1222
1223 static struct ttm_bo_driver amdgpu_bo_driver = {
1224         .ttm_tt_create = &amdgpu_ttm_tt_create,
1225         .ttm_tt_populate = &amdgpu_ttm_tt_populate,
1226         .ttm_tt_unpopulate = &amdgpu_ttm_tt_unpopulate,
1227         .invalidate_caches = &amdgpu_invalidate_caches,
1228         .init_mem_type = &amdgpu_init_mem_type,
1229         .eviction_valuable = amdgpu_ttm_bo_eviction_valuable,
1230         .evict_flags = &amdgpu_evict_flags,
1231         .move = &amdgpu_bo_move,
1232         .verify_access = &amdgpu_verify_access,
1233         .move_notify = &amdgpu_bo_move_notify,
1234         .fault_reserve_notify = &amdgpu_bo_fault_reserve_notify,
1235         .io_mem_reserve = &amdgpu_ttm_io_mem_reserve,
1236         .io_mem_free = &amdgpu_ttm_io_mem_free,
1237         .io_mem_pfn = amdgpu_ttm_io_mem_pfn,
1238         .access_memory = &amdgpu_ttm_access_memory
1239 };
1240
1241 int amdgpu_ttm_init(struct amdgpu_device *adev)
1242 {
1243         uint64_t gtt_size;
1244         int r;
1245         u64 vis_vram_limit;
1246
1247         r = amdgpu_ttm_global_init(adev);
1248         if (r) {
1249                 return r;
1250         }
1251         /* No others user of address space so set it to 0 */
1252         r = ttm_bo_device_init(&adev->mman.bdev,
1253                                adev->mman.bo_global_ref.ref.object,
1254                                &amdgpu_bo_driver,
1255                                adev->ddev->anon_inode->i_mapping,
1256                                DRM_FILE_PAGE_OFFSET,
1257                                adev->need_dma32);
1258         if (r) {
1259                 DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
1260                 return r;
1261         }
1262         adev->mman.initialized = true;
1263         r = ttm_bo_init_mm(&adev->mman.bdev, TTM_PL_VRAM,
1264                                 adev->mc.real_vram_size >> PAGE_SHIFT);
1265         if (r) {
1266                 DRM_ERROR("Failed initializing VRAM heap.\n");
1267                 return r;
1268         }
1269
1270         /* Reduce size of CPU-visible VRAM if requested */
1271         vis_vram_limit = (u64)amdgpu_vis_vram_limit * 1024 * 1024;
1272         if (amdgpu_vis_vram_limit > 0 &&
1273             vis_vram_limit <= adev->mc.visible_vram_size)
1274                 adev->mc.visible_vram_size = vis_vram_limit;
1275
1276         /* Change the size here instead of the init above so only lpfn is affected */
1277         amdgpu_ttm_set_active_vram_size(adev, adev->mc.visible_vram_size);
1278
1279         r = amdgpu_bo_create_kernel(adev, adev->mc.stolen_size, PAGE_SIZE,
1280                                     AMDGPU_GEM_DOMAIN_VRAM,
1281                                     &adev->stolen_vga_memory,
1282                                     NULL, NULL);
1283         if (r)
1284                 return r;
1285         DRM_INFO("amdgpu: %uM of VRAM memory ready\n",
1286                  (unsigned) (adev->mc.real_vram_size / (1024 * 1024)));
1287
1288         if (amdgpu_gtt_size == -1)
1289                 gtt_size = max((AMDGPU_DEFAULT_GTT_SIZE_MB << 20),
1290                                adev->mc.mc_vram_size);
1291         else
1292                 gtt_size = (uint64_t)amdgpu_gtt_size << 20;
1293         r = ttm_bo_init_mm(&adev->mman.bdev, TTM_PL_TT, gtt_size >> PAGE_SHIFT);
1294         if (r) {
1295                 DRM_ERROR("Failed initializing GTT heap.\n");
1296                 return r;
1297         }
1298         DRM_INFO("amdgpu: %uM of GTT memory ready.\n",
1299                  (unsigned)(gtt_size / (1024 * 1024)));
1300
1301         adev->gds.mem.total_size = adev->gds.mem.total_size << AMDGPU_GDS_SHIFT;
1302         adev->gds.mem.gfx_partition_size = adev->gds.mem.gfx_partition_size << AMDGPU_GDS_SHIFT;
1303         adev->gds.mem.cs_partition_size = adev->gds.mem.cs_partition_size << AMDGPU_GDS_SHIFT;
1304         adev->gds.gws.total_size = adev->gds.gws.total_size << AMDGPU_GWS_SHIFT;
1305         adev->gds.gws.gfx_partition_size = adev->gds.gws.gfx_partition_size << AMDGPU_GWS_SHIFT;
1306         adev->gds.gws.cs_partition_size = adev->gds.gws.cs_partition_size << AMDGPU_GWS_SHIFT;
1307         adev->gds.oa.total_size = adev->gds.oa.total_size << AMDGPU_OA_SHIFT;
1308         adev->gds.oa.gfx_partition_size = adev->gds.oa.gfx_partition_size << AMDGPU_OA_SHIFT;
1309         adev->gds.oa.cs_partition_size = adev->gds.oa.cs_partition_size << AMDGPU_OA_SHIFT;
1310         /* GDS Memory */
1311         if (adev->gds.mem.total_size) {
1312                 r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_GDS,
1313                                    adev->gds.mem.total_size >> PAGE_SHIFT);
1314                 if (r) {
1315                         DRM_ERROR("Failed initializing GDS heap.\n");
1316                         return r;
1317                 }
1318         }
1319
1320         /* GWS */
1321         if (adev->gds.gws.total_size) {
1322                 r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_GWS,
1323                                    adev->gds.gws.total_size >> PAGE_SHIFT);
1324                 if (r) {
1325                         DRM_ERROR("Failed initializing gws heap.\n");
1326                         return r;
1327                 }
1328         }
1329
1330         /* OA */
1331         if (adev->gds.oa.total_size) {
1332                 r = ttm_bo_init_mm(&adev->mman.bdev, AMDGPU_PL_OA,
1333                                    adev->gds.oa.total_size >> PAGE_SHIFT);
1334                 if (r) {
1335                         DRM_ERROR("Failed initializing oa heap.\n");
1336                         return r;
1337                 }
1338         }
1339
1340         r = amdgpu_ttm_debugfs_init(adev);
1341         if (r) {
1342                 DRM_ERROR("Failed to init debugfs\n");
1343                 return r;
1344         }
1345         return 0;
1346 }
1347
1348 void amdgpu_ttm_fini(struct amdgpu_device *adev)
1349 {
1350         int r;
1351
1352         if (!adev->mman.initialized)
1353                 return;
1354         amdgpu_ttm_debugfs_fini(adev);
1355         if (adev->stolen_vga_memory) {
1356                 r = amdgpu_bo_reserve(adev->stolen_vga_memory, true);
1357                 if (r == 0) {
1358                         amdgpu_bo_unpin(adev->stolen_vga_memory);
1359                         amdgpu_bo_unreserve(adev->stolen_vga_memory);
1360                 }
1361                 amdgpu_bo_unref(&adev->stolen_vga_memory);
1362         }
1363         ttm_bo_clean_mm(&adev->mman.bdev, TTM_PL_VRAM);
1364         ttm_bo_clean_mm(&adev->mman.bdev, TTM_PL_TT);
1365         if (adev->gds.mem.total_size)
1366                 ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_GDS);
1367         if (adev->gds.gws.total_size)
1368                 ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_GWS);
1369         if (adev->gds.oa.total_size)
1370                 ttm_bo_clean_mm(&adev->mman.bdev, AMDGPU_PL_OA);
1371         ttm_bo_device_release(&adev->mman.bdev);
1372         amdgpu_gart_fini(adev);
1373         amdgpu_ttm_global_fini(adev);
1374         adev->mman.initialized = false;
1375         DRM_INFO("amdgpu: ttm finalized\n");
1376 }
1377
1378 /* this should only be called at bootup or when userspace
1379  * isn't running */
1380 void amdgpu_ttm_set_active_vram_size(struct amdgpu_device *adev, u64 size)
1381 {
1382         struct ttm_mem_type_manager *man;
1383
1384         if (!adev->mman.initialized)
1385                 return;
1386
1387         man = &adev->mman.bdev.man[TTM_PL_VRAM];
1388         /* this just adjusts TTM size idea, which sets lpfn to the correct value */
1389         man->size = size >> PAGE_SHIFT;
1390 }
1391
1392 int amdgpu_mmap(struct file *filp, struct vm_area_struct *vma)
1393 {
1394         struct drm_file *file_priv;
1395         struct amdgpu_device *adev;
1396
1397         if (unlikely(vma->vm_pgoff < DRM_FILE_PAGE_OFFSET))
1398                 return -EINVAL;
1399
1400         file_priv = filp->private_data;
1401         adev = file_priv->minor->dev->dev_private;
1402         if (adev == NULL)
1403                 return -EINVAL;
1404
1405         return ttm_bo_mmap(filp, vma, &adev->mman.bdev);
1406 }
1407
1408 static int amdgpu_map_buffer(struct ttm_buffer_object *bo,
1409                              struct ttm_mem_reg *mem, unsigned num_pages,
1410                              uint64_t offset, unsigned window,
1411                              struct amdgpu_ring *ring,
1412                              uint64_t *addr)
1413 {
1414         struct amdgpu_ttm_tt *gtt = (void *)bo->ttm;
1415         struct amdgpu_device *adev = ring->adev;
1416         struct ttm_tt *ttm = bo->ttm;
1417         struct amdgpu_job *job;
1418         unsigned num_dw, num_bytes;
1419         dma_addr_t *dma_address;
1420         struct dma_fence *fence;
1421         uint64_t src_addr, dst_addr;
1422         uint64_t flags;
1423         int r;
1424
1425         BUG_ON(adev->mman.buffer_funcs->copy_max_bytes <
1426                AMDGPU_GTT_MAX_TRANSFER_SIZE * 8);
1427
1428         *addr = adev->mc.gart_start;
1429         *addr += (u64)window * AMDGPU_GTT_MAX_TRANSFER_SIZE *
1430                 AMDGPU_GPU_PAGE_SIZE;
1431
1432         num_dw = adev->mman.buffer_funcs->copy_num_dw;
1433         while (num_dw & 0x7)
1434                 num_dw++;
1435
1436         num_bytes = num_pages * 8;
1437
1438         r = amdgpu_job_alloc_with_ib(adev, num_dw * 4 + num_bytes, &job);
1439         if (r)
1440                 return r;
1441
1442         src_addr = num_dw * 4;
1443         src_addr += job->ibs[0].gpu_addr;
1444
1445         dst_addr = adev->gart.table_addr;
1446         dst_addr += window * AMDGPU_GTT_MAX_TRANSFER_SIZE * 8;
1447         amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
1448                                 dst_addr, num_bytes);
1449
1450         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
1451         WARN_ON(job->ibs[0].length_dw > num_dw);
1452
1453         dma_address = &gtt->ttm.dma_address[offset >> PAGE_SHIFT];
1454         flags = amdgpu_ttm_tt_pte_flags(adev, ttm, mem);
1455         r = amdgpu_gart_map(adev, 0, num_pages, dma_address, flags,
1456                             &job->ibs[0].ptr[num_dw]);
1457         if (r)
1458                 goto error_free;
1459
1460         r = amdgpu_job_submit(job, ring, &adev->mman.entity,
1461                               AMDGPU_FENCE_OWNER_UNDEFINED, &fence);
1462         if (r)
1463                 goto error_free;
1464
1465         dma_fence_put(fence);
1466
1467         return r;
1468
1469 error_free:
1470         amdgpu_job_free(job);
1471         return r;
1472 }
1473
1474 int amdgpu_copy_buffer(struct amdgpu_ring *ring, uint64_t src_offset,
1475                        uint64_t dst_offset, uint32_t byte_count,
1476                        struct reservation_object *resv,
1477                        struct dma_fence **fence, bool direct_submit,
1478                        bool vm_needs_flush)
1479 {
1480         struct amdgpu_device *adev = ring->adev;
1481         struct amdgpu_job *job;
1482
1483         uint32_t max_bytes;
1484         unsigned num_loops, num_dw;
1485         unsigned i;
1486         int r;
1487
1488         max_bytes = adev->mman.buffer_funcs->copy_max_bytes;
1489         num_loops = DIV_ROUND_UP(byte_count, max_bytes);
1490         num_dw = num_loops * adev->mman.buffer_funcs->copy_num_dw;
1491
1492         /* for IB padding */
1493         while (num_dw & 0x7)
1494                 num_dw++;
1495
1496         r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, &job);
1497         if (r)
1498                 return r;
1499
1500         job->vm_needs_flush = vm_needs_flush;
1501         if (resv) {
1502                 r = amdgpu_sync_resv(adev, &job->sync, resv,
1503                                      AMDGPU_FENCE_OWNER_UNDEFINED);
1504                 if (r) {
1505                         DRM_ERROR("sync failed (%d).\n", r);
1506                         goto error_free;
1507                 }
1508         }
1509
1510         for (i = 0; i < num_loops; i++) {
1511                 uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
1512
1513                 amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_offset,
1514                                         dst_offset, cur_size_in_bytes);
1515
1516                 src_offset += cur_size_in_bytes;
1517                 dst_offset += cur_size_in_bytes;
1518                 byte_count -= cur_size_in_bytes;
1519         }
1520
1521         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
1522         WARN_ON(job->ibs[0].length_dw > num_dw);
1523         if (direct_submit) {
1524                 r = amdgpu_ib_schedule(ring, job->num_ibs, job->ibs,
1525                                        NULL, fence);
1526                 job->fence = dma_fence_get(*fence);
1527                 if (r)
1528                         DRM_ERROR("Error scheduling IBs (%d)\n", r);
1529                 amdgpu_job_free(job);
1530         } else {
1531                 r = amdgpu_job_submit(job, ring, &adev->mman.entity,
1532                                       AMDGPU_FENCE_OWNER_UNDEFINED, fence);
1533                 if (r)
1534                         goto error_free;
1535         }
1536
1537         return r;
1538
1539 error_free:
1540         amdgpu_job_free(job);
1541         return r;
1542 }
1543
1544 int amdgpu_fill_buffer(struct amdgpu_bo *bo,
1545                        uint64_t src_data,
1546                        struct reservation_object *resv,
1547                        struct dma_fence **fence)
1548 {
1549         struct amdgpu_device *adev = amdgpu_ttm_adev(bo->tbo.bdev);
1550         /* max_bytes applies to SDMA_OP_PTEPDE as well as SDMA_OP_CONST_FILL*/
1551         uint32_t max_bytes = adev->mman.buffer_funcs->fill_max_bytes;
1552         struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
1553
1554         struct drm_mm_node *mm_node;
1555         unsigned long num_pages;
1556         unsigned int num_loops, num_dw;
1557
1558         struct amdgpu_job *job;
1559         int r;
1560
1561         if (!ring->ready) {
1562                 DRM_ERROR("Trying to clear memory with ring turned off.\n");
1563                 return -EINVAL;
1564         }
1565
1566         if (bo->tbo.mem.mem_type == TTM_PL_TT) {
1567                 r = amdgpu_ttm_bind(&bo->tbo, &bo->tbo.mem);
1568                 if (r)
1569                         return r;
1570         }
1571
1572         num_pages = bo->tbo.num_pages;
1573         mm_node = bo->tbo.mem.mm_node;
1574         num_loops = 0;
1575         while (num_pages) {
1576                 uint32_t byte_count = mm_node->size << PAGE_SHIFT;
1577
1578                 num_loops += DIV_ROUND_UP(byte_count, max_bytes);
1579                 num_pages -= mm_node->size;
1580                 ++mm_node;
1581         }
1582
1583         /* 10 double words for each SDMA_OP_PTEPDE cmd */
1584         num_dw = num_loops * 10;
1585
1586         /* for IB padding */
1587         num_dw += 64;
1588
1589         r = amdgpu_job_alloc_with_ib(adev, num_dw * 4, &job);
1590         if (r)
1591                 return r;
1592
1593         if (resv) {
1594                 r = amdgpu_sync_resv(adev, &job->sync, resv,
1595                                      AMDGPU_FENCE_OWNER_UNDEFINED);
1596                 if (r) {
1597                         DRM_ERROR("sync failed (%d).\n", r);
1598                         goto error_free;
1599                 }
1600         }
1601
1602         num_pages = bo->tbo.num_pages;
1603         mm_node = bo->tbo.mem.mm_node;
1604
1605         while (num_pages) {
1606                 uint32_t byte_count = mm_node->size << PAGE_SHIFT;
1607                 uint64_t dst_addr;
1608
1609                 WARN_ONCE(byte_count & 0x7, "size should be a multiple of 8");
1610
1611                 dst_addr = amdgpu_mm_node_addr(&bo->tbo, mm_node, &bo->tbo.mem);
1612                 while (byte_count) {
1613                         uint32_t cur_size_in_bytes = min(byte_count, max_bytes);
1614
1615                         amdgpu_vm_set_pte_pde(adev, &job->ibs[0],
1616                                         dst_addr, 0,
1617                                         cur_size_in_bytes >> 3, 0,
1618                                         src_data);
1619
1620                         dst_addr += cur_size_in_bytes;
1621                         byte_count -= cur_size_in_bytes;
1622                 }
1623
1624                 num_pages -= mm_node->size;
1625                 ++mm_node;
1626         }
1627
1628         amdgpu_ring_pad_ib(ring, &job->ibs[0]);
1629         WARN_ON(job->ibs[0].length_dw > num_dw);
1630         r = amdgpu_job_submit(job, ring, &adev->mman.entity,
1631                               AMDGPU_FENCE_OWNER_UNDEFINED, fence);
1632         if (r)
1633                 goto error_free;
1634
1635         return 0;
1636
1637 error_free:
1638         amdgpu_job_free(job);
1639         return r;
1640 }
1641
1642 #if defined(CONFIG_DEBUG_FS)
1643
1644 static int amdgpu_mm_dump_table(struct seq_file *m, void *data)
1645 {
1646         struct drm_info_node *node = (struct drm_info_node *)m->private;
1647         unsigned ttm_pl = *(int *)node->info_ent->data;
1648         struct drm_device *dev = node->minor->dev;
1649         struct amdgpu_device *adev = dev->dev_private;
1650         struct ttm_mem_type_manager *man = &adev->mman.bdev.man[ttm_pl];
1651         struct drm_printer p = drm_seq_file_printer(m);
1652
1653         man->func->debug(man, &p);
1654         return 0;
1655 }
1656
1657 static int ttm_pl_vram = TTM_PL_VRAM;
1658 static int ttm_pl_tt = TTM_PL_TT;
1659
1660 static const struct drm_info_list amdgpu_ttm_debugfs_list[] = {
1661         {"amdgpu_vram_mm", amdgpu_mm_dump_table, 0, &ttm_pl_vram},
1662         {"amdgpu_gtt_mm", amdgpu_mm_dump_table, 0, &ttm_pl_tt},
1663         {"ttm_page_pool", ttm_page_alloc_debugfs, 0, NULL},
1664 #ifdef CONFIG_SWIOTLB
1665         {"ttm_dma_page_pool", ttm_dma_page_alloc_debugfs, 0, NULL}
1666 #endif
1667 };
1668
1669 static ssize_t amdgpu_ttm_vram_read(struct file *f, char __user *buf,
1670                                     size_t size, loff_t *pos)
1671 {
1672         struct amdgpu_device *adev = file_inode(f)->i_private;
1673         ssize_t result = 0;
1674         int r;
1675
1676         if (size & 0x3 || *pos & 0x3)
1677                 return -EINVAL;
1678
1679         if (*pos >= adev->mc.mc_vram_size)
1680                 return -ENXIO;
1681
1682         while (size) {
1683                 unsigned long flags;
1684                 uint32_t value;
1685
1686                 if (*pos >= adev->mc.mc_vram_size)
1687                         return result;
1688
1689                 spin_lock_irqsave(&adev->mmio_idx_lock, flags);
1690                 WREG32(mmMM_INDEX, ((uint32_t)*pos) | 0x80000000);
1691                 WREG32(mmMM_INDEX_HI, *pos >> 31);
1692                 value = RREG32(mmMM_DATA);
1693                 spin_unlock_irqrestore(&adev->mmio_idx_lock, flags);
1694
1695                 r = put_user(value, (uint32_t *)buf);
1696                 if (r)
1697                         return r;
1698
1699                 result += 4;
1700                 buf += 4;
1701                 *pos += 4;
1702                 size -= 4;
1703         }
1704
1705         return result;
1706 }
1707
1708 static const struct file_operations amdgpu_ttm_vram_fops = {
1709         .owner = THIS_MODULE,
1710         .read = amdgpu_ttm_vram_read,
1711         .llseek = default_llseek
1712 };
1713
1714 #ifdef CONFIG_DRM_AMDGPU_GART_DEBUGFS
1715
1716 static ssize_t amdgpu_ttm_gtt_read(struct file *f, char __user *buf,
1717                                    size_t size, loff_t *pos)
1718 {
1719         struct amdgpu_device *adev = file_inode(f)->i_private;
1720         ssize_t result = 0;
1721         int r;
1722
1723         while (size) {
1724                 loff_t p = *pos / PAGE_SIZE;
1725                 unsigned off = *pos & ~PAGE_MASK;
1726                 size_t cur_size = min_t(size_t, size, PAGE_SIZE - off);
1727                 struct page *page;
1728                 void *ptr;
1729
1730                 if (p >= adev->gart.num_cpu_pages)
1731                         return result;
1732
1733                 page = adev->gart.pages[p];
1734                 if (page) {
1735                         ptr = kmap(page);
1736                         ptr += off;
1737
1738                         r = copy_to_user(buf, ptr, cur_size);
1739                         kunmap(adev->gart.pages[p]);
1740                 } else
1741                         r = clear_user(buf, cur_size);
1742
1743                 if (r)
1744                         return -EFAULT;
1745
1746                 result += cur_size;
1747                 buf += cur_size;
1748                 *pos += cur_size;
1749                 size -= cur_size;
1750         }
1751
1752         return result;
1753 }
1754
1755 static const struct file_operations amdgpu_ttm_gtt_fops = {
1756         .owner = THIS_MODULE,
1757         .read = amdgpu_ttm_gtt_read,
1758         .llseek = default_llseek
1759 };
1760
1761 #endif
1762
1763 #endif
1764
1765 static int amdgpu_ttm_debugfs_init(struct amdgpu_device *adev)
1766 {
1767 #if defined(CONFIG_DEBUG_FS)
1768         unsigned count;
1769
1770         struct drm_minor *minor = adev->ddev->primary;
1771         struct dentry *ent, *root = minor->debugfs_root;
1772
1773         ent = debugfs_create_file("amdgpu_vram", S_IFREG | S_IRUGO, root,
1774                                   adev, &amdgpu_ttm_vram_fops);
1775         if (IS_ERR(ent))
1776                 return PTR_ERR(ent);
1777         i_size_write(ent->d_inode, adev->mc.mc_vram_size);
1778         adev->mman.vram = ent;
1779
1780 #ifdef CONFIG_DRM_AMDGPU_GART_DEBUGFS
1781         ent = debugfs_create_file("amdgpu_gtt", S_IFREG | S_IRUGO, root,
1782                                   adev, &amdgpu_ttm_gtt_fops);
1783         if (IS_ERR(ent))
1784                 return PTR_ERR(ent);
1785         i_size_write(ent->d_inode, adev->mc.gart_size);
1786         adev->mman.gtt = ent;
1787
1788 #endif
1789         count = ARRAY_SIZE(amdgpu_ttm_debugfs_list);
1790
1791 #ifdef CONFIG_SWIOTLB
1792         if (!swiotlb_nr_tbl())
1793                 --count;
1794 #endif
1795
1796         return amdgpu_debugfs_add_files(adev, amdgpu_ttm_debugfs_list, count);
1797 #else
1798
1799         return 0;
1800 #endif
1801 }
1802
1803 static void amdgpu_ttm_debugfs_fini(struct amdgpu_device *adev)
1804 {
1805 #if defined(CONFIG_DEBUG_FS)
1806
1807         debugfs_remove(adev->mman.vram);
1808         adev->mman.vram = NULL;
1809
1810 #ifdef CONFIG_DRM_AMDGPU_GART_DEBUGFS
1811         debugfs_remove(adev->mman.gtt);
1812         adev->mman.gtt = NULL;
1813 #endif
1814
1815 #endif
1816 }