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 <ttm/ttm_bo_api.h>
33#include <ttm/ttm_bo_driver.h>
34#include <ttm/ttm_placement.h>
35#include <ttm/ttm_module.h>
36#include <ttm/ttm_page_alloc.h>
37#include <drm/drmP.h>
38#include <drm/radeon_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 "radeon_reg.h"
46#include "radeon.h"
47
48#define DRM_FILE_PAGE_OFFSET (0x100000000ULL >> PAGE_SHIFT)
49
50static int radeon_ttm_debugfs_init(struct radeon_device *rdev);
51static void radeon_ttm_debugfs_fini(struct radeon_device *rdev);
52
53static struct radeon_device *radeon_get_rdev(struct ttm_bo_device *bdev)
54{
55	struct radeon_mman *mman;
56	struct radeon_device *rdev;
57
58	mman = container_of(bdev, struct radeon_mman, bdev);
59	rdev = container_of(mman, struct radeon_device, mman);
60	return rdev;
61}
62
63
64/*
65 * Global memory.
66 */
67static int radeon_ttm_mem_global_init(struct drm_global_reference *ref)
68{
69	return ttm_mem_global_init(ref->object);
70}
71
72static void radeon_ttm_mem_global_release(struct drm_global_reference *ref)
73{
74	ttm_mem_global_release(ref->object);
75}
76
77static int radeon_ttm_global_init(struct radeon_device *rdev)
78{
79	struct drm_global_reference *global_ref;
80	int r;
81
82	rdev->mman.mem_global_referenced = false;
83	global_ref = &rdev->mman.mem_global_ref;
84	global_ref->global_type = DRM_GLOBAL_TTM_MEM;
85	global_ref->size = sizeof(struct ttm_mem_global);
86	global_ref->init = &radeon_ttm_mem_global_init;
87	global_ref->release = &radeon_ttm_mem_global_release;
88	r = drm_global_item_ref(global_ref);
89	if (r != 0) {
90		DRM_ERROR("Failed setting up TTM memory accounting "
91			  "subsystem.\n");
92		return r;
93	}
94
95	rdev->mman.bo_global_ref.mem_glob =
96		rdev->mman.mem_global_ref.object;
97	global_ref = &rdev->mman.bo_global_ref.ref;
98	global_ref->global_type = DRM_GLOBAL_TTM_BO;
99	global_ref->size = sizeof(struct ttm_bo_global);
100	global_ref->init = &ttm_bo_global_init;
101	global_ref->release = &ttm_bo_global_release;
102	r = drm_global_item_ref(global_ref);
103	if (r != 0) {
104		DRM_ERROR("Failed setting up TTM BO subsystem.\n");
105		drm_global_item_unref(&rdev->mman.mem_global_ref);
106		return r;
107	}
108
109	rdev->mman.mem_global_referenced = true;
110	return 0;
111}
112
113static void radeon_ttm_global_fini(struct radeon_device *rdev)
114{
115	if (rdev->mman.mem_global_referenced) {
116		drm_global_item_unref(&rdev->mman.bo_global_ref.ref);
117		drm_global_item_unref(&rdev->mman.mem_global_ref);
118		rdev->mman.mem_global_referenced = false;
119	}
120}
121
122static int radeon_invalidate_caches(struct ttm_bo_device *bdev, uint32_t flags)
123{
124	return 0;
125}
126
127static int radeon_init_mem_type(struct ttm_bo_device *bdev, uint32_t type,
128				struct ttm_mem_type_manager *man)
129{
130	struct radeon_device *rdev;
131
132	rdev = radeon_get_rdev(bdev);
133
134	switch (type) {
135	case TTM_PL_SYSTEM:
136		/* System memory */
137		man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
138		man->available_caching = TTM_PL_MASK_CACHING;
139		man->default_caching = TTM_PL_FLAG_CACHED;
140		break;
141	case TTM_PL_TT:
142		man->func = &ttm_bo_manager_func;
143		man->gpu_offset = rdev->mc.gtt_start;
144		man->available_caching = TTM_PL_MASK_CACHING;
145		man->default_caching = TTM_PL_FLAG_CACHED;
146		man->flags = TTM_MEMTYPE_FLAG_MAPPABLE | TTM_MEMTYPE_FLAG_CMA;
147#if IS_ENABLED(CONFIG_AGP)
148		if (rdev->flags & RADEON_IS_AGP) {
149			if (!rdev->ddev->agp) {
150				DRM_ERROR("AGP is not enabled for memory type %u\n",
151					  (unsigned)type);
152				return -EINVAL;
153			}
154			if (!rdev->ddev->agp->cant_use_aperture)
155				man->flags = TTM_MEMTYPE_FLAG_MAPPABLE;
156			man->available_caching = TTM_PL_FLAG_UNCACHED |
157						 TTM_PL_FLAG_WC;
158			man->default_caching = TTM_PL_FLAG_WC;
159		}
160#endif
161		break;
162	case TTM_PL_VRAM:
163		/* "On-card" video ram */
164		man->func = &ttm_bo_manager_func;
165		man->gpu_offset = rdev->mc.vram_start;
166		man->flags = TTM_MEMTYPE_FLAG_FIXED |
167			     TTM_MEMTYPE_FLAG_MAPPABLE;
168		man->available_caching = TTM_PL_FLAG_UNCACHED | TTM_PL_FLAG_WC;
169		man->default_caching = TTM_PL_FLAG_WC;
170		break;
171	default:
172		DRM_ERROR("Unsupported memory type %u\n", (unsigned)type);
173		return -EINVAL;
174	}
175	return 0;
176}
177
178static void radeon_evict_flags(struct ttm_buffer_object *bo,
179				struct ttm_placement *placement)
180{
181	static struct ttm_place placements = {
182		.fpfn = 0,
183		.lpfn = 0,
184		.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_SYSTEM
185	};
186
187	struct radeon_bo *rbo;
188
189	if (!radeon_ttm_bo_is_radeon_bo(bo)) {
190		placement->placement = &placements;
191		placement->busy_placement = &placements;
192		placement->num_placement = 1;
193		placement->num_busy_placement = 1;
194		return;
195	}
196	rbo = container_of(bo, struct radeon_bo, tbo);
197	switch (bo->mem.mem_type) {
198	case TTM_PL_VRAM:
199		if (rbo->rdev->ring[radeon_copy_ring_index(rbo->rdev)].ready == false)
200			radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_CPU);
201		else if (rbo->rdev->mc.visible_vram_size < rbo->rdev->mc.real_vram_size &&
202			 bo->mem.start < (rbo->rdev->mc.visible_vram_size >> PAGE_SHIFT)) {
203			unsigned fpfn = rbo->rdev->mc.visible_vram_size >> PAGE_SHIFT;
204			int i;
205
206			/* Try evicting to the CPU inaccessible part of VRAM
207			 * first, but only set GTT as busy placement, so this
208			 * BO will be evicted to GTT rather than causing other
209			 * BOs to be evicted from VRAM
210			 */
211			radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_VRAM |
212							 RADEON_GEM_DOMAIN_GTT);
213			rbo->placement.num_busy_placement = 0;
214			for (i = 0; i < rbo->placement.num_placement; i++) {
215				if (rbo->placements[i].flags & TTM_PL_FLAG_VRAM) {
216					if (rbo->placements[0].fpfn < fpfn)
217						rbo->placements[0].fpfn = fpfn;
218				} else {
219					rbo->placement.busy_placement =
220						&rbo->placements[i];
221					rbo->placement.num_busy_placement = 1;
222				}
223			}
224		} else
225			radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_GTT);
226		break;
227	case TTM_PL_TT:
228	default:
229		radeon_ttm_placement_from_domain(rbo, RADEON_GEM_DOMAIN_CPU);
230	}
231	*placement = rbo->placement;
232}
233
234static int radeon_verify_access(struct ttm_buffer_object *bo, struct file *filp)
235{
236	struct radeon_bo *rbo = container_of(bo, struct radeon_bo, tbo);
237
238	if (radeon_ttm_tt_has_userptr(bo->ttm))
239		return -EPERM;
240	return drm_vma_node_verify_access(&rbo->gem_base.vma_node, filp);
241}
242
243static void radeon_move_null(struct ttm_buffer_object *bo,
244			     struct ttm_mem_reg *new_mem)
245{
246	struct ttm_mem_reg *old_mem = &bo->mem;
247
248	BUG_ON(old_mem->mm_node != NULL);
249	*old_mem = *new_mem;
250	new_mem->mm_node = NULL;
251}
252
253static int radeon_move_blit(struct ttm_buffer_object *bo,
254			bool evict, bool no_wait_gpu,
255			struct ttm_mem_reg *new_mem,
256			struct ttm_mem_reg *old_mem)
257{
258	struct radeon_device *rdev;
259	uint64_t old_start, new_start;
260	struct radeon_fence *fence;
261	unsigned num_pages;
262	int r, ridx;
263
264	rdev = radeon_get_rdev(bo->bdev);
265	ridx = radeon_copy_ring_index(rdev);
266	old_start = old_mem->start << PAGE_SHIFT;
267	new_start = new_mem->start << PAGE_SHIFT;
268
269	switch (old_mem->mem_type) {
270	case TTM_PL_VRAM:
271		old_start += rdev->mc.vram_start;
272		break;
273	case TTM_PL_TT:
274		old_start += rdev->mc.gtt_start;
275		break;
276	default:
277		DRM_ERROR("Unknown placement %d\n", old_mem->mem_type);
278		return -EINVAL;
279	}
280	switch (new_mem->mem_type) {
281	case TTM_PL_VRAM:
282		new_start += rdev->mc.vram_start;
283		break;
284	case TTM_PL_TT:
285		new_start += rdev->mc.gtt_start;
286		break;
287	default:
288		DRM_ERROR("Unknown placement %d\n", old_mem->mem_type);
289		return -EINVAL;
290	}
291	if (!rdev->ring[ridx].ready) {
292		DRM_ERROR("Trying to move memory with ring turned off.\n");
293		return -EINVAL;
294	}
295
296	BUILD_BUG_ON((PAGE_SIZE % RADEON_GPU_PAGE_SIZE) != 0);
297
298	num_pages = new_mem->num_pages * (PAGE_SIZE / RADEON_GPU_PAGE_SIZE);
299	fence = radeon_copy(rdev, old_start, new_start, num_pages, bo->resv);
300	if (IS_ERR(fence))
301		return PTR_ERR(fence);
302
303	r = ttm_bo_move_accel_cleanup(bo, &fence->base,
304				      evict, no_wait_gpu, new_mem);
305	radeon_fence_unref(&fence);
306	return r;
307}
308
309static int radeon_move_vram_ram(struct ttm_buffer_object *bo,
310				bool evict, bool interruptible,
311				bool no_wait_gpu,
312				struct ttm_mem_reg *new_mem)
313{
314	struct radeon_device *rdev;
315	struct ttm_mem_reg *old_mem = &bo->mem;
316	struct ttm_mem_reg tmp_mem;
317	struct ttm_place placements;
318	struct ttm_placement placement;
319	int r;
320
321	rdev = radeon_get_rdev(bo->bdev);
322	tmp_mem = *new_mem;
323	tmp_mem.mm_node = NULL;
324	placement.num_placement = 1;
325	placement.placement = &placements;
326	placement.num_busy_placement = 1;
327	placement.busy_placement = &placements;
328	placements.fpfn = 0;
329	placements.lpfn = 0;
330	placements.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
331	r = ttm_bo_mem_space(bo, &placement, &tmp_mem,
332			     interruptible, no_wait_gpu);
333	if (unlikely(r)) {
334		return r;
335	}
336
337	r = ttm_tt_set_placement_caching(bo->ttm, tmp_mem.placement);
338	if (unlikely(r)) {
339		goto out_cleanup;
340	}
341
342	r = ttm_tt_bind(bo->ttm, &tmp_mem);
343	if (unlikely(r)) {
344		goto out_cleanup;
345	}
346	r = radeon_move_blit(bo, true, no_wait_gpu, &tmp_mem, old_mem);
347	if (unlikely(r)) {
348		goto out_cleanup;
349	}
350	r = ttm_bo_move_ttm(bo, true, no_wait_gpu, new_mem);
351out_cleanup:
352	ttm_bo_mem_put(bo, &tmp_mem);
353	return r;
354}
355
356static int radeon_move_ram_vram(struct ttm_buffer_object *bo,
357				bool evict, bool interruptible,
358				bool no_wait_gpu,
359				struct ttm_mem_reg *new_mem)
360{
361	struct radeon_device *rdev;
362	struct ttm_mem_reg *old_mem = &bo->mem;
363	struct ttm_mem_reg tmp_mem;
364	struct ttm_placement placement;
365	struct ttm_place placements;
366	int r;
367
368	rdev = radeon_get_rdev(bo->bdev);
369	tmp_mem = *new_mem;
370	tmp_mem.mm_node = NULL;
371	placement.num_placement = 1;
372	placement.placement = &placements;
373	placement.num_busy_placement = 1;
374	placement.busy_placement = &placements;
375	placements.fpfn = 0;
376	placements.lpfn = 0;
377	placements.flags = TTM_PL_MASK_CACHING | TTM_PL_FLAG_TT;
378	r = ttm_bo_mem_space(bo, &placement, &tmp_mem,
379			     interruptible, no_wait_gpu);
380	if (unlikely(r)) {
381		return r;
382	}
383	r = ttm_bo_move_ttm(bo, true, no_wait_gpu, &tmp_mem);
384	if (unlikely(r)) {
385		goto out_cleanup;
386	}
387	r = radeon_move_blit(bo, true, no_wait_gpu, new_mem, old_mem);
388	if (unlikely(r)) {
389		goto out_cleanup;
390	}
391out_cleanup:
392	ttm_bo_mem_put(bo, &tmp_mem);
393	return r;
394}
395
396static int radeon_bo_move(struct ttm_buffer_object *bo,
397			bool evict, bool interruptible,
398			bool no_wait_gpu,
399			struct ttm_mem_reg *new_mem)
400{
401	struct radeon_device *rdev;
402	struct ttm_mem_reg *old_mem = &bo->mem;
403	int r;
404
405	rdev = radeon_get_rdev(bo->bdev);
406	if (old_mem->mem_type == TTM_PL_SYSTEM && bo->ttm == NULL) {
407		radeon_move_null(bo, new_mem);
408		return 0;
409	}
410	if ((old_mem->mem_type == TTM_PL_TT &&
411	     new_mem->mem_type == TTM_PL_SYSTEM) ||
412	    (old_mem->mem_type == TTM_PL_SYSTEM &&
413	     new_mem->mem_type == TTM_PL_TT)) {
414		/* bind is enough */
415		radeon_move_null(bo, new_mem);
416		return 0;
417	}
418	if (!rdev->ring[radeon_copy_ring_index(rdev)].ready ||
419	    rdev->asic->copy.copy == NULL) {
420		/* use memcpy */
421		goto memcpy;
422	}
423
424	if (old_mem->mem_type == TTM_PL_VRAM &&
425	    new_mem->mem_type == TTM_PL_SYSTEM) {
426		r = radeon_move_vram_ram(bo, evict, interruptible,
427					no_wait_gpu, new_mem);
428	} else if (old_mem->mem_type == TTM_PL_SYSTEM &&
429		   new_mem->mem_type == TTM_PL_VRAM) {
430		r = radeon_move_ram_vram(bo, evict, interruptible,
431					    no_wait_gpu, new_mem);
432	} else {
433		r = radeon_move_blit(bo, evict, no_wait_gpu, new_mem, old_mem);
434	}
435
436	if (r) {
437memcpy:
438		r = ttm_bo_move_memcpy(bo, evict, no_wait_gpu, new_mem);
439		if (r) {
440			return r;
441		}
442	}
443
444	/* update statistics */
445	atomic64_add((u64)bo->num_pages << PAGE_SHIFT, &rdev->num_bytes_moved);
446	return 0;
447}
448
449static int radeon_ttm_io_mem_reserve(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
450{
451	struct ttm_mem_type_manager *man = &bdev->man[mem->mem_type];
452	struct radeon_device *rdev = radeon_get_rdev(bdev);
453
454	mem->bus.addr = NULL;
455	mem->bus.offset = 0;
456	mem->bus.size = mem->num_pages << PAGE_SHIFT;
457	mem->bus.base = 0;
458	mem->bus.is_iomem = false;
459	if (!(man->flags & TTM_MEMTYPE_FLAG_MAPPABLE))
460		return -EINVAL;
461	switch (mem->mem_type) {
462	case TTM_PL_SYSTEM:
463		/* system memory */
464		return 0;
465	case TTM_PL_TT:
466#if IS_ENABLED(CONFIG_AGP)
467		if (rdev->flags & RADEON_IS_AGP) {
468			/* RADEON_IS_AGP is set only if AGP is active */
469			mem->bus.offset = mem->start << PAGE_SHIFT;
470			mem->bus.base = rdev->mc.agp_base;
471			mem->bus.is_iomem = !rdev->ddev->agp->cant_use_aperture;
472		}
473#endif
474		break;
475	case TTM_PL_VRAM:
476		mem->bus.offset = mem->start << PAGE_SHIFT;
477		/* check if it's visible */
478		if ((mem->bus.offset + mem->bus.size) > rdev->mc.visible_vram_size)
479			return -EINVAL;
480		mem->bus.base = rdev->mc.aper_base;
481		mem->bus.is_iomem = true;
482#ifdef __alpha__
483		/*
484		 * Alpha: use bus.addr to hold the ioremap() return,
485		 * so we can modify bus.base below.
486		 */
487		if (mem->placement & TTM_PL_FLAG_WC)
488			mem->bus.addr =
489				ioremap_wc(mem->bus.base + mem->bus.offset,
490					   mem->bus.size);
491		else
492			mem->bus.addr =
493				ioremap_nocache(mem->bus.base + mem->bus.offset,
494						mem->bus.size);
495
496		/*
497		 * Alpha: Use just the bus offset plus
498		 * the hose/domain memory base for bus.base.
499		 * It then can be used to build PTEs for VRAM
500		 * access, as done in ttm_bo_vm_fault().
501		 */
502		mem->bus.base = (mem->bus.base & 0x0ffffffffUL) +
503			rdev->ddev->hose->dense_mem_base;
504#endif
505		break;
506	default:
507		return -EINVAL;
508	}
509	return 0;
510}
511
512static void radeon_ttm_io_mem_free(struct ttm_bo_device *bdev, struct ttm_mem_reg *mem)
513{
514}
515
516/*
517 * TTM backend functions.
518 */
519struct radeon_ttm_tt {
520	struct ttm_dma_tt		ttm;
521	struct radeon_device		*rdev;
522	u64				offset;
523
524	uint64_t			userptr;
525	struct mm_struct		*usermm;
526	uint32_t			userflags;
527};
528
529/* prepare the sg table with the user pages */
530static int radeon_ttm_tt_pin_userptr(struct ttm_tt *ttm)
531{
532	struct radeon_device *rdev = radeon_get_rdev(ttm->bdev);
533	struct radeon_ttm_tt *gtt = (void *)ttm;
534	unsigned pinned = 0, nents;
535	int r;
536
537	int write = !(gtt->userflags & RADEON_GEM_USERPTR_READONLY);
538	enum dma_data_direction direction = write ?
539		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
540
541	if (current->mm != gtt->usermm)
542		return -EPERM;
543
544	if (gtt->userflags & RADEON_GEM_USERPTR_ANONONLY) {
545		/* check that we only pin down anonymous memory
546		   to prevent problems with writeback */
547		unsigned long end = gtt->userptr + ttm->num_pages * PAGE_SIZE;
548		struct vm_area_struct *vma;
549		vma = find_vma(gtt->usermm, gtt->userptr);
550		if (!vma || vma->vm_file || vma->vm_end < end)
551			return -EPERM;
552	}
553
554	do {
555		unsigned num_pages = ttm->num_pages - pinned;
556		uint64_t userptr = gtt->userptr + pinned * PAGE_SIZE;
557		struct page **pages = ttm->pages + pinned;
558
559		r = get_user_pages(current, current->mm, userptr, num_pages,
560				   write, 0, pages, NULL);
561		if (r < 0)
562			goto release_pages;
563
564		pinned += r;
565
566	} while (pinned < ttm->num_pages);
567
568	r = sg_alloc_table_from_pages(ttm->sg, ttm->pages, ttm->num_pages, 0,
569				      ttm->num_pages << PAGE_SHIFT,
570				      GFP_KERNEL);
571	if (r)
572		goto release_sg;
573
574	r = -ENOMEM;
575	nents = dma_map_sg(rdev->dev, ttm->sg->sgl, ttm->sg->nents, direction);
576	if (nents != ttm->sg->nents)
577		goto release_sg;
578
579	drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
580					 gtt->ttm.dma_address, ttm->num_pages);
581
582	return 0;
583
584release_sg:
585	kfree(ttm->sg);
586
587release_pages:
588	release_pages(ttm->pages, pinned, 0);
589	return r;
590}
591
592static void radeon_ttm_tt_unpin_userptr(struct ttm_tt *ttm)
593{
594	struct radeon_device *rdev = radeon_get_rdev(ttm->bdev);
595	struct radeon_ttm_tt *gtt = (void *)ttm;
596	struct sg_page_iter sg_iter;
597
598	int write = !(gtt->userflags & RADEON_GEM_USERPTR_READONLY);
599	enum dma_data_direction direction = write ?
600		DMA_BIDIRECTIONAL : DMA_TO_DEVICE;
601
602	/* double check that we don't free the table twice */
603	if (!ttm->sg->sgl)
604		return;
605
606	/* free the sg table and pages again */
607	dma_unmap_sg(rdev->dev, ttm->sg->sgl, ttm->sg->nents, direction);
608
609	for_each_sg_page(ttm->sg->sgl, &sg_iter, ttm->sg->nents, 0) {
610		struct page *page = sg_page_iter_page(&sg_iter);
611		if (!(gtt->userflags & RADEON_GEM_USERPTR_READONLY))
612			set_page_dirty(page);
613
614		mark_page_accessed(page);
615		page_cache_release(page);
616	}
617
618	sg_free_table(ttm->sg);
619}
620
621static int radeon_ttm_backend_bind(struct ttm_tt *ttm,
622				   struct ttm_mem_reg *bo_mem)
623{
624	struct radeon_ttm_tt *gtt = (void*)ttm;
625	uint32_t flags = RADEON_GART_PAGE_VALID | RADEON_GART_PAGE_READ |
626		RADEON_GART_PAGE_WRITE;
627	int r;
628
629	if (gtt->userptr) {
630		radeon_ttm_tt_pin_userptr(ttm);
631		flags &= ~RADEON_GART_PAGE_WRITE;
632	}
633
634	gtt->offset = (unsigned long)(bo_mem->start << PAGE_SHIFT);
635	if (!ttm->num_pages) {
636		WARN(1, "nothing to bind %lu pages for mreg %p back %p!\n",
637		     ttm->num_pages, bo_mem, ttm);
638	}
639	if (ttm->caching_state == tt_cached)
640		flags |= RADEON_GART_PAGE_SNOOP;
641	r = radeon_gart_bind(gtt->rdev, gtt->offset, ttm->num_pages,
642			     ttm->pages, gtt->ttm.dma_address, flags);
643	if (r) {
644		DRM_ERROR("failed to bind %lu pages at 0x%08X\n",
645			  ttm->num_pages, (unsigned)gtt->offset);
646		return r;
647	}
648	return 0;
649}
650
651static int radeon_ttm_backend_unbind(struct ttm_tt *ttm)
652{
653	struct radeon_ttm_tt *gtt = (void *)ttm;
654
655	radeon_gart_unbind(gtt->rdev, gtt->offset, ttm->num_pages);
656
657	if (gtt->userptr)
658		radeon_ttm_tt_unpin_userptr(ttm);
659
660	return 0;
661}
662
663static void radeon_ttm_backend_destroy(struct ttm_tt *ttm)
664{
665	struct radeon_ttm_tt *gtt = (void *)ttm;
666
667	ttm_dma_tt_fini(&gtt->ttm);
668	kfree(gtt);
669}
670
671static struct ttm_backend_func radeon_backend_func = {
672	.bind = &radeon_ttm_backend_bind,
673	.unbind = &radeon_ttm_backend_unbind,
674	.destroy = &radeon_ttm_backend_destroy,
675};
676
677static struct ttm_tt *radeon_ttm_tt_create(struct ttm_bo_device *bdev,
678				    unsigned long size, uint32_t page_flags,
679				    struct page *dummy_read_page)
680{
681	struct radeon_device *rdev;
682	struct radeon_ttm_tt *gtt;
683
684	rdev = radeon_get_rdev(bdev);
685#if IS_ENABLED(CONFIG_AGP)
686	if (rdev->flags & RADEON_IS_AGP) {
687		return ttm_agp_tt_create(bdev, rdev->ddev->agp->bridge,
688					 size, page_flags, dummy_read_page);
689	}
690#endif
691
692	gtt = kzalloc(sizeof(struct radeon_ttm_tt), GFP_KERNEL);
693	if (gtt == NULL) {
694		return NULL;
695	}
696	gtt->ttm.ttm.func = &radeon_backend_func;
697	gtt->rdev = rdev;
698	if (ttm_dma_tt_init(&gtt->ttm, bdev, size, page_flags, dummy_read_page)) {
699		kfree(gtt);
700		return NULL;
701	}
702	return &gtt->ttm.ttm;
703}
704
705static struct radeon_ttm_tt *radeon_ttm_tt_to_gtt(struct ttm_tt *ttm)
706{
707	if (!ttm || ttm->func != &radeon_backend_func)
708		return NULL;
709	return (struct radeon_ttm_tt *)ttm;
710}
711
712static int radeon_ttm_tt_populate(struct ttm_tt *ttm)
713{
714	struct radeon_ttm_tt *gtt = radeon_ttm_tt_to_gtt(ttm);
715	struct radeon_device *rdev;
716	unsigned i;
717	int r;
718	bool slave = !!(ttm->page_flags & TTM_PAGE_FLAG_SG);
719
720	if (ttm->state != tt_unpopulated)
721		return 0;
722
723	if (gtt && gtt->userptr) {
724		ttm->sg = kzalloc(sizeof(struct sg_table), GFP_KERNEL);
725		if (!ttm->sg)
726			return -ENOMEM;
727
728		ttm->page_flags |= TTM_PAGE_FLAG_SG;
729		ttm->state = tt_unbound;
730		return 0;
731	}
732
733	if (slave && ttm->sg) {
734		drm_prime_sg_to_page_addr_arrays(ttm->sg, ttm->pages,
735						 gtt->ttm.dma_address, ttm->num_pages);
736		ttm->state = tt_unbound;
737		return 0;
738	}
739
740	rdev = radeon_get_rdev(ttm->bdev);
741#if IS_ENABLED(CONFIG_AGP)
742	if (rdev->flags & RADEON_IS_AGP) {
743		return ttm_agp_tt_populate(ttm);
744	}
745#endif
746
747#ifdef CONFIG_SWIOTLB
748	if (swiotlb_nr_tbl()) {
749		return ttm_dma_populate(&gtt->ttm, rdev->dev);
750	}
751#endif
752
753	r = ttm_pool_populate(ttm);
754	if (r) {
755		return r;
756	}
757
758	for (i = 0; i < ttm->num_pages; i++) {
759		gtt->ttm.dma_address[i] = pci_map_page(rdev->pdev, ttm->pages[i],
760						       0, PAGE_SIZE,
761						       PCI_DMA_BIDIRECTIONAL);
762		if (pci_dma_mapping_error(rdev->pdev, gtt->ttm.dma_address[i])) {
763			while (i--) {
764				pci_unmap_page(rdev->pdev, gtt->ttm.dma_address[i],
765					       PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
766				gtt->ttm.dma_address[i] = 0;
767			}
768			ttm_pool_unpopulate(ttm);
769			return -EFAULT;
770		}
771	}
772	return 0;
773}
774
775static void radeon_ttm_tt_unpopulate(struct ttm_tt *ttm)
776{
777	struct radeon_device *rdev;
778	struct radeon_ttm_tt *gtt = radeon_ttm_tt_to_gtt(ttm);
779	unsigned i;
780	bool slave = !!(ttm->page_flags & TTM_PAGE_FLAG_SG);
781
782	if (gtt && gtt->userptr) {
783		kfree(ttm->sg);
784		ttm->page_flags &= ~TTM_PAGE_FLAG_SG;
785		return;
786	}
787
788	if (slave)
789		return;
790
791	rdev = radeon_get_rdev(ttm->bdev);
792#if IS_ENABLED(CONFIG_AGP)
793	if (rdev->flags & RADEON_IS_AGP) {
794		ttm_agp_tt_unpopulate(ttm);
795		return;
796	}
797#endif
798
799#ifdef CONFIG_SWIOTLB
800	if (swiotlb_nr_tbl()) {
801		ttm_dma_unpopulate(&gtt->ttm, rdev->dev);
802		return;
803	}
804#endif
805
806	for (i = 0; i < ttm->num_pages; i++) {
807		if (gtt->ttm.dma_address[i]) {
808			pci_unmap_page(rdev->pdev, gtt->ttm.dma_address[i],
809				       PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
810		}
811	}
812
813	ttm_pool_unpopulate(ttm);
814}
815
816int radeon_ttm_tt_set_userptr(struct ttm_tt *ttm, uint64_t addr,
817			      uint32_t flags)
818{
819	struct radeon_ttm_tt *gtt = radeon_ttm_tt_to_gtt(ttm);
820
821	if (gtt == NULL)
822		return -EINVAL;
823
824	gtt->userptr = addr;
825	gtt->usermm = current->mm;
826	gtt->userflags = flags;
827	return 0;
828}
829
830bool radeon_ttm_tt_has_userptr(struct ttm_tt *ttm)
831{
832	struct radeon_ttm_tt *gtt = radeon_ttm_tt_to_gtt(ttm);
833
834	if (gtt == NULL)
835		return false;
836
837	return !!gtt->userptr;
838}
839
840bool radeon_ttm_tt_is_readonly(struct ttm_tt *ttm)
841{
842	struct radeon_ttm_tt *gtt = radeon_ttm_tt_to_gtt(ttm);
843
844	if (gtt == NULL)
845		return false;
846
847	return !!(gtt->userflags & RADEON_GEM_USERPTR_READONLY);
848}
849
850static struct ttm_bo_driver radeon_bo_driver = {
851	.ttm_tt_create = &radeon_ttm_tt_create,
852	.ttm_tt_populate = &radeon_ttm_tt_populate,
853	.ttm_tt_unpopulate = &radeon_ttm_tt_unpopulate,
854	.invalidate_caches = &radeon_invalidate_caches,
855	.init_mem_type = &radeon_init_mem_type,
856	.evict_flags = &radeon_evict_flags,
857	.move = &radeon_bo_move,
858	.verify_access = &radeon_verify_access,
859	.move_notify = &radeon_bo_move_notify,
860	.fault_reserve_notify = &radeon_bo_fault_reserve_notify,
861	.io_mem_reserve = &radeon_ttm_io_mem_reserve,
862	.io_mem_free = &radeon_ttm_io_mem_free,
863};
864
865int radeon_ttm_init(struct radeon_device *rdev)
866{
867	int r;
868
869	r = radeon_ttm_global_init(rdev);
870	if (r) {
871		return r;
872	}
873	/* No others user of address space so set it to 0 */
874	r = ttm_bo_device_init(&rdev->mman.bdev,
875			       rdev->mman.bo_global_ref.ref.object,
876			       &radeon_bo_driver,
877			       rdev->ddev->anon_inode->i_mapping,
878			       DRM_FILE_PAGE_OFFSET,
879			       rdev->need_dma32);
880	if (r) {
881		DRM_ERROR("failed initializing buffer object driver(%d).\n", r);
882		return r;
883	}
884	rdev->mman.initialized = true;
885	r = ttm_bo_init_mm(&rdev->mman.bdev, TTM_PL_VRAM,
886				rdev->mc.real_vram_size >> PAGE_SHIFT);
887	if (r) {
888		DRM_ERROR("Failed initializing VRAM heap.\n");
889		return r;
890	}
891	/* Change the size here instead of the init above so only lpfn is affected */
892	radeon_ttm_set_active_vram_size(rdev, rdev->mc.visible_vram_size);
893
894	r = radeon_bo_create(rdev, 256 * 1024, PAGE_SIZE, true,
895			     RADEON_GEM_DOMAIN_VRAM, 0, NULL,
896			     NULL, &rdev->stollen_vga_memory);
897	if (r) {
898		return r;
899	}
900	r = radeon_bo_reserve(rdev->stollen_vga_memory, false);
901	if (r)
902		return r;
903	r = radeon_bo_pin(rdev->stollen_vga_memory, RADEON_GEM_DOMAIN_VRAM, NULL);
904	radeon_bo_unreserve(rdev->stollen_vga_memory);
905	if (r) {
906		radeon_bo_unref(&rdev->stollen_vga_memory);
907		return r;
908	}
909	DRM_INFO("radeon: %uM of VRAM memory ready\n",
910		 (unsigned) (rdev->mc.real_vram_size / (1024 * 1024)));
911	r = ttm_bo_init_mm(&rdev->mman.bdev, TTM_PL_TT,
912				rdev->mc.gtt_size >> PAGE_SHIFT);
913	if (r) {
914		DRM_ERROR("Failed initializing GTT heap.\n");
915		return r;
916	}
917	DRM_INFO("radeon: %uM of GTT memory ready.\n",
918		 (unsigned)(rdev->mc.gtt_size / (1024 * 1024)));
919
920	r = radeon_ttm_debugfs_init(rdev);
921	if (r) {
922		DRM_ERROR("Failed to init debugfs\n");
923		return r;
924	}
925	return 0;
926}
927
928void radeon_ttm_fini(struct radeon_device *rdev)
929{
930	int r;
931
932	if (!rdev->mman.initialized)
933		return;
934	radeon_ttm_debugfs_fini(rdev);
935	if (rdev->stollen_vga_memory) {
936		r = radeon_bo_reserve(rdev->stollen_vga_memory, false);
937		if (r == 0) {
938			radeon_bo_unpin(rdev->stollen_vga_memory);
939			radeon_bo_unreserve(rdev->stollen_vga_memory);
940		}
941		radeon_bo_unref(&rdev->stollen_vga_memory);
942	}
943	ttm_bo_clean_mm(&rdev->mman.bdev, TTM_PL_VRAM);
944	ttm_bo_clean_mm(&rdev->mman.bdev, TTM_PL_TT);
945	ttm_bo_device_release(&rdev->mman.bdev);
946	radeon_gart_fini(rdev);
947	radeon_ttm_global_fini(rdev);
948	rdev->mman.initialized = false;
949	DRM_INFO("radeon: ttm finalized\n");
950}
951
952/* this should only be called at bootup or when userspace
953 * isn't running */
954void radeon_ttm_set_active_vram_size(struct radeon_device *rdev, u64 size)
955{
956	struct ttm_mem_type_manager *man;
957
958	if (!rdev->mman.initialized)
959		return;
960
961	man = &rdev->mman.bdev.man[TTM_PL_VRAM];
962	/* this just adjusts TTM size idea, which sets lpfn to the correct value */
963	man->size = size >> PAGE_SHIFT;
964}
965
966static struct vm_operations_struct radeon_ttm_vm_ops;
967static const struct vm_operations_struct *ttm_vm_ops = NULL;
968
969static int radeon_ttm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
970{
971	struct ttm_buffer_object *bo;
972	struct radeon_device *rdev;
973	int r;
974
975	bo = (struct ttm_buffer_object *)vma->vm_private_data;
976	if (bo == NULL) {
977		return VM_FAULT_NOPAGE;
978	}
979	rdev = radeon_get_rdev(bo->bdev);
980	down_read(&rdev->pm.mclk_lock);
981	r = ttm_vm_ops->fault(vma, vmf);
982	up_read(&rdev->pm.mclk_lock);
983	return r;
984}
985
986int radeon_mmap(struct file *filp, struct vm_area_struct *vma)
987{
988	struct drm_file *file_priv;
989	struct radeon_device *rdev;
990	int r;
991
992	if (unlikely(vma->vm_pgoff < DRM_FILE_PAGE_OFFSET)) {
993		return -EINVAL;
994	}
995
996	file_priv = filp->private_data;
997	rdev = file_priv->minor->dev->dev_private;
998	if (rdev == NULL) {
999		return -EINVAL;
1000	}
1001	r = ttm_bo_mmap(filp, vma, &rdev->mman.bdev);
1002	if (unlikely(r != 0)) {
1003		return r;
1004	}
1005	if (unlikely(ttm_vm_ops == NULL)) {
1006		ttm_vm_ops = vma->vm_ops;
1007		radeon_ttm_vm_ops = *ttm_vm_ops;
1008		radeon_ttm_vm_ops.fault = &radeon_ttm_fault;
1009	}
1010	vma->vm_ops = &radeon_ttm_vm_ops;
1011	return 0;
1012}
1013
1014#if defined(CONFIG_DEBUG_FS)
1015
1016static int radeon_mm_dump_table(struct seq_file *m, void *data)
1017{
1018	struct drm_info_node *node = (struct drm_info_node *)m->private;
1019	unsigned ttm_pl = *(int *)node->info_ent->data;
1020	struct drm_device *dev = node->minor->dev;
1021	struct radeon_device *rdev = dev->dev_private;
1022	struct drm_mm *mm = (struct drm_mm *)rdev->mman.bdev.man[ttm_pl].priv;
1023	int ret;
1024	struct ttm_bo_global *glob = rdev->mman.bdev.glob;
1025
1026	spin_lock(&glob->lru_lock);
1027	ret = drm_mm_dump_table(m, mm);
1028	spin_unlock(&glob->lru_lock);
1029	return ret;
1030}
1031
1032static int ttm_pl_vram = TTM_PL_VRAM;
1033static int ttm_pl_tt = TTM_PL_TT;
1034
1035static struct drm_info_list radeon_ttm_debugfs_list[] = {
1036	{"radeon_vram_mm", radeon_mm_dump_table, 0, &ttm_pl_vram},
1037	{"radeon_gtt_mm", radeon_mm_dump_table, 0, &ttm_pl_tt},
1038	{"ttm_page_pool", ttm_page_alloc_debugfs, 0, NULL},
1039#ifdef CONFIG_SWIOTLB
1040	{"ttm_dma_page_pool", ttm_dma_page_alloc_debugfs, 0, NULL}
1041#endif
1042};
1043
1044static int radeon_ttm_vram_open(struct inode *inode, struct file *filep)
1045{
1046	struct radeon_device *rdev = inode->i_private;
1047	i_size_write(inode, rdev->mc.mc_vram_size);
1048	filep->private_data = inode->i_private;
1049	return 0;
1050}
1051
1052static ssize_t radeon_ttm_vram_read(struct file *f, char __user *buf,
1053				    size_t size, loff_t *pos)
1054{
1055	struct radeon_device *rdev = f->private_data;
1056	ssize_t result = 0;
1057	int r;
1058
1059	if (size & 0x3 || *pos & 0x3)
1060		return -EINVAL;
1061
1062	while (size) {
1063		unsigned long flags;
1064		uint32_t value;
1065
1066		if (*pos >= rdev->mc.mc_vram_size)
1067			return result;
1068
1069		spin_lock_irqsave(&rdev->mmio_idx_lock, flags);
1070		WREG32(RADEON_MM_INDEX, ((uint32_t)*pos) | 0x80000000);
1071		if (rdev->family >= CHIP_CEDAR)
1072			WREG32(EVERGREEN_MM_INDEX_HI, *pos >> 31);
1073		value = RREG32(RADEON_MM_DATA);
1074		spin_unlock_irqrestore(&rdev->mmio_idx_lock, flags);
1075
1076		r = put_user(value, (uint32_t *)buf);
1077		if (r)
1078			return r;
1079
1080		result += 4;
1081		buf += 4;
1082		*pos += 4;
1083		size -= 4;
1084	}
1085
1086	return result;
1087}
1088
1089static const struct file_operations radeon_ttm_vram_fops = {
1090	.owner = THIS_MODULE,
1091	.open = radeon_ttm_vram_open,
1092	.read = radeon_ttm_vram_read,
1093	.llseek = default_llseek
1094};
1095
1096static int radeon_ttm_gtt_open(struct inode *inode, struct file *filep)
1097{
1098	struct radeon_device *rdev = inode->i_private;
1099	i_size_write(inode, rdev->mc.gtt_size);
1100	filep->private_data = inode->i_private;
1101	return 0;
1102}
1103
1104static ssize_t radeon_ttm_gtt_read(struct file *f, char __user *buf,
1105				   size_t size, loff_t *pos)
1106{
1107	struct radeon_device *rdev = f->private_data;
1108	ssize_t result = 0;
1109	int r;
1110
1111	while (size) {
1112		loff_t p = *pos / PAGE_SIZE;
1113		unsigned off = *pos & ~PAGE_MASK;
1114		size_t cur_size = min_t(size_t, size, PAGE_SIZE - off);
1115		struct page *page;
1116		void *ptr;
1117
1118		if (p >= rdev->gart.num_cpu_pages)
1119			return result;
1120
1121		page = rdev->gart.pages[p];
1122		if (page) {
1123			ptr = kmap(page);
1124			ptr += off;
1125
1126			r = copy_to_user(buf, ptr, cur_size);
1127			kunmap(rdev->gart.pages[p]);
1128		} else
1129			r = clear_user(buf, cur_size);
1130
1131		if (r)
1132			return -EFAULT;
1133
1134		result += cur_size;
1135		buf += cur_size;
1136		*pos += cur_size;
1137		size -= cur_size;
1138	}
1139
1140	return result;
1141}
1142
1143static const struct file_operations radeon_ttm_gtt_fops = {
1144	.owner = THIS_MODULE,
1145	.open = radeon_ttm_gtt_open,
1146	.read = radeon_ttm_gtt_read,
1147	.llseek = default_llseek
1148};
1149
1150#endif
1151
1152static int radeon_ttm_debugfs_init(struct radeon_device *rdev)
1153{
1154#if defined(CONFIG_DEBUG_FS)
1155	unsigned count;
1156
1157	struct drm_minor *minor = rdev->ddev->primary;
1158	struct dentry *ent, *root = minor->debugfs_root;
1159
1160	ent = debugfs_create_file("radeon_vram", S_IFREG | S_IRUGO, root,
1161				  rdev, &radeon_ttm_vram_fops);
1162	if (IS_ERR(ent))
1163		return PTR_ERR(ent);
1164	rdev->mman.vram = ent;
1165
1166	ent = debugfs_create_file("radeon_gtt", S_IFREG | S_IRUGO, root,
1167				  rdev, &radeon_ttm_gtt_fops);
1168	if (IS_ERR(ent))
1169		return PTR_ERR(ent);
1170	rdev->mman.gtt = ent;
1171
1172	count = ARRAY_SIZE(radeon_ttm_debugfs_list);
1173
1174#ifdef CONFIG_SWIOTLB
1175	if (!swiotlb_nr_tbl())
1176		--count;
1177#endif
1178
1179	return radeon_debugfs_add_files(rdev, radeon_ttm_debugfs_list, count);
1180#else
1181
1182	return 0;
1183#endif
1184}
1185
1186static void radeon_ttm_debugfs_fini(struct radeon_device *rdev)
1187{
1188#if defined(CONFIG_DEBUG_FS)
1189
1190	debugfs_remove(rdev->mman.vram);
1191	rdev->mman.vram = NULL;
1192
1193	debugfs_remove(rdev->mman.gtt);
1194	rdev->mman.gtt = NULL;
1195#endif
1196}
1197