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