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