xref: /linux/drivers/gpu/drm/radeon/radeon_gart.c (revision 08ec212c0f92cbf30e3ecc7349f18151714041d6)
1 /*
2  * Copyright 2008 Advanced Micro Devices, Inc.
3  * Copyright 2008 Red Hat Inc.
4  * Copyright 2009 Jerome Glisse.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
20  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22  * OTHER DEALINGS IN THE SOFTWARE.
23  *
24  * Authors: Dave Airlie
25  *          Alex Deucher
26  *          Jerome Glisse
27  */
28 #include <drm/drmP.h>
29 #include <drm/radeon_drm.h>
30 #include "radeon.h"
31 #include "radeon_reg.h"
32 
33 /*
34  * GART
35  * The GART (Graphics Aperture Remapping Table) is an aperture
36  * in the GPU's address space.  System pages can be mapped into
37  * the aperture and look like contiguous pages from the GPU's
38  * perspective.  A page table maps the pages in the aperture
39  * to the actual backing pages in system memory.
40  *
41  * Radeon GPUs support both an internal GART, as described above,
42  * and AGP.  AGP works similarly, but the GART table is configured
43  * and maintained by the northbridge rather than the driver.
44  * Radeon hw has a separate AGP aperture that is programmed to
45  * point to the AGP aperture provided by the northbridge and the
46  * requests are passed through to the northbridge aperture.
47  * Both AGP and internal GART can be used at the same time, however
48  * that is not currently supported by the driver.
49  *
50  * This file handles the common internal GART management.
51  */
52 
53 /*
54  * Common GART table functions.
55  */
56 /**
57  * radeon_gart_table_ram_alloc - allocate system ram for gart page table
58  *
59  * @rdev: radeon_device pointer
60  *
61  * Allocate system memory for GART page table
62  * (r1xx-r3xx, non-pcie r4xx, rs400).  These asics require the
63  * gart table to be in system memory.
64  * Returns 0 for success, -ENOMEM for failure.
65  */
66 int radeon_gart_table_ram_alloc(struct radeon_device *rdev)
67 {
68 	void *ptr;
69 
70 	ptr = pci_alloc_consistent(rdev->pdev, rdev->gart.table_size,
71 				   &rdev->gart.table_addr);
72 	if (ptr == NULL) {
73 		return -ENOMEM;
74 	}
75 #ifdef CONFIG_X86
76 	if (rdev->family == CHIP_RS400 || rdev->family == CHIP_RS480 ||
77 	    rdev->family == CHIP_RS690 || rdev->family == CHIP_RS740) {
78 		set_memory_uc((unsigned long)ptr,
79 			      rdev->gart.table_size >> PAGE_SHIFT);
80 	}
81 #endif
82 	rdev->gart.ptr = ptr;
83 	memset((void *)rdev->gart.ptr, 0, rdev->gart.table_size);
84 	return 0;
85 }
86 
87 /**
88  * radeon_gart_table_ram_free - free system ram for gart page table
89  *
90  * @rdev: radeon_device pointer
91  *
92  * Free system memory for GART page table
93  * (r1xx-r3xx, non-pcie r4xx, rs400).  These asics require the
94  * gart table to be in system memory.
95  */
96 void radeon_gart_table_ram_free(struct radeon_device *rdev)
97 {
98 	if (rdev->gart.ptr == NULL) {
99 		return;
100 	}
101 #ifdef CONFIG_X86
102 	if (rdev->family == CHIP_RS400 || rdev->family == CHIP_RS480 ||
103 	    rdev->family == CHIP_RS690 || rdev->family == CHIP_RS740) {
104 		set_memory_wb((unsigned long)rdev->gart.ptr,
105 			      rdev->gart.table_size >> PAGE_SHIFT);
106 	}
107 #endif
108 	pci_free_consistent(rdev->pdev, rdev->gart.table_size,
109 			    (void *)rdev->gart.ptr,
110 			    rdev->gart.table_addr);
111 	rdev->gart.ptr = NULL;
112 	rdev->gart.table_addr = 0;
113 }
114 
115 /**
116  * radeon_gart_table_vram_alloc - allocate vram for gart page table
117  *
118  * @rdev: radeon_device pointer
119  *
120  * Allocate video memory for GART page table
121  * (pcie r4xx, r5xx+).  These asics require the
122  * gart table to be in video memory.
123  * Returns 0 for success, error for failure.
124  */
125 int radeon_gart_table_vram_alloc(struct radeon_device *rdev)
126 {
127 	int r;
128 
129 	if (rdev->gart.robj == NULL) {
130 		r = radeon_bo_create(rdev, rdev->gart.table_size,
131 				     PAGE_SIZE, true, RADEON_GEM_DOMAIN_VRAM,
132 				     NULL, &rdev->gart.robj);
133 		if (r) {
134 			return r;
135 		}
136 	}
137 	return 0;
138 }
139 
140 /**
141  * radeon_gart_table_vram_pin - pin gart page table in vram
142  *
143  * @rdev: radeon_device pointer
144  *
145  * Pin the GART page table in vram so it will not be moved
146  * by the memory manager (pcie r4xx, r5xx+).  These asics require the
147  * gart table to be in video memory.
148  * Returns 0 for success, error for failure.
149  */
150 int radeon_gart_table_vram_pin(struct radeon_device *rdev)
151 {
152 	uint64_t gpu_addr;
153 	int r;
154 
155 	r = radeon_bo_reserve(rdev->gart.robj, false);
156 	if (unlikely(r != 0))
157 		return r;
158 	r = radeon_bo_pin(rdev->gart.robj,
159 				RADEON_GEM_DOMAIN_VRAM, &gpu_addr);
160 	if (r) {
161 		radeon_bo_unreserve(rdev->gart.robj);
162 		return r;
163 	}
164 	r = radeon_bo_kmap(rdev->gart.robj, &rdev->gart.ptr);
165 	if (r)
166 		radeon_bo_unpin(rdev->gart.robj);
167 	radeon_bo_unreserve(rdev->gart.robj);
168 	rdev->gart.table_addr = gpu_addr;
169 	return r;
170 }
171 
172 /**
173  * radeon_gart_table_vram_unpin - unpin gart page table in vram
174  *
175  * @rdev: radeon_device pointer
176  *
177  * Unpin the GART page table in vram (pcie r4xx, r5xx+).
178  * These asics require the gart table to be in video memory.
179  */
180 void radeon_gart_table_vram_unpin(struct radeon_device *rdev)
181 {
182 	int r;
183 
184 	if (rdev->gart.robj == NULL) {
185 		return;
186 	}
187 	r = radeon_bo_reserve(rdev->gart.robj, false);
188 	if (likely(r == 0)) {
189 		radeon_bo_kunmap(rdev->gart.robj);
190 		radeon_bo_unpin(rdev->gart.robj);
191 		radeon_bo_unreserve(rdev->gart.robj);
192 		rdev->gart.ptr = NULL;
193 	}
194 }
195 
196 /**
197  * radeon_gart_table_vram_free - free gart page table vram
198  *
199  * @rdev: radeon_device pointer
200  *
201  * Free the video memory used for the GART page table
202  * (pcie r4xx, r5xx+).  These asics require the gart table to
203  * be in video memory.
204  */
205 void radeon_gart_table_vram_free(struct radeon_device *rdev)
206 {
207 	if (rdev->gart.robj == NULL) {
208 		return;
209 	}
210 	radeon_gart_table_vram_unpin(rdev);
211 	radeon_bo_unref(&rdev->gart.robj);
212 }
213 
214 /*
215  * Common gart functions.
216  */
217 /**
218  * radeon_gart_unbind - unbind pages from the gart page table
219  *
220  * @rdev: radeon_device pointer
221  * @offset: offset into the GPU's gart aperture
222  * @pages: number of pages to unbind
223  *
224  * Unbinds the requested pages from the gart page table and
225  * replaces them with the dummy page (all asics).
226  */
227 void radeon_gart_unbind(struct radeon_device *rdev, unsigned offset,
228 			int pages)
229 {
230 	unsigned t;
231 	unsigned p;
232 	int i, j;
233 	u64 page_base;
234 
235 	if (!rdev->gart.ready) {
236 		WARN(1, "trying to unbind memory from uninitialized GART !\n");
237 		return;
238 	}
239 	t = offset / RADEON_GPU_PAGE_SIZE;
240 	p = t / (PAGE_SIZE / RADEON_GPU_PAGE_SIZE);
241 	for (i = 0; i < pages; i++, p++) {
242 		if (rdev->gart.pages[p]) {
243 			rdev->gart.pages[p] = NULL;
244 			rdev->gart.pages_addr[p] = rdev->dummy_page.addr;
245 			page_base = rdev->gart.pages_addr[p];
246 			for (j = 0; j < (PAGE_SIZE / RADEON_GPU_PAGE_SIZE); j++, t++) {
247 				if (rdev->gart.ptr) {
248 					radeon_gart_set_page(rdev, t, page_base);
249 				}
250 				page_base += RADEON_GPU_PAGE_SIZE;
251 			}
252 		}
253 	}
254 	mb();
255 	radeon_gart_tlb_flush(rdev);
256 }
257 
258 /**
259  * radeon_gart_bind - bind pages into the gart page table
260  *
261  * @rdev: radeon_device pointer
262  * @offset: offset into the GPU's gart aperture
263  * @pages: number of pages to bind
264  * @pagelist: pages to bind
265  * @dma_addr: DMA addresses of pages
266  *
267  * Binds the requested pages to the gart page table
268  * (all asics).
269  * Returns 0 for success, -EINVAL for failure.
270  */
271 int radeon_gart_bind(struct radeon_device *rdev, unsigned offset,
272 		     int pages, struct page **pagelist, dma_addr_t *dma_addr)
273 {
274 	unsigned t;
275 	unsigned p;
276 	uint64_t page_base;
277 	int i, j;
278 
279 	if (!rdev->gart.ready) {
280 		WARN(1, "trying to bind memory to uninitialized GART !\n");
281 		return -EINVAL;
282 	}
283 	t = offset / RADEON_GPU_PAGE_SIZE;
284 	p = t / (PAGE_SIZE / RADEON_GPU_PAGE_SIZE);
285 
286 	for (i = 0; i < pages; i++, p++) {
287 		rdev->gart.pages_addr[p] = dma_addr[i];
288 		rdev->gart.pages[p] = pagelist[i];
289 		if (rdev->gart.ptr) {
290 			page_base = rdev->gart.pages_addr[p];
291 			for (j = 0; j < (PAGE_SIZE / RADEON_GPU_PAGE_SIZE); j++, t++) {
292 				radeon_gart_set_page(rdev, t, page_base);
293 				page_base += RADEON_GPU_PAGE_SIZE;
294 			}
295 		}
296 	}
297 	mb();
298 	radeon_gart_tlb_flush(rdev);
299 	return 0;
300 }
301 
302 /**
303  * radeon_gart_restore - bind all pages in the gart page table
304  *
305  * @rdev: radeon_device pointer
306  *
307  * Binds all pages in the gart page table (all asics).
308  * Used to rebuild the gart table on device startup or resume.
309  */
310 void radeon_gart_restore(struct radeon_device *rdev)
311 {
312 	int i, j, t;
313 	u64 page_base;
314 
315 	if (!rdev->gart.ptr) {
316 		return;
317 	}
318 	for (i = 0, t = 0; i < rdev->gart.num_cpu_pages; i++) {
319 		page_base = rdev->gart.pages_addr[i];
320 		for (j = 0; j < (PAGE_SIZE / RADEON_GPU_PAGE_SIZE); j++, t++) {
321 			radeon_gart_set_page(rdev, t, page_base);
322 			page_base += RADEON_GPU_PAGE_SIZE;
323 		}
324 	}
325 	mb();
326 	radeon_gart_tlb_flush(rdev);
327 }
328 
329 /**
330  * radeon_gart_init - init the driver info for managing the gart
331  *
332  * @rdev: radeon_device pointer
333  *
334  * Allocate the dummy page and init the gart driver info (all asics).
335  * Returns 0 for success, error for failure.
336  */
337 int radeon_gart_init(struct radeon_device *rdev)
338 {
339 	int r, i;
340 
341 	if (rdev->gart.pages) {
342 		return 0;
343 	}
344 	/* We need PAGE_SIZE >= RADEON_GPU_PAGE_SIZE */
345 	if (PAGE_SIZE < RADEON_GPU_PAGE_SIZE) {
346 		DRM_ERROR("Page size is smaller than GPU page size!\n");
347 		return -EINVAL;
348 	}
349 	r = radeon_dummy_page_init(rdev);
350 	if (r)
351 		return r;
352 	/* Compute table size */
353 	rdev->gart.num_cpu_pages = rdev->mc.gtt_size / PAGE_SIZE;
354 	rdev->gart.num_gpu_pages = rdev->mc.gtt_size / RADEON_GPU_PAGE_SIZE;
355 	DRM_INFO("GART: num cpu pages %u, num gpu pages %u\n",
356 		 rdev->gart.num_cpu_pages, rdev->gart.num_gpu_pages);
357 	/* Allocate pages table */
358 	rdev->gart.pages = kzalloc(sizeof(void *) * rdev->gart.num_cpu_pages,
359 				   GFP_KERNEL);
360 	if (rdev->gart.pages == NULL) {
361 		radeon_gart_fini(rdev);
362 		return -ENOMEM;
363 	}
364 	rdev->gart.pages_addr = kzalloc(sizeof(dma_addr_t) *
365 					rdev->gart.num_cpu_pages, GFP_KERNEL);
366 	if (rdev->gart.pages_addr == NULL) {
367 		radeon_gart_fini(rdev);
368 		return -ENOMEM;
369 	}
370 	/* set GART entry to point to the dummy page by default */
371 	for (i = 0; i < rdev->gart.num_cpu_pages; i++) {
372 		rdev->gart.pages_addr[i] = rdev->dummy_page.addr;
373 	}
374 	return 0;
375 }
376 
377 /**
378  * radeon_gart_fini - tear down the driver info for managing the gart
379  *
380  * @rdev: radeon_device pointer
381  *
382  * Tear down the gart driver info and free the dummy page (all asics).
383  */
384 void radeon_gart_fini(struct radeon_device *rdev)
385 {
386 	if (rdev->gart.pages && rdev->gart.pages_addr && rdev->gart.ready) {
387 		/* unbind pages */
388 		radeon_gart_unbind(rdev, 0, rdev->gart.num_cpu_pages);
389 	}
390 	rdev->gart.ready = false;
391 	kfree(rdev->gart.pages);
392 	kfree(rdev->gart.pages_addr);
393 	rdev->gart.pages = NULL;
394 	rdev->gart.pages_addr = NULL;
395 
396 	radeon_dummy_page_fini(rdev);
397 }
398 
399 /*
400  * GPUVM
401  * GPUVM is similar to the legacy gart on older asics, however
402  * rather than there being a single global gart table
403  * for the entire GPU, there are multiple VM page tables active
404  * at any given time.  The VM page tables can contain a mix
405  * vram pages and system memory pages and system memory pages
406  * can be mapped as snooped (cached system pages) or unsnooped
407  * (uncached system pages).
408  * Each VM has an ID associated with it and there is a page table
409  * associated with each VMID.  When execting a command buffer,
410  * the kernel tells the the ring what VMID to use for that command
411  * buffer.  VMIDs are allocated dynamically as commands are submitted.
412  * The userspace drivers maintain their own address space and the kernel
413  * sets up their pages tables accordingly when they submit their
414  * command buffers and a VMID is assigned.
415  * Cayman/Trinity support up to 8 active VMs at any given time;
416  * SI supports 16.
417  */
418 
419 /*
420  * vm helpers
421  *
422  * TODO bind a default page at vm initialization for default address
423  */
424 
425 /**
426  * radeon_vm_num_pde - return the number of page directory entries
427  *
428  * @rdev: radeon_device pointer
429  *
430  * Calculate the number of page directory entries (cayman+).
431  */
432 static unsigned radeon_vm_num_pdes(struct radeon_device *rdev)
433 {
434 	return rdev->vm_manager.max_pfn >> RADEON_VM_BLOCK_SIZE;
435 }
436 
437 /**
438  * radeon_vm_directory_size - returns the size of the page directory in bytes
439  *
440  * @rdev: radeon_device pointer
441  *
442  * Calculate the size of the page directory in bytes (cayman+).
443  */
444 static unsigned radeon_vm_directory_size(struct radeon_device *rdev)
445 {
446 	return RADEON_GPU_PAGE_ALIGN(radeon_vm_num_pdes(rdev) * 8);
447 }
448 
449 /**
450  * radeon_vm_manager_init - init the vm manager
451  *
452  * @rdev: radeon_device pointer
453  *
454  * Init the vm manager (cayman+).
455  * Returns 0 for success, error for failure.
456  */
457 int radeon_vm_manager_init(struct radeon_device *rdev)
458 {
459 	struct radeon_vm *vm;
460 	struct radeon_bo_va *bo_va;
461 	int r;
462 	unsigned size;
463 
464 	if (!rdev->vm_manager.enabled) {
465 		/* allocate enough for 2 full VM pts */
466 		size = radeon_vm_directory_size(rdev);
467 		size += rdev->vm_manager.max_pfn * 8;
468 		size *= 2;
469 		r = radeon_sa_bo_manager_init(rdev, &rdev->vm_manager.sa_manager,
470 					      RADEON_GPU_PAGE_ALIGN(size),
471 					      RADEON_GEM_DOMAIN_VRAM);
472 		if (r) {
473 			dev_err(rdev->dev, "failed to allocate vm bo (%dKB)\n",
474 				(rdev->vm_manager.max_pfn * 8) >> 10);
475 			return r;
476 		}
477 
478 		r = radeon_asic_vm_init(rdev);
479 		if (r)
480 			return r;
481 
482 		rdev->vm_manager.enabled = true;
483 
484 		r = radeon_sa_bo_manager_start(rdev, &rdev->vm_manager.sa_manager);
485 		if (r)
486 			return r;
487 	}
488 
489 	/* restore page table */
490 	list_for_each_entry(vm, &rdev->vm_manager.lru_vm, list) {
491 		if (vm->page_directory == NULL)
492 			continue;
493 
494 		list_for_each_entry(bo_va, &vm->va, vm_list) {
495 			bo_va->valid = false;
496 		}
497 	}
498 	return 0;
499 }
500 
501 /**
502  * radeon_vm_free_pt - free the page table for a specific vm
503  *
504  * @rdev: radeon_device pointer
505  * @vm: vm to unbind
506  *
507  * Free the page table of a specific vm (cayman+).
508  *
509  * Global and local mutex must be lock!
510  */
511 static void radeon_vm_free_pt(struct radeon_device *rdev,
512 				    struct radeon_vm *vm)
513 {
514 	struct radeon_bo_va *bo_va;
515 	int i;
516 
517 	if (!vm->page_directory)
518 		return;
519 
520 	list_del_init(&vm->list);
521 	radeon_sa_bo_free(rdev, &vm->page_directory, vm->fence);
522 
523 	list_for_each_entry(bo_va, &vm->va, vm_list) {
524 		bo_va->valid = false;
525 	}
526 
527 	if (vm->page_tables == NULL)
528 		return;
529 
530 	for (i = 0; i < radeon_vm_num_pdes(rdev); i++)
531 		radeon_sa_bo_free(rdev, &vm->page_tables[i], vm->fence);
532 
533 	kfree(vm->page_tables);
534 }
535 
536 /**
537  * radeon_vm_manager_fini - tear down the vm manager
538  *
539  * @rdev: radeon_device pointer
540  *
541  * Tear down the VM manager (cayman+).
542  */
543 void radeon_vm_manager_fini(struct radeon_device *rdev)
544 {
545 	struct radeon_vm *vm, *tmp;
546 	int i;
547 
548 	if (!rdev->vm_manager.enabled)
549 		return;
550 
551 	mutex_lock(&rdev->vm_manager.lock);
552 	/* free all allocated page tables */
553 	list_for_each_entry_safe(vm, tmp, &rdev->vm_manager.lru_vm, list) {
554 		mutex_lock(&vm->mutex);
555 		radeon_vm_free_pt(rdev, vm);
556 		mutex_unlock(&vm->mutex);
557 	}
558 	for (i = 0; i < RADEON_NUM_VM; ++i) {
559 		radeon_fence_unref(&rdev->vm_manager.active[i]);
560 	}
561 	radeon_asic_vm_fini(rdev);
562 	mutex_unlock(&rdev->vm_manager.lock);
563 
564 	radeon_sa_bo_manager_suspend(rdev, &rdev->vm_manager.sa_manager);
565 	radeon_sa_bo_manager_fini(rdev, &rdev->vm_manager.sa_manager);
566 	rdev->vm_manager.enabled = false;
567 }
568 
569 /**
570  * radeon_vm_evict - evict page table to make room for new one
571  *
572  * @rdev: radeon_device pointer
573  * @vm: VM we want to allocate something for
574  *
575  * Evict a VM from the lru, making sure that it isn't @vm. (cayman+).
576  * Returns 0 for success, -ENOMEM for failure.
577  *
578  * Global and local mutex must be locked!
579  */
580 int radeon_vm_evict(struct radeon_device *rdev, struct radeon_vm *vm)
581 {
582 	struct radeon_vm *vm_evict;
583 
584 	if (list_empty(&rdev->vm_manager.lru_vm))
585 		return -ENOMEM;
586 
587 	vm_evict = list_first_entry(&rdev->vm_manager.lru_vm,
588 				    struct radeon_vm, list);
589 	if (vm_evict == vm)
590 		return -ENOMEM;
591 
592 	mutex_lock(&vm_evict->mutex);
593 	radeon_vm_free_pt(rdev, vm_evict);
594 	mutex_unlock(&vm_evict->mutex);
595 	return 0;
596 }
597 
598 /**
599  * radeon_vm_alloc_pt - allocates a page table for a VM
600  *
601  * @rdev: radeon_device pointer
602  * @vm: vm to bind
603  *
604  * Allocate a page table for the requested vm (cayman+).
605  * Returns 0 for success, error for failure.
606  *
607  * Global and local mutex must be locked!
608  */
609 int radeon_vm_alloc_pt(struct radeon_device *rdev, struct radeon_vm *vm)
610 {
611 	unsigned pd_size, pts_size;
612 	u64 *pd_addr;
613 	int r;
614 
615 	if (vm == NULL) {
616 		return -EINVAL;
617 	}
618 
619 	if (vm->page_directory != NULL) {
620 		return 0;
621 	}
622 
623 retry:
624 	pd_size = RADEON_GPU_PAGE_ALIGN(radeon_vm_directory_size(rdev));
625 	r = radeon_sa_bo_new(rdev, &rdev->vm_manager.sa_manager,
626 			     &vm->page_directory, pd_size,
627 			     RADEON_GPU_PAGE_SIZE, false);
628 	if (r == -ENOMEM) {
629 		r = radeon_vm_evict(rdev, vm);
630 		if (r)
631 			return r;
632 		goto retry;
633 
634 	} else if (r) {
635 		return r;
636 	}
637 
638 	vm->pd_gpu_addr = radeon_sa_bo_gpu_addr(vm->page_directory);
639 
640 	/* Initially clear the page directory */
641 	pd_addr = radeon_sa_bo_cpu_addr(vm->page_directory);
642 	memset(pd_addr, 0, pd_size);
643 
644 	pts_size = radeon_vm_num_pdes(rdev) * sizeof(struct radeon_sa_bo *);
645 	vm->page_tables = kzalloc(pts_size, GFP_KERNEL);
646 
647 	if (vm->page_tables == NULL) {
648 		DRM_ERROR("Cannot allocate memory for page table array\n");
649 		radeon_sa_bo_free(rdev, &vm->page_directory, vm->fence);
650 		return -ENOMEM;
651 	}
652 
653 	return 0;
654 }
655 
656 /**
657  * radeon_vm_add_to_lru - add VMs page table to LRU list
658  *
659  * @rdev: radeon_device pointer
660  * @vm: vm to add to LRU
661  *
662  * Add the allocated page table to the LRU list (cayman+).
663  *
664  * Global mutex must be locked!
665  */
666 void radeon_vm_add_to_lru(struct radeon_device *rdev, struct radeon_vm *vm)
667 {
668 	list_del_init(&vm->list);
669 	list_add_tail(&vm->list, &rdev->vm_manager.lru_vm);
670 }
671 
672 /**
673  * radeon_vm_grab_id - allocate the next free VMID
674  *
675  * @rdev: radeon_device pointer
676  * @vm: vm to allocate id for
677  * @ring: ring we want to submit job to
678  *
679  * Allocate an id for the vm (cayman+).
680  * Returns the fence we need to sync to (if any).
681  *
682  * Global and local mutex must be locked!
683  */
684 struct radeon_fence *radeon_vm_grab_id(struct radeon_device *rdev,
685 				       struct radeon_vm *vm, int ring)
686 {
687 	struct radeon_fence *best[RADEON_NUM_RINGS] = {};
688 	unsigned choices[2] = {};
689 	unsigned i;
690 
691 	/* check if the id is still valid */
692 	if (vm->fence && vm->fence == rdev->vm_manager.active[vm->id])
693 		return NULL;
694 
695 	/* we definately need to flush */
696 	radeon_fence_unref(&vm->last_flush);
697 
698 	/* skip over VMID 0, since it is the system VM */
699 	for (i = 1; i < rdev->vm_manager.nvm; ++i) {
700 		struct radeon_fence *fence = rdev->vm_manager.active[i];
701 
702 		if (fence == NULL) {
703 			/* found a free one */
704 			vm->id = i;
705 			return NULL;
706 		}
707 
708 		if (radeon_fence_is_earlier(fence, best[fence->ring])) {
709 			best[fence->ring] = fence;
710 			choices[fence->ring == ring ? 0 : 1] = i;
711 		}
712 	}
713 
714 	for (i = 0; i < 2; ++i) {
715 		if (choices[i]) {
716 			vm->id = choices[i];
717 			return rdev->vm_manager.active[choices[i]];
718 		}
719 	}
720 
721 	/* should never happen */
722 	BUG();
723 	return NULL;
724 }
725 
726 /**
727  * radeon_vm_fence - remember fence for vm
728  *
729  * @rdev: radeon_device pointer
730  * @vm: vm we want to fence
731  * @fence: fence to remember
732  *
733  * Fence the vm (cayman+).
734  * Set the fence used to protect page table and id.
735  *
736  * Global and local mutex must be locked!
737  */
738 void radeon_vm_fence(struct radeon_device *rdev,
739 		     struct radeon_vm *vm,
740 		     struct radeon_fence *fence)
741 {
742 	radeon_fence_unref(&rdev->vm_manager.active[vm->id]);
743 	rdev->vm_manager.active[vm->id] = radeon_fence_ref(fence);
744 
745 	radeon_fence_unref(&vm->fence);
746 	vm->fence = radeon_fence_ref(fence);
747 }
748 
749 /**
750  * radeon_vm_bo_find - find the bo_va for a specific vm & bo
751  *
752  * @vm: requested vm
753  * @bo: requested buffer object
754  *
755  * Find @bo inside the requested vm (cayman+).
756  * Search inside the @bos vm list for the requested vm
757  * Returns the found bo_va or NULL if none is found
758  *
759  * Object has to be reserved!
760  */
761 struct radeon_bo_va *radeon_vm_bo_find(struct radeon_vm *vm,
762 				       struct radeon_bo *bo)
763 {
764 	struct radeon_bo_va *bo_va;
765 
766 	list_for_each_entry(bo_va, &bo->va, bo_list) {
767 		if (bo_va->vm == vm) {
768 			return bo_va;
769 		}
770 	}
771 	return NULL;
772 }
773 
774 /**
775  * radeon_vm_bo_add - add a bo to a specific vm
776  *
777  * @rdev: radeon_device pointer
778  * @vm: requested vm
779  * @bo: radeon buffer object
780  *
781  * Add @bo into the requested vm (cayman+).
782  * Add @bo to the list of bos associated with the vm
783  * Returns newly added bo_va or NULL for failure
784  *
785  * Object has to be reserved!
786  */
787 struct radeon_bo_va *radeon_vm_bo_add(struct radeon_device *rdev,
788 				      struct radeon_vm *vm,
789 				      struct radeon_bo *bo)
790 {
791 	struct radeon_bo_va *bo_va;
792 
793 	bo_va = kzalloc(sizeof(struct radeon_bo_va), GFP_KERNEL);
794 	if (bo_va == NULL) {
795 		return NULL;
796 	}
797 	bo_va->vm = vm;
798 	bo_va->bo = bo;
799 	bo_va->soffset = 0;
800 	bo_va->eoffset = 0;
801 	bo_va->flags = 0;
802 	bo_va->valid = false;
803 	bo_va->ref_count = 1;
804 	INIT_LIST_HEAD(&bo_va->bo_list);
805 	INIT_LIST_HEAD(&bo_va->vm_list);
806 
807 	mutex_lock(&vm->mutex);
808 	list_add(&bo_va->vm_list, &vm->va);
809 	list_add_tail(&bo_va->bo_list, &bo->va);
810 	mutex_unlock(&vm->mutex);
811 
812 	return bo_va;
813 }
814 
815 /**
816  * radeon_vm_bo_set_addr - set bos virtual address inside a vm
817  *
818  * @rdev: radeon_device pointer
819  * @bo_va: bo_va to store the address
820  * @soffset: requested offset of the buffer in the VM address space
821  * @flags: attributes of pages (read/write/valid/etc.)
822  *
823  * Set offset of @bo_va (cayman+).
824  * Validate and set the offset requested within the vm address space.
825  * Returns 0 for success, error for failure.
826  *
827  * Object has to be reserved!
828  */
829 int radeon_vm_bo_set_addr(struct radeon_device *rdev,
830 			  struct radeon_bo_va *bo_va,
831 			  uint64_t soffset,
832 			  uint32_t flags)
833 {
834 	uint64_t size = radeon_bo_size(bo_va->bo);
835 	uint64_t eoffset, last_offset = 0;
836 	struct radeon_vm *vm = bo_va->vm;
837 	struct radeon_bo_va *tmp;
838 	struct list_head *head;
839 	unsigned last_pfn;
840 
841 	if (soffset) {
842 		/* make sure object fit at this offset */
843 		eoffset = soffset + size;
844 		if (soffset >= eoffset) {
845 			return -EINVAL;
846 		}
847 
848 		last_pfn = eoffset / RADEON_GPU_PAGE_SIZE;
849 		if (last_pfn > rdev->vm_manager.max_pfn) {
850 			dev_err(rdev->dev, "va above limit (0x%08X > 0x%08X)\n",
851 				last_pfn, rdev->vm_manager.max_pfn);
852 			return -EINVAL;
853 		}
854 
855 	} else {
856 		eoffset = last_pfn = 0;
857 	}
858 
859 	mutex_lock(&vm->mutex);
860 	head = &vm->va;
861 	last_offset = 0;
862 	list_for_each_entry(tmp, &vm->va, vm_list) {
863 		if (bo_va == tmp) {
864 			/* skip over currently modified bo */
865 			continue;
866 		}
867 
868 		if (soffset >= last_offset && eoffset <= tmp->soffset) {
869 			/* bo can be added before this one */
870 			break;
871 		}
872 		if (eoffset > tmp->soffset && soffset < tmp->eoffset) {
873 			/* bo and tmp overlap, invalid offset */
874 			dev_err(rdev->dev, "bo %p va 0x%08X conflict with (bo %p 0x%08X 0x%08X)\n",
875 				bo_va->bo, (unsigned)bo_va->soffset, tmp->bo,
876 				(unsigned)tmp->soffset, (unsigned)tmp->eoffset);
877 			mutex_unlock(&vm->mutex);
878 			return -EINVAL;
879 		}
880 		last_offset = tmp->eoffset;
881 		head = &tmp->vm_list;
882 	}
883 
884 	bo_va->soffset = soffset;
885 	bo_va->eoffset = eoffset;
886 	bo_va->flags = flags;
887 	bo_va->valid = false;
888 	list_move(&bo_va->vm_list, head);
889 
890 	mutex_unlock(&vm->mutex);
891 	return 0;
892 }
893 
894 /**
895  * radeon_vm_map_gart - get the physical address of a gart page
896  *
897  * @rdev: radeon_device pointer
898  * @addr: the unmapped addr
899  *
900  * Look up the physical address of the page that the pte resolves
901  * to (cayman+).
902  * Returns the physical address of the page.
903  */
904 uint64_t radeon_vm_map_gart(struct radeon_device *rdev, uint64_t addr)
905 {
906 	uint64_t result;
907 
908 	/* page table offset */
909 	result = rdev->gart.pages_addr[addr >> PAGE_SHIFT];
910 
911 	/* in case cpu page size != gpu page size*/
912 	result |= addr & (~PAGE_MASK);
913 
914 	return result;
915 }
916 
917 /**
918  * radeon_vm_update_pdes - make sure that page directory is valid
919  *
920  * @rdev: radeon_device pointer
921  * @vm: requested vm
922  * @start: start of GPU address range
923  * @end: end of GPU address range
924  *
925  * Allocates new page tables if necessary
926  * and updates the page directory (cayman+).
927  * Returns 0 for success, error for failure.
928  *
929  * Global and local mutex must be locked!
930  */
931 static int radeon_vm_update_pdes(struct radeon_device *rdev,
932 				 struct radeon_vm *vm,
933 				 uint64_t start, uint64_t end)
934 {
935 	static const uint32_t incr = RADEON_VM_PTE_COUNT * 8;
936 
937 	uint64_t last_pde = ~0, last_pt = ~0;
938 	unsigned count = 0;
939 	uint64_t pt_idx;
940 	int r;
941 
942 	start = (start / RADEON_GPU_PAGE_SIZE) >> RADEON_VM_BLOCK_SIZE;
943 	end = (end / RADEON_GPU_PAGE_SIZE) >> RADEON_VM_BLOCK_SIZE;
944 
945 	/* walk over the address space and update the page directory */
946 	for (pt_idx = start; pt_idx <= end; ++pt_idx) {
947 		uint64_t pde, pt;
948 
949 		if (vm->page_tables[pt_idx])
950 			continue;
951 
952 retry:
953 		r = radeon_sa_bo_new(rdev, &rdev->vm_manager.sa_manager,
954 				     &vm->page_tables[pt_idx],
955 				     RADEON_VM_PTE_COUNT * 8,
956 				     RADEON_GPU_PAGE_SIZE, false);
957 
958 		if (r == -ENOMEM) {
959 			r = radeon_vm_evict(rdev, vm);
960 			if (r)
961 				return r;
962 			goto retry;
963 		} else if (r) {
964 			return r;
965 		}
966 
967 		pde = vm->pd_gpu_addr + pt_idx * 8;
968 
969 		pt = radeon_sa_bo_gpu_addr(vm->page_tables[pt_idx]);
970 
971 		if (((last_pde + 8 * count) != pde) ||
972 		    ((last_pt + incr * count) != pt)) {
973 
974 			if (count) {
975 				radeon_asic_vm_set_page(rdev, last_pde,
976 							last_pt, count, incr,
977 							RADEON_VM_PAGE_VALID);
978 			}
979 
980 			count = 1;
981 			last_pde = pde;
982 			last_pt = pt;
983 		} else {
984 			++count;
985 		}
986 	}
987 
988 	if (count) {
989 		radeon_asic_vm_set_page(rdev, last_pde, last_pt, count,
990 					incr, RADEON_VM_PAGE_VALID);
991 
992 	}
993 
994 	return 0;
995 }
996 
997 /**
998  * radeon_vm_update_ptes - make sure that page tables are valid
999  *
1000  * @rdev: radeon_device pointer
1001  * @vm: requested vm
1002  * @start: start of GPU address range
1003  * @end: end of GPU address range
1004  * @dst: destination address to map to
1005  * @flags: mapping flags
1006  *
1007  * Update the page tables in the range @start - @end (cayman+).
1008  *
1009  * Global and local mutex must be locked!
1010  */
1011 static void radeon_vm_update_ptes(struct radeon_device *rdev,
1012 				  struct radeon_vm *vm,
1013 				  uint64_t start, uint64_t end,
1014 				  uint64_t dst, uint32_t flags)
1015 {
1016 	static const uint64_t mask = RADEON_VM_PTE_COUNT - 1;
1017 
1018 	uint64_t last_pte = ~0, last_dst = ~0;
1019 	unsigned count = 0;
1020 	uint64_t addr;
1021 
1022 	start = start / RADEON_GPU_PAGE_SIZE;
1023 	end = end / RADEON_GPU_PAGE_SIZE;
1024 
1025 	/* walk over the address space and update the page tables */
1026 	for (addr = start; addr < end; ) {
1027 		uint64_t pt_idx = addr >> RADEON_VM_BLOCK_SIZE;
1028 		unsigned nptes;
1029 		uint64_t pte;
1030 
1031 		if ((addr & ~mask) == (end & ~mask))
1032 			nptes = end - addr;
1033 		else
1034 			nptes = RADEON_VM_PTE_COUNT - (addr & mask);
1035 
1036 		pte = radeon_sa_bo_gpu_addr(vm->page_tables[pt_idx]);
1037 		pte += (addr & mask) * 8;
1038 
1039 		if (((last_pte + 8 * count) != pte) ||
1040 		    ((count + nptes) > 1 << 11)) {
1041 
1042 			if (count) {
1043 				radeon_asic_vm_set_page(rdev, last_pte,
1044 							last_dst, count,
1045 							RADEON_GPU_PAGE_SIZE,
1046 							flags);
1047 			}
1048 
1049 			count = nptes;
1050 			last_pte = pte;
1051 			last_dst = dst;
1052 		} else {
1053 			count += nptes;
1054 		}
1055 
1056 		addr += nptes;
1057 		dst += nptes * RADEON_GPU_PAGE_SIZE;
1058 	}
1059 
1060 	if (count) {
1061 		radeon_asic_vm_set_page(rdev, last_pte,	last_dst, count,
1062 					RADEON_GPU_PAGE_SIZE, flags);
1063 	}
1064 }
1065 
1066 /**
1067  * radeon_vm_bo_update_pte - map a bo into the vm page table
1068  *
1069  * @rdev: radeon_device pointer
1070  * @vm: requested vm
1071  * @bo: radeon buffer object
1072  * @mem: ttm mem
1073  *
1074  * Fill in the page table entries for @bo (cayman+).
1075  * Returns 0 for success, -EINVAL for failure.
1076  *
1077  * Object have to be reserved & global and local mutex must be locked!
1078  */
1079 int radeon_vm_bo_update_pte(struct radeon_device *rdev,
1080 			    struct radeon_vm *vm,
1081 			    struct radeon_bo *bo,
1082 			    struct ttm_mem_reg *mem)
1083 {
1084 	unsigned ridx = rdev->asic->vm.pt_ring_index;
1085 	struct radeon_ring *ring = &rdev->ring[ridx];
1086 	struct radeon_semaphore *sem = NULL;
1087 	struct radeon_bo_va *bo_va;
1088 	unsigned nptes, npdes, ndw;
1089 	uint64_t addr;
1090 	int r;
1091 
1092 	/* nothing to do if vm isn't bound */
1093 	if (vm->page_directory == NULL)
1094 		return 0;
1095 
1096 	bo_va = radeon_vm_bo_find(vm, bo);
1097 	if (bo_va == NULL) {
1098 		dev_err(rdev->dev, "bo %p not in vm %p\n", bo, vm);
1099 		return -EINVAL;
1100 	}
1101 
1102 	if (!bo_va->soffset) {
1103 		dev_err(rdev->dev, "bo %p don't has a mapping in vm %p\n",
1104 			bo, vm);
1105 		return -EINVAL;
1106 	}
1107 
1108 	if ((bo_va->valid && mem) || (!bo_va->valid && mem == NULL))
1109 		return 0;
1110 
1111 	bo_va->flags &= ~RADEON_VM_PAGE_VALID;
1112 	bo_va->flags &= ~RADEON_VM_PAGE_SYSTEM;
1113 	if (mem) {
1114 		addr = mem->start << PAGE_SHIFT;
1115 		if (mem->mem_type != TTM_PL_SYSTEM) {
1116 			bo_va->flags |= RADEON_VM_PAGE_VALID;
1117 			bo_va->valid = true;
1118 		}
1119 		if (mem->mem_type == TTM_PL_TT) {
1120 			bo_va->flags |= RADEON_VM_PAGE_SYSTEM;
1121 		} else {
1122 			addr += rdev->vm_manager.vram_base_offset;
1123 		}
1124 	} else {
1125 		addr = 0;
1126 		bo_va->valid = false;
1127 	}
1128 
1129 	if (vm->fence && radeon_fence_signaled(vm->fence)) {
1130 		radeon_fence_unref(&vm->fence);
1131 	}
1132 
1133 	if (vm->fence && vm->fence->ring != ridx) {
1134 		r = radeon_semaphore_create(rdev, &sem);
1135 		if (r) {
1136 			return r;
1137 		}
1138 	}
1139 
1140 	nptes = radeon_bo_ngpu_pages(bo);
1141 
1142 	/* assume two extra pdes in case the mapping overlaps the borders */
1143 	npdes = (nptes >> RADEON_VM_BLOCK_SIZE) + 2;
1144 
1145 	/* estimate number of dw needed */
1146 	/* semaphore, fence and padding */
1147 	ndw = 32;
1148 
1149 	if (RADEON_VM_BLOCK_SIZE > 11)
1150 		/* reserve space for one header for every 2k dwords */
1151 		ndw += (nptes >> 11) * 3;
1152 	else
1153 		/* reserve space for one header for
1154 		    every (1 << BLOCK_SIZE) entries */
1155 		ndw += (nptes >> RADEON_VM_BLOCK_SIZE) * 3;
1156 
1157 	/* reserve space for pte addresses */
1158 	ndw += nptes * 2;
1159 
1160 	/* reserve space for one header for every 2k dwords */
1161 	ndw += (npdes >> 11) * 3;
1162 
1163 	/* reserve space for pde addresses */
1164 	ndw += npdes * 2;
1165 
1166 	r = radeon_ring_lock(rdev, ring, ndw);
1167 	if (r) {
1168 		return r;
1169 	}
1170 
1171 	if (sem && radeon_fence_need_sync(vm->fence, ridx)) {
1172 		radeon_semaphore_sync_rings(rdev, sem, vm->fence->ring, ridx);
1173 		radeon_fence_note_sync(vm->fence, ridx);
1174 	}
1175 
1176 	r = radeon_vm_update_pdes(rdev, vm, bo_va->soffset, bo_va->eoffset);
1177 	if (r) {
1178 		radeon_ring_unlock_undo(rdev, ring);
1179 		return r;
1180 	}
1181 
1182 	radeon_vm_update_ptes(rdev, vm, bo_va->soffset, bo_va->eoffset,
1183 			      addr, bo_va->flags);
1184 
1185 	radeon_fence_unref(&vm->fence);
1186 	r = radeon_fence_emit(rdev, &vm->fence, ridx);
1187 	if (r) {
1188 		radeon_ring_unlock_undo(rdev, ring);
1189 		return r;
1190 	}
1191 	radeon_ring_unlock_commit(rdev, ring);
1192 	radeon_semaphore_free(rdev, &sem, vm->fence);
1193 	radeon_fence_unref(&vm->last_flush);
1194 
1195 	return 0;
1196 }
1197 
1198 /**
1199  * radeon_vm_bo_rmv - remove a bo to a specific vm
1200  *
1201  * @rdev: radeon_device pointer
1202  * @bo_va: requested bo_va
1203  *
1204  * Remove @bo_va->bo from the requested vm (cayman+).
1205  * Remove @bo_va->bo from the list of bos associated with the bo_va->vm and
1206  * remove the ptes for @bo_va in the page table.
1207  * Returns 0 for success.
1208  *
1209  * Object have to be reserved!
1210  */
1211 int radeon_vm_bo_rmv(struct radeon_device *rdev,
1212 		     struct radeon_bo_va *bo_va)
1213 {
1214 	int r;
1215 
1216 	mutex_lock(&rdev->vm_manager.lock);
1217 	mutex_lock(&bo_va->vm->mutex);
1218 	r = radeon_vm_bo_update_pte(rdev, bo_va->vm, bo_va->bo, NULL);
1219 	mutex_unlock(&rdev->vm_manager.lock);
1220 	list_del(&bo_va->vm_list);
1221 	mutex_unlock(&bo_va->vm->mutex);
1222 	list_del(&bo_va->bo_list);
1223 
1224 	kfree(bo_va);
1225 	return r;
1226 }
1227 
1228 /**
1229  * radeon_vm_bo_invalidate - mark the bo as invalid
1230  *
1231  * @rdev: radeon_device pointer
1232  * @vm: requested vm
1233  * @bo: radeon buffer object
1234  *
1235  * Mark @bo as invalid (cayman+).
1236  */
1237 void radeon_vm_bo_invalidate(struct radeon_device *rdev,
1238 			     struct radeon_bo *bo)
1239 {
1240 	struct radeon_bo_va *bo_va;
1241 
1242 	BUG_ON(!atomic_read(&bo->tbo.reserved));
1243 	list_for_each_entry(bo_va, &bo->va, bo_list) {
1244 		bo_va->valid = false;
1245 	}
1246 }
1247 
1248 /**
1249  * radeon_vm_init - initialize a vm instance
1250  *
1251  * @rdev: radeon_device pointer
1252  * @vm: requested vm
1253  *
1254  * Init @vm fields (cayman+).
1255  */
1256 void radeon_vm_init(struct radeon_device *rdev, struct radeon_vm *vm)
1257 {
1258 	vm->id = 0;
1259 	vm->fence = NULL;
1260 	mutex_init(&vm->mutex);
1261 	INIT_LIST_HEAD(&vm->list);
1262 	INIT_LIST_HEAD(&vm->va);
1263 }
1264 
1265 /**
1266  * radeon_vm_fini - tear down a vm instance
1267  *
1268  * @rdev: radeon_device pointer
1269  * @vm: requested vm
1270  *
1271  * Tear down @vm (cayman+).
1272  * Unbind the VM and remove all bos from the vm bo list
1273  */
1274 void radeon_vm_fini(struct radeon_device *rdev, struct radeon_vm *vm)
1275 {
1276 	struct radeon_bo_va *bo_va, *tmp;
1277 	int r;
1278 
1279 	mutex_lock(&rdev->vm_manager.lock);
1280 	mutex_lock(&vm->mutex);
1281 	radeon_vm_free_pt(rdev, vm);
1282 	mutex_unlock(&rdev->vm_manager.lock);
1283 
1284 	if (!list_empty(&vm->va)) {
1285 		dev_err(rdev->dev, "still active bo inside vm\n");
1286 	}
1287 	list_for_each_entry_safe(bo_va, tmp, &vm->va, vm_list) {
1288 		list_del_init(&bo_va->vm_list);
1289 		r = radeon_bo_reserve(bo_va->bo, false);
1290 		if (!r) {
1291 			list_del_init(&bo_va->bo_list);
1292 			radeon_bo_unreserve(bo_va->bo);
1293 			kfree(bo_va);
1294 		}
1295 	}
1296 	radeon_fence_unref(&vm->fence);
1297 	radeon_fence_unref(&vm->last_flush);
1298 	mutex_unlock(&vm->mutex);
1299 }
1300