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/amdgpu_drm.h>
30 #include "amdgpu.h"
31 #include "amdgpu_trace.h"
32 
33 /*
34  * GPUVM
35  * GPUVM is similar to the legacy gart on older asics, however
36  * rather than there being a single global gart table
37  * for the entire GPU, there are multiple VM page tables active
38  * at any given time.  The VM page tables can contain a mix
39  * vram pages and system memory pages and system memory pages
40  * can be mapped as snooped (cached system pages) or unsnooped
41  * (uncached system pages).
42  * Each VM has an ID associated with it and there is a page table
43  * associated with each VMID.  When execting a command buffer,
44  * the kernel tells the the ring what VMID to use for that command
45  * buffer.  VMIDs are allocated dynamically as commands are submitted.
46  * The userspace drivers maintain their own address space and the kernel
47  * sets up their pages tables accordingly when they submit their
48  * command buffers and a VMID is assigned.
49  * Cayman/Trinity support up to 8 active VMs at any given time;
50  * SI supports 16.
51  */
52 
53 /**
54  * amdgpu_vm_num_pde - return the number of page directory entries
55  *
56  * @adev: amdgpu_device pointer
57  *
58  * Calculate the number of page directory entries (cayman+).
59  */
60 static unsigned amdgpu_vm_num_pdes(struct amdgpu_device *adev)
61 {
62 	return adev->vm_manager.max_pfn >> amdgpu_vm_block_size;
63 }
64 
65 /**
66  * amdgpu_vm_directory_size - returns the size of the page directory in bytes
67  *
68  * @adev: amdgpu_device pointer
69  *
70  * Calculate the size of the page directory in bytes (cayman+).
71  */
72 static unsigned amdgpu_vm_directory_size(struct amdgpu_device *adev)
73 {
74 	return AMDGPU_GPU_PAGE_ALIGN(amdgpu_vm_num_pdes(adev) * 8);
75 }
76 
77 /**
78  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
79  *
80  * @vm: vm providing the BOs
81  * @validated: head of validation list
82  * @entry: entry to add
83  *
84  * Add the page directory to the list of BOs to
85  * validate for command submission.
86  */
87 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
88 			 struct list_head *validated,
89 			 struct amdgpu_bo_list_entry *entry)
90 {
91 	entry->robj = vm->page_directory;
92 	entry->prefered_domains = AMDGPU_GEM_DOMAIN_VRAM;
93 	entry->allowed_domains = AMDGPU_GEM_DOMAIN_VRAM;
94 	entry->priority = 0;
95 	entry->tv.bo = &vm->page_directory->tbo;
96 	entry->tv.shared = true;
97 	list_add(&entry->tv.head, validated);
98 }
99 
100 /**
101  * amdgpu_vm_get_bos - add the vm BOs to a duplicates list
102  *
103  * @vm: vm providing the BOs
104  * @duplicates: head of duplicates list
105  *
106  * Add the page directory to the BO duplicates list
107  * for command submission.
108  */
109 void amdgpu_vm_get_pt_bos(struct amdgpu_vm *vm, struct list_head *duplicates)
110 {
111 	unsigned i;
112 
113 	/* add the vm page table to the list */
114 	for (i = 0; i <= vm->max_pde_used; ++i) {
115 		struct amdgpu_bo_list_entry *entry = &vm->page_tables[i].entry;
116 
117 		if (!entry->robj)
118 			continue;
119 
120 		list_add(&entry->tv.head, duplicates);
121 	}
122 
123 }
124 
125 /**
126  * amdgpu_vm_move_pt_bos_in_lru - move the PT BOs to the LRU tail
127  *
128  * @adev: amdgpu device instance
129  * @vm: vm providing the BOs
130  *
131  * Move the PT BOs to the tail of the LRU.
132  */
133 void amdgpu_vm_move_pt_bos_in_lru(struct amdgpu_device *adev,
134 				  struct amdgpu_vm *vm)
135 {
136 	struct ttm_bo_global *glob = adev->mman.bdev.glob;
137 	unsigned i;
138 
139 	spin_lock(&glob->lru_lock);
140 	for (i = 0; i <= vm->max_pde_used; ++i) {
141 		struct amdgpu_bo_list_entry *entry = &vm->page_tables[i].entry;
142 
143 		if (!entry->robj)
144 			continue;
145 
146 		ttm_bo_move_to_lru_tail(&entry->robj->tbo);
147 	}
148 	spin_unlock(&glob->lru_lock);
149 }
150 
151 /**
152  * amdgpu_vm_grab_id - allocate the next free VMID
153  *
154  * @vm: vm to allocate id for
155  * @ring: ring we want to submit job to
156  * @sync: sync object where we add dependencies
157  *
158  * Allocate an id for the vm, adding fences to the sync obj as necessary.
159  *
160  * Global mutex must be locked!
161  */
162 int amdgpu_vm_grab_id(struct amdgpu_vm *vm, struct amdgpu_ring *ring,
163 		      struct amdgpu_sync *sync)
164 {
165 	struct fence *best[AMDGPU_MAX_RINGS] = {};
166 	struct amdgpu_vm_id *vm_id = &vm->ids[ring->idx];
167 	struct amdgpu_device *adev = ring->adev;
168 
169 	unsigned choices[2] = {};
170 	unsigned i;
171 
172 	/* check if the id is still valid */
173 	if (vm_id->id) {
174 		unsigned id = vm_id->id;
175 		long owner;
176 
177 		owner = atomic_long_read(&adev->vm_manager.ids[id].owner);
178 		if (owner == (long)vm) {
179 			trace_amdgpu_vm_grab_id(vm_id->id, ring->idx);
180 			return 0;
181 		}
182 	}
183 
184 	/* we definately need to flush */
185 	vm_id->pd_gpu_addr = ~0ll;
186 
187 	/* skip over VMID 0, since it is the system VM */
188 	for (i = 1; i < adev->vm_manager.nvm; ++i) {
189 		struct fence *fence = adev->vm_manager.ids[i].active;
190 		struct amdgpu_ring *fring;
191 
192 		if (fence == NULL) {
193 			/* found a free one */
194 			vm_id->id = i;
195 			trace_amdgpu_vm_grab_id(i, ring->idx);
196 			return 0;
197 		}
198 
199 		fring = amdgpu_ring_from_fence(fence);
200 		if (best[fring->idx] == NULL ||
201 		    fence_is_later(best[fring->idx], fence)) {
202 			best[fring->idx] = fence;
203 			choices[fring == ring ? 0 : 1] = i;
204 		}
205 	}
206 
207 	for (i = 0; i < 2; ++i) {
208 		if (choices[i]) {
209 			struct fence *fence;
210 
211 			fence  = adev->vm_manager.ids[choices[i]].active;
212 			vm_id->id = choices[i];
213 
214 			trace_amdgpu_vm_grab_id(choices[i], ring->idx);
215 			return amdgpu_sync_fence(ring->adev, sync, fence);
216 		}
217 	}
218 
219 	/* should never happen */
220 	BUG();
221 	return -EINVAL;
222 }
223 
224 /**
225  * amdgpu_vm_flush - hardware flush the vm
226  *
227  * @ring: ring to use for flush
228  * @vm: vm we want to flush
229  * @updates: last vm update that we waited for
230  *
231  * Flush the vm (cayman+).
232  *
233  * Global and local mutex must be locked!
234  */
235 void amdgpu_vm_flush(struct amdgpu_ring *ring,
236 		     struct amdgpu_vm *vm,
237 		     struct fence *updates)
238 {
239 	uint64_t pd_addr = amdgpu_bo_gpu_offset(vm->page_directory);
240 	struct amdgpu_vm_id *vm_id = &vm->ids[ring->idx];
241 	struct fence *flushed_updates = vm_id->flushed_updates;
242 	bool is_later;
243 
244 	if (!flushed_updates)
245 		is_later = true;
246 	else if (!updates)
247 		is_later = false;
248 	else
249 		is_later = fence_is_later(updates, flushed_updates);
250 
251 	if (pd_addr != vm_id->pd_gpu_addr || is_later) {
252 		trace_amdgpu_vm_flush(pd_addr, ring->idx, vm_id->id);
253 		if (is_later) {
254 			vm_id->flushed_updates = fence_get(updates);
255 			fence_put(flushed_updates);
256 		}
257 		vm_id->pd_gpu_addr = pd_addr;
258 		amdgpu_ring_emit_vm_flush(ring, vm_id->id, vm_id->pd_gpu_addr);
259 	}
260 }
261 
262 /**
263  * amdgpu_vm_fence - remember fence for vm
264  *
265  * @adev: amdgpu_device pointer
266  * @vm: vm we want to fence
267  * @fence: fence to remember
268  *
269  * Fence the vm (cayman+).
270  * Set the fence used to protect page table and id.
271  *
272  * Global and local mutex must be locked!
273  */
274 void amdgpu_vm_fence(struct amdgpu_device *adev,
275 		     struct amdgpu_vm *vm,
276 		     struct fence *fence)
277 {
278 	struct amdgpu_ring *ring = amdgpu_ring_from_fence(fence);
279 	unsigned vm_id = vm->ids[ring->idx].id;
280 
281 	fence_put(adev->vm_manager.ids[vm_id].active);
282 	adev->vm_manager.ids[vm_id].active = fence_get(fence);
283 	atomic_long_set(&adev->vm_manager.ids[vm_id].owner, (long)vm);
284 }
285 
286 /**
287  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
288  *
289  * @vm: requested vm
290  * @bo: requested buffer object
291  *
292  * Find @bo inside the requested vm (cayman+).
293  * Search inside the @bos vm list for the requested vm
294  * Returns the found bo_va or NULL if none is found
295  *
296  * Object has to be reserved!
297  */
298 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
299 				       struct amdgpu_bo *bo)
300 {
301 	struct amdgpu_bo_va *bo_va;
302 
303 	list_for_each_entry(bo_va, &bo->va, bo_list) {
304 		if (bo_va->vm == vm) {
305 			return bo_va;
306 		}
307 	}
308 	return NULL;
309 }
310 
311 /**
312  * amdgpu_vm_update_pages - helper to call the right asic function
313  *
314  * @adev: amdgpu_device pointer
315  * @ib: indirect buffer to fill with commands
316  * @pe: addr of the page entry
317  * @addr: dst addr to write into pe
318  * @count: number of page entries to update
319  * @incr: increase next addr by incr bytes
320  * @flags: hw access flags
321  * @gtt_flags: GTT hw access flags
322  *
323  * Traces the parameters and calls the right asic functions
324  * to setup the page table using the DMA.
325  */
326 static void amdgpu_vm_update_pages(struct amdgpu_device *adev,
327 				   struct amdgpu_ib *ib,
328 				   uint64_t pe, uint64_t addr,
329 				   unsigned count, uint32_t incr,
330 				   uint32_t flags, uint32_t gtt_flags)
331 {
332 	trace_amdgpu_vm_set_page(pe, addr, count, incr, flags);
333 
334 	if ((flags & AMDGPU_PTE_SYSTEM) && (flags == gtt_flags)) {
335 		uint64_t src = adev->gart.table_addr + (addr >> 12) * 8;
336 		amdgpu_vm_copy_pte(adev, ib, pe, src, count);
337 
338 	} else if ((flags & AMDGPU_PTE_SYSTEM) || (count < 3)) {
339 		amdgpu_vm_write_pte(adev, ib, pe, addr,
340 				      count, incr, flags);
341 
342 	} else {
343 		amdgpu_vm_set_pte_pde(adev, ib, pe, addr,
344 				      count, incr, flags);
345 	}
346 }
347 
348 int amdgpu_vm_free_job(struct amdgpu_job *job)
349 {
350 	int i;
351 	for (i = 0; i < job->num_ibs; i++)
352 		amdgpu_ib_free(job->adev, &job->ibs[i]);
353 	kfree(job->ibs);
354 	return 0;
355 }
356 
357 /**
358  * amdgpu_vm_clear_bo - initially clear the page dir/table
359  *
360  * @adev: amdgpu_device pointer
361  * @bo: bo to clear
362  *
363  * need to reserve bo first before calling it.
364  */
365 static int amdgpu_vm_clear_bo(struct amdgpu_device *adev,
366 			      struct amdgpu_bo *bo)
367 {
368 	struct amdgpu_ring *ring = adev->vm_manager.vm_pte_funcs_ring;
369 	struct fence *fence = NULL;
370 	struct amdgpu_ib *ib;
371 	unsigned entries;
372 	uint64_t addr;
373 	int r;
374 
375 	r = reservation_object_reserve_shared(bo->tbo.resv);
376 	if (r)
377 		return r;
378 
379 	r = ttm_bo_validate(&bo->tbo, &bo->placement, true, false);
380 	if (r)
381 		goto error;
382 
383 	addr = amdgpu_bo_gpu_offset(bo);
384 	entries = amdgpu_bo_size(bo) / 8;
385 
386 	ib = kzalloc(sizeof(struct amdgpu_ib), GFP_KERNEL);
387 	if (!ib)
388 		goto error;
389 
390 	r = amdgpu_ib_get(ring, NULL, entries * 2 + 64, ib);
391 	if (r)
392 		goto error_free;
393 
394 	ib->length_dw = 0;
395 
396 	amdgpu_vm_update_pages(adev, ib, addr, 0, entries, 0, 0, 0);
397 	amdgpu_vm_pad_ib(adev, ib);
398 	WARN_ON(ib->length_dw > 64);
399 	r = amdgpu_sched_ib_submit_kernel_helper(adev, ring, ib, 1,
400 						 &amdgpu_vm_free_job,
401 						 AMDGPU_FENCE_OWNER_VM,
402 						 &fence);
403 	if (!r)
404 		amdgpu_bo_fence(bo, fence, true);
405 	fence_put(fence);
406 	if (amdgpu_enable_scheduler)
407 		return 0;
408 
409 error_free:
410 	amdgpu_ib_free(adev, ib);
411 	kfree(ib);
412 
413 error:
414 	return r;
415 }
416 
417 /**
418  * amdgpu_vm_map_gart - get the physical address of a gart page
419  *
420  * @adev: amdgpu_device pointer
421  * @addr: the unmapped addr
422  *
423  * Look up the physical address of the page that the pte resolves
424  * to (cayman+).
425  * Returns the physical address of the page.
426  */
427 uint64_t amdgpu_vm_map_gart(struct amdgpu_device *adev, uint64_t addr)
428 {
429 	uint64_t result;
430 
431 	/* page table offset */
432 	result = adev->gart.pages_addr[addr >> PAGE_SHIFT];
433 
434 	/* in case cpu page size != gpu page size*/
435 	result |= addr & (~PAGE_MASK);
436 
437 	return result;
438 }
439 
440 /**
441  * amdgpu_vm_update_pdes - make sure that page directory is valid
442  *
443  * @adev: amdgpu_device pointer
444  * @vm: requested vm
445  * @start: start of GPU address range
446  * @end: end of GPU address range
447  *
448  * Allocates new page tables if necessary
449  * and updates the page directory (cayman+).
450  * Returns 0 for success, error for failure.
451  *
452  * Global and local mutex must be locked!
453  */
454 int amdgpu_vm_update_page_directory(struct amdgpu_device *adev,
455 				    struct amdgpu_vm *vm)
456 {
457 	struct amdgpu_ring *ring = adev->vm_manager.vm_pte_funcs_ring;
458 	struct amdgpu_bo *pd = vm->page_directory;
459 	uint64_t pd_addr = amdgpu_bo_gpu_offset(pd);
460 	uint32_t incr = AMDGPU_VM_PTE_COUNT * 8;
461 	uint64_t last_pde = ~0, last_pt = ~0;
462 	unsigned count = 0, pt_idx, ndw;
463 	struct amdgpu_ib *ib;
464 	struct fence *fence = NULL;
465 
466 	int r;
467 
468 	/* padding, etc. */
469 	ndw = 64;
470 
471 	/* assume the worst case */
472 	ndw += vm->max_pde_used * 6;
473 
474 	/* update too big for an IB */
475 	if (ndw > 0xfffff)
476 		return -ENOMEM;
477 
478 	ib = kzalloc(sizeof(struct amdgpu_ib), GFP_KERNEL);
479 	if (!ib)
480 		return -ENOMEM;
481 
482 	r = amdgpu_ib_get(ring, NULL, ndw * 4, ib);
483 	if (r) {
484 		kfree(ib);
485 		return r;
486 	}
487 	ib->length_dw = 0;
488 
489 	/* walk over the address space and update the page directory */
490 	for (pt_idx = 0; pt_idx <= vm->max_pde_used; ++pt_idx) {
491 		struct amdgpu_bo *bo = vm->page_tables[pt_idx].entry.robj;
492 		uint64_t pde, pt;
493 
494 		if (bo == NULL)
495 			continue;
496 
497 		pt = amdgpu_bo_gpu_offset(bo);
498 		if (vm->page_tables[pt_idx].addr == pt)
499 			continue;
500 		vm->page_tables[pt_idx].addr = pt;
501 
502 		pde = pd_addr + pt_idx * 8;
503 		if (((last_pde + 8 * count) != pde) ||
504 		    ((last_pt + incr * count) != pt)) {
505 
506 			if (count) {
507 				amdgpu_vm_update_pages(adev, ib, last_pde,
508 						       last_pt, count, incr,
509 						       AMDGPU_PTE_VALID, 0);
510 			}
511 
512 			count = 1;
513 			last_pde = pde;
514 			last_pt = pt;
515 		} else {
516 			++count;
517 		}
518 	}
519 
520 	if (count)
521 		amdgpu_vm_update_pages(adev, ib, last_pde, last_pt, count,
522 				       incr, AMDGPU_PTE_VALID, 0);
523 
524 	if (ib->length_dw != 0) {
525 		amdgpu_vm_pad_ib(adev, ib);
526 		amdgpu_sync_resv(adev, &ib->sync, pd->tbo.resv, AMDGPU_FENCE_OWNER_VM);
527 		WARN_ON(ib->length_dw > ndw);
528 		r = amdgpu_sched_ib_submit_kernel_helper(adev, ring, ib, 1,
529 							 &amdgpu_vm_free_job,
530 							 AMDGPU_FENCE_OWNER_VM,
531 							 &fence);
532 		if (r)
533 			goto error_free;
534 
535 		amdgpu_bo_fence(pd, fence, true);
536 		fence_put(vm->page_directory_fence);
537 		vm->page_directory_fence = fence_get(fence);
538 		fence_put(fence);
539 	}
540 
541 	if (!amdgpu_enable_scheduler || ib->length_dw == 0) {
542 		amdgpu_ib_free(adev, ib);
543 		kfree(ib);
544 	}
545 
546 	return 0;
547 
548 error_free:
549 	amdgpu_ib_free(adev, ib);
550 	kfree(ib);
551 	return r;
552 }
553 
554 /**
555  * amdgpu_vm_frag_ptes - add fragment information to PTEs
556  *
557  * @adev: amdgpu_device pointer
558  * @ib: IB for the update
559  * @pe_start: first PTE to handle
560  * @pe_end: last PTE to handle
561  * @addr: addr those PTEs should point to
562  * @flags: hw mapping flags
563  * @gtt_flags: GTT hw mapping flags
564  *
565  * Global and local mutex must be locked!
566  */
567 static void amdgpu_vm_frag_ptes(struct amdgpu_device *adev,
568 				struct amdgpu_ib *ib,
569 				uint64_t pe_start, uint64_t pe_end,
570 				uint64_t addr, uint32_t flags,
571 				uint32_t gtt_flags)
572 {
573 	/**
574 	 * The MC L1 TLB supports variable sized pages, based on a fragment
575 	 * field in the PTE. When this field is set to a non-zero value, page
576 	 * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
577 	 * flags are considered valid for all PTEs within the fragment range
578 	 * and corresponding mappings are assumed to be physically contiguous.
579 	 *
580 	 * The L1 TLB can store a single PTE for the whole fragment,
581 	 * significantly increasing the space available for translation
582 	 * caching. This leads to large improvements in throughput when the
583 	 * TLB is under pressure.
584 	 *
585 	 * The L2 TLB distributes small and large fragments into two
586 	 * asymmetric partitions. The large fragment cache is significantly
587 	 * larger. Thus, we try to use large fragments wherever possible.
588 	 * Userspace can support this by aligning virtual base address and
589 	 * allocation size to the fragment size.
590 	 */
591 
592 	/* SI and newer are optimized for 64KB */
593 	uint64_t frag_flags = AMDGPU_PTE_FRAG_64KB;
594 	uint64_t frag_align = 0x80;
595 
596 	uint64_t frag_start = ALIGN(pe_start, frag_align);
597 	uint64_t frag_end = pe_end & ~(frag_align - 1);
598 
599 	unsigned count;
600 
601 	/* system pages are non continuously */
602 	if ((flags & AMDGPU_PTE_SYSTEM) || !(flags & AMDGPU_PTE_VALID) ||
603 	    (frag_start >= frag_end)) {
604 
605 		count = (pe_end - pe_start) / 8;
606 		amdgpu_vm_update_pages(adev, ib, pe_start, addr, count,
607 				       AMDGPU_GPU_PAGE_SIZE, flags, gtt_flags);
608 		return;
609 	}
610 
611 	/* handle the 4K area at the beginning */
612 	if (pe_start != frag_start) {
613 		count = (frag_start - pe_start) / 8;
614 		amdgpu_vm_update_pages(adev, ib, pe_start, addr, count,
615 				       AMDGPU_GPU_PAGE_SIZE, flags, gtt_flags);
616 		addr += AMDGPU_GPU_PAGE_SIZE * count;
617 	}
618 
619 	/* handle the area in the middle */
620 	count = (frag_end - frag_start) / 8;
621 	amdgpu_vm_update_pages(adev, ib, frag_start, addr, count,
622 			       AMDGPU_GPU_PAGE_SIZE, flags | frag_flags,
623 			       gtt_flags);
624 
625 	/* handle the 4K area at the end */
626 	if (frag_end != pe_end) {
627 		addr += AMDGPU_GPU_PAGE_SIZE * count;
628 		count = (pe_end - frag_end) / 8;
629 		amdgpu_vm_update_pages(adev, ib, frag_end, addr, count,
630 				       AMDGPU_GPU_PAGE_SIZE, flags, gtt_flags);
631 	}
632 }
633 
634 /**
635  * amdgpu_vm_update_ptes - make sure that page tables are valid
636  *
637  * @adev: amdgpu_device pointer
638  * @vm: requested vm
639  * @start: start of GPU address range
640  * @end: end of GPU address range
641  * @dst: destination address to map to
642  * @flags: mapping flags
643  *
644  * Update the page tables in the range @start - @end (cayman+).
645  *
646  * Global and local mutex must be locked!
647  */
648 static int amdgpu_vm_update_ptes(struct amdgpu_device *adev,
649 				 struct amdgpu_vm *vm,
650 				 struct amdgpu_ib *ib,
651 				 uint64_t start, uint64_t end,
652 				 uint64_t dst, uint32_t flags,
653 				 uint32_t gtt_flags)
654 {
655 	uint64_t mask = AMDGPU_VM_PTE_COUNT - 1;
656 	uint64_t last_pte = ~0, last_dst = ~0;
657 	void *owner = AMDGPU_FENCE_OWNER_VM;
658 	unsigned count = 0;
659 	uint64_t addr;
660 
661 	/* sync to everything on unmapping */
662 	if (!(flags & AMDGPU_PTE_VALID))
663 		owner = AMDGPU_FENCE_OWNER_UNDEFINED;
664 
665 	/* walk over the address space and update the page tables */
666 	for (addr = start; addr < end; ) {
667 		uint64_t pt_idx = addr >> amdgpu_vm_block_size;
668 		struct amdgpu_bo *pt = vm->page_tables[pt_idx].entry.robj;
669 		unsigned nptes;
670 		uint64_t pte;
671 		int r;
672 
673 		amdgpu_sync_resv(adev, &ib->sync, pt->tbo.resv, owner);
674 		r = reservation_object_reserve_shared(pt->tbo.resv);
675 		if (r)
676 			return r;
677 
678 		if ((addr & ~mask) == (end & ~mask))
679 			nptes = end - addr;
680 		else
681 			nptes = AMDGPU_VM_PTE_COUNT - (addr & mask);
682 
683 		pte = amdgpu_bo_gpu_offset(pt);
684 		pte += (addr & mask) * 8;
685 
686 		if ((last_pte + 8 * count) != pte) {
687 
688 			if (count) {
689 				amdgpu_vm_frag_ptes(adev, ib, last_pte,
690 						    last_pte + 8 * count,
691 						    last_dst, flags,
692 						    gtt_flags);
693 			}
694 
695 			count = nptes;
696 			last_pte = pte;
697 			last_dst = dst;
698 		} else {
699 			count += nptes;
700 		}
701 
702 		addr += nptes;
703 		dst += nptes * AMDGPU_GPU_PAGE_SIZE;
704 	}
705 
706 	if (count) {
707 		amdgpu_vm_frag_ptes(adev, ib, last_pte,
708 				    last_pte + 8 * count,
709 				    last_dst, flags, gtt_flags);
710 	}
711 
712 	return 0;
713 }
714 
715 /**
716  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
717  *
718  * @adev: amdgpu_device pointer
719  * @vm: requested vm
720  * @mapping: mapped range and flags to use for the update
721  * @addr: addr to set the area to
722  * @gtt_flags: flags as they are used for GTT
723  * @fence: optional resulting fence
724  *
725  * Fill in the page table entries for @mapping.
726  * Returns 0 for success, -EINVAL for failure.
727  *
728  * Object have to be reserved and mutex must be locked!
729  */
730 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
731 				       struct amdgpu_vm *vm,
732 				       struct amdgpu_bo_va_mapping *mapping,
733 				       uint64_t addr, uint32_t gtt_flags,
734 				       struct fence **fence)
735 {
736 	struct amdgpu_ring *ring = adev->vm_manager.vm_pte_funcs_ring;
737 	unsigned nptes, ncmds, ndw;
738 	uint32_t flags = gtt_flags;
739 	struct amdgpu_ib *ib;
740 	struct fence *f = NULL;
741 	int r;
742 
743 	/* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
744 	 * but in case of something, we filter the flags in first place
745 	 */
746 	if (!(mapping->flags & AMDGPU_PTE_READABLE))
747 		flags &= ~AMDGPU_PTE_READABLE;
748 	if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
749 		flags &= ~AMDGPU_PTE_WRITEABLE;
750 
751 	trace_amdgpu_vm_bo_update(mapping);
752 
753 	nptes = mapping->it.last - mapping->it.start + 1;
754 
755 	/*
756 	 * reserve space for one command every (1 << BLOCK_SIZE)
757 	 *  entries or 2k dwords (whatever is smaller)
758 	 */
759 	ncmds = (nptes >> min(amdgpu_vm_block_size, 11)) + 1;
760 
761 	/* padding, etc. */
762 	ndw = 64;
763 
764 	if ((flags & AMDGPU_PTE_SYSTEM) && (flags == gtt_flags)) {
765 		/* only copy commands needed */
766 		ndw += ncmds * 7;
767 
768 	} else if (flags & AMDGPU_PTE_SYSTEM) {
769 		/* header for write data commands */
770 		ndw += ncmds * 4;
771 
772 		/* body of write data command */
773 		ndw += nptes * 2;
774 
775 	} else {
776 		/* set page commands needed */
777 		ndw += ncmds * 10;
778 
779 		/* two extra commands for begin/end of fragment */
780 		ndw += 2 * 10;
781 	}
782 
783 	/* update too big for an IB */
784 	if (ndw > 0xfffff)
785 		return -ENOMEM;
786 
787 	ib = kzalloc(sizeof(struct amdgpu_ib), GFP_KERNEL);
788 	if (!ib)
789 		return -ENOMEM;
790 
791 	r = amdgpu_ib_get(ring, NULL, ndw * 4, ib);
792 	if (r) {
793 		kfree(ib);
794 		return r;
795 	}
796 
797 	ib->length_dw = 0;
798 
799 	r = amdgpu_vm_update_ptes(adev, vm, ib, mapping->it.start,
800 				  mapping->it.last + 1, addr + mapping->offset,
801 				  flags, gtt_flags);
802 
803 	if (r) {
804 		amdgpu_ib_free(adev, ib);
805 		kfree(ib);
806 		return r;
807 	}
808 
809 	amdgpu_vm_pad_ib(adev, ib);
810 	WARN_ON(ib->length_dw > ndw);
811 	r = amdgpu_sched_ib_submit_kernel_helper(adev, ring, ib, 1,
812 						 &amdgpu_vm_free_job,
813 						 AMDGPU_FENCE_OWNER_VM,
814 						 &f);
815 	if (r)
816 		goto error_free;
817 
818 	amdgpu_bo_fence(vm->page_directory, f, true);
819 	if (fence) {
820 		fence_put(*fence);
821 		*fence = fence_get(f);
822 	}
823 	fence_put(f);
824 	if (!amdgpu_enable_scheduler) {
825 		amdgpu_ib_free(adev, ib);
826 		kfree(ib);
827 	}
828 	return 0;
829 
830 error_free:
831 	amdgpu_ib_free(adev, ib);
832 	kfree(ib);
833 	return r;
834 }
835 
836 /**
837  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
838  *
839  * @adev: amdgpu_device pointer
840  * @bo_va: requested BO and VM object
841  * @mem: ttm mem
842  *
843  * Fill in the page table entries for @bo_va.
844  * Returns 0 for success, -EINVAL for failure.
845  *
846  * Object have to be reserved and mutex must be locked!
847  */
848 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
849 			struct amdgpu_bo_va *bo_va,
850 			struct ttm_mem_reg *mem)
851 {
852 	struct amdgpu_vm *vm = bo_va->vm;
853 	struct amdgpu_bo_va_mapping *mapping;
854 	uint32_t flags;
855 	uint64_t addr;
856 	int r;
857 
858 	if (mem) {
859 		addr = (u64)mem->start << PAGE_SHIFT;
860 		if (mem->mem_type != TTM_PL_TT)
861 			addr += adev->vm_manager.vram_base_offset;
862 	} else {
863 		addr = 0;
864 	}
865 
866 	flags = amdgpu_ttm_tt_pte_flags(adev, bo_va->bo->tbo.ttm, mem);
867 
868 	spin_lock(&vm->status_lock);
869 	if (!list_empty(&bo_va->vm_status))
870 		list_splice_init(&bo_va->valids, &bo_va->invalids);
871 	spin_unlock(&vm->status_lock);
872 
873 	list_for_each_entry(mapping, &bo_va->invalids, list) {
874 		r = amdgpu_vm_bo_update_mapping(adev, vm, mapping, addr,
875 						flags, &bo_va->last_pt_update);
876 		if (r)
877 			return r;
878 	}
879 
880 	if (trace_amdgpu_vm_bo_mapping_enabled()) {
881 		list_for_each_entry(mapping, &bo_va->valids, list)
882 			trace_amdgpu_vm_bo_mapping(mapping);
883 
884 		list_for_each_entry(mapping, &bo_va->invalids, list)
885 			trace_amdgpu_vm_bo_mapping(mapping);
886 	}
887 
888 	spin_lock(&vm->status_lock);
889 	list_splice_init(&bo_va->invalids, &bo_va->valids);
890 	list_del_init(&bo_va->vm_status);
891 	if (!mem)
892 		list_add(&bo_va->vm_status, &vm->cleared);
893 	spin_unlock(&vm->status_lock);
894 
895 	return 0;
896 }
897 
898 /**
899  * amdgpu_vm_clear_freed - clear freed BOs in the PT
900  *
901  * @adev: amdgpu_device pointer
902  * @vm: requested vm
903  *
904  * Make sure all freed BOs are cleared in the PT.
905  * Returns 0 for success.
906  *
907  * PTs have to be reserved and mutex must be locked!
908  */
909 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
910 			  struct amdgpu_vm *vm)
911 {
912 	struct amdgpu_bo_va_mapping *mapping;
913 	int r;
914 
915 	spin_lock(&vm->freed_lock);
916 	while (!list_empty(&vm->freed)) {
917 		mapping = list_first_entry(&vm->freed,
918 			struct amdgpu_bo_va_mapping, list);
919 		list_del(&mapping->list);
920 		spin_unlock(&vm->freed_lock);
921 		r = amdgpu_vm_bo_update_mapping(adev, vm, mapping, 0, 0, NULL);
922 		kfree(mapping);
923 		if (r)
924 			return r;
925 
926 		spin_lock(&vm->freed_lock);
927 	}
928 	spin_unlock(&vm->freed_lock);
929 
930 	return 0;
931 
932 }
933 
934 /**
935  * amdgpu_vm_clear_invalids - clear invalidated BOs in the PT
936  *
937  * @adev: amdgpu_device pointer
938  * @vm: requested vm
939  *
940  * Make sure all invalidated BOs are cleared in the PT.
941  * Returns 0 for success.
942  *
943  * PTs have to be reserved and mutex must be locked!
944  */
945 int amdgpu_vm_clear_invalids(struct amdgpu_device *adev,
946 			     struct amdgpu_vm *vm, struct amdgpu_sync *sync)
947 {
948 	struct amdgpu_bo_va *bo_va = NULL;
949 	int r = 0;
950 
951 	spin_lock(&vm->status_lock);
952 	while (!list_empty(&vm->invalidated)) {
953 		bo_va = list_first_entry(&vm->invalidated,
954 			struct amdgpu_bo_va, vm_status);
955 		spin_unlock(&vm->status_lock);
956 		mutex_lock(&bo_va->mutex);
957 		r = amdgpu_vm_bo_update(adev, bo_va, NULL);
958 		mutex_unlock(&bo_va->mutex);
959 		if (r)
960 			return r;
961 
962 		spin_lock(&vm->status_lock);
963 	}
964 	spin_unlock(&vm->status_lock);
965 
966 	if (bo_va)
967 		r = amdgpu_sync_fence(adev, sync, bo_va->last_pt_update);
968 
969 	return r;
970 }
971 
972 /**
973  * amdgpu_vm_bo_add - add a bo to a specific vm
974  *
975  * @adev: amdgpu_device pointer
976  * @vm: requested vm
977  * @bo: amdgpu buffer object
978  *
979  * Add @bo into the requested vm (cayman+).
980  * Add @bo to the list of bos associated with the vm
981  * Returns newly added bo_va or NULL for failure
982  *
983  * Object has to be reserved!
984  */
985 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
986 				      struct amdgpu_vm *vm,
987 				      struct amdgpu_bo *bo)
988 {
989 	struct amdgpu_bo_va *bo_va;
990 
991 	bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
992 	if (bo_va == NULL) {
993 		return NULL;
994 	}
995 	bo_va->vm = vm;
996 	bo_va->bo = bo;
997 	bo_va->ref_count = 1;
998 	INIT_LIST_HEAD(&bo_va->bo_list);
999 	INIT_LIST_HEAD(&bo_va->valids);
1000 	INIT_LIST_HEAD(&bo_va->invalids);
1001 	INIT_LIST_HEAD(&bo_va->vm_status);
1002 	mutex_init(&bo_va->mutex);
1003 	list_add_tail(&bo_va->bo_list, &bo->va);
1004 
1005 	return bo_va;
1006 }
1007 
1008 /**
1009  * amdgpu_vm_bo_map - map bo inside a vm
1010  *
1011  * @adev: amdgpu_device pointer
1012  * @bo_va: bo_va to store the address
1013  * @saddr: where to map the BO
1014  * @offset: requested offset in the BO
1015  * @flags: attributes of pages (read/write/valid/etc.)
1016  *
1017  * Add a mapping of the BO at the specefied addr into the VM.
1018  * Returns 0 for success, error for failure.
1019  *
1020  * Object has to be reserved and unreserved outside!
1021  */
1022 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1023 		     struct amdgpu_bo_va *bo_va,
1024 		     uint64_t saddr, uint64_t offset,
1025 		     uint64_t size, uint32_t flags)
1026 {
1027 	struct amdgpu_bo_va_mapping *mapping;
1028 	struct amdgpu_vm *vm = bo_va->vm;
1029 	struct interval_tree_node *it;
1030 	unsigned last_pfn, pt_idx;
1031 	uint64_t eaddr;
1032 	int r;
1033 
1034 	/* validate the parameters */
1035 	if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1036 	    size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1037 		return -EINVAL;
1038 
1039 	/* make sure object fit at this offset */
1040 	eaddr = saddr + size - 1;
1041 	if ((saddr >= eaddr) || (offset + size > amdgpu_bo_size(bo_va->bo)))
1042 		return -EINVAL;
1043 
1044 	last_pfn = eaddr / AMDGPU_GPU_PAGE_SIZE;
1045 	if (last_pfn >= adev->vm_manager.max_pfn) {
1046 		dev_err(adev->dev, "va above limit (0x%08X >= 0x%08X)\n",
1047 			last_pfn, adev->vm_manager.max_pfn);
1048 		return -EINVAL;
1049 	}
1050 
1051 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1052 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
1053 
1054 	spin_lock(&vm->it_lock);
1055 	it = interval_tree_iter_first(&vm->va, saddr, eaddr);
1056 	spin_unlock(&vm->it_lock);
1057 	if (it) {
1058 		struct amdgpu_bo_va_mapping *tmp;
1059 		tmp = container_of(it, struct amdgpu_bo_va_mapping, it);
1060 		/* bo and tmp overlap, invalid addr */
1061 		dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1062 			"0x%010lx-0x%010lx\n", bo_va->bo, saddr, eaddr,
1063 			tmp->it.start, tmp->it.last + 1);
1064 		r = -EINVAL;
1065 		goto error;
1066 	}
1067 
1068 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1069 	if (!mapping) {
1070 		r = -ENOMEM;
1071 		goto error;
1072 	}
1073 
1074 	INIT_LIST_HEAD(&mapping->list);
1075 	mapping->it.start = saddr;
1076 	mapping->it.last = eaddr;
1077 	mapping->offset = offset;
1078 	mapping->flags = flags;
1079 
1080 	mutex_lock(&bo_va->mutex);
1081 	list_add(&mapping->list, &bo_va->invalids);
1082 	mutex_unlock(&bo_va->mutex);
1083 	spin_lock(&vm->it_lock);
1084 	interval_tree_insert(&mapping->it, &vm->va);
1085 	spin_unlock(&vm->it_lock);
1086 	trace_amdgpu_vm_bo_map(bo_va, mapping);
1087 
1088 	/* Make sure the page tables are allocated */
1089 	saddr >>= amdgpu_vm_block_size;
1090 	eaddr >>= amdgpu_vm_block_size;
1091 
1092 	BUG_ON(eaddr >= amdgpu_vm_num_pdes(adev));
1093 
1094 	if (eaddr > vm->max_pde_used)
1095 		vm->max_pde_used = eaddr;
1096 
1097 	/* walk over the address space and allocate the page tables */
1098 	for (pt_idx = saddr; pt_idx <= eaddr; ++pt_idx) {
1099 		struct reservation_object *resv = vm->page_directory->tbo.resv;
1100 		struct amdgpu_bo_list_entry *entry;
1101 		struct amdgpu_bo *pt;
1102 
1103 		entry = &vm->page_tables[pt_idx].entry;
1104 		if (entry->robj)
1105 			continue;
1106 
1107 		r = amdgpu_bo_create(adev, AMDGPU_VM_PTE_COUNT * 8,
1108 				     AMDGPU_GPU_PAGE_SIZE, true,
1109 				     AMDGPU_GEM_DOMAIN_VRAM,
1110 				     AMDGPU_GEM_CREATE_NO_CPU_ACCESS,
1111 				     NULL, resv, &pt);
1112 		if (r)
1113 			goto error_free;
1114 
1115 		/* Keep a reference to the page table to avoid freeing
1116 		 * them up in the wrong order.
1117 		 */
1118 		pt->parent = amdgpu_bo_ref(vm->page_directory);
1119 
1120 		r = amdgpu_vm_clear_bo(adev, pt);
1121 		if (r) {
1122 			amdgpu_bo_unref(&pt);
1123 			goto error_free;
1124 		}
1125 
1126 		entry->robj = pt;
1127 		entry->prefered_domains = AMDGPU_GEM_DOMAIN_VRAM;
1128 		entry->allowed_domains = AMDGPU_GEM_DOMAIN_VRAM;
1129 		entry->priority = 0;
1130 		entry->tv.bo = &entry->robj->tbo;
1131 		entry->tv.shared = true;
1132 		vm->page_tables[pt_idx].addr = 0;
1133 	}
1134 
1135 	return 0;
1136 
1137 error_free:
1138 	list_del(&mapping->list);
1139 	spin_lock(&vm->it_lock);
1140 	interval_tree_remove(&mapping->it, &vm->va);
1141 	spin_unlock(&vm->it_lock);
1142 	trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1143 	kfree(mapping);
1144 
1145 error:
1146 	return r;
1147 }
1148 
1149 /**
1150  * amdgpu_vm_bo_unmap - remove bo mapping from vm
1151  *
1152  * @adev: amdgpu_device pointer
1153  * @bo_va: bo_va to remove the address from
1154  * @saddr: where to the BO is mapped
1155  *
1156  * Remove a mapping of the BO at the specefied addr from the VM.
1157  * Returns 0 for success, error for failure.
1158  *
1159  * Object has to be reserved and unreserved outside!
1160  */
1161 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
1162 		       struct amdgpu_bo_va *bo_va,
1163 		       uint64_t saddr)
1164 {
1165 	struct amdgpu_bo_va_mapping *mapping;
1166 	struct amdgpu_vm *vm = bo_va->vm;
1167 	bool valid = true;
1168 
1169 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1170 	mutex_lock(&bo_va->mutex);
1171 	list_for_each_entry(mapping, &bo_va->valids, list) {
1172 		if (mapping->it.start == saddr)
1173 			break;
1174 	}
1175 
1176 	if (&mapping->list == &bo_va->valids) {
1177 		valid = false;
1178 
1179 		list_for_each_entry(mapping, &bo_va->invalids, list) {
1180 			if (mapping->it.start == saddr)
1181 				break;
1182 		}
1183 
1184 		if (&mapping->list == &bo_va->invalids) {
1185 			mutex_unlock(&bo_va->mutex);
1186 			return -ENOENT;
1187 		}
1188 	}
1189 	mutex_unlock(&bo_va->mutex);
1190 	list_del(&mapping->list);
1191 	spin_lock(&vm->it_lock);
1192 	interval_tree_remove(&mapping->it, &vm->va);
1193 	spin_unlock(&vm->it_lock);
1194 	trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1195 
1196 	if (valid) {
1197 		spin_lock(&vm->freed_lock);
1198 		list_add(&mapping->list, &vm->freed);
1199 		spin_unlock(&vm->freed_lock);
1200 	} else {
1201 		kfree(mapping);
1202 	}
1203 
1204 	return 0;
1205 }
1206 
1207 /**
1208  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
1209  *
1210  * @adev: amdgpu_device pointer
1211  * @bo_va: requested bo_va
1212  *
1213  * Remove @bo_va->bo from the requested vm (cayman+).
1214  *
1215  * Object have to be reserved!
1216  */
1217 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
1218 		      struct amdgpu_bo_va *bo_va)
1219 {
1220 	struct amdgpu_bo_va_mapping *mapping, *next;
1221 	struct amdgpu_vm *vm = bo_va->vm;
1222 
1223 	list_del(&bo_va->bo_list);
1224 
1225 	spin_lock(&vm->status_lock);
1226 	list_del(&bo_va->vm_status);
1227 	spin_unlock(&vm->status_lock);
1228 
1229 	list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
1230 		list_del(&mapping->list);
1231 		spin_lock(&vm->it_lock);
1232 		interval_tree_remove(&mapping->it, &vm->va);
1233 		spin_unlock(&vm->it_lock);
1234 		trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1235 		spin_lock(&vm->freed_lock);
1236 		list_add(&mapping->list, &vm->freed);
1237 		spin_unlock(&vm->freed_lock);
1238 	}
1239 	list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
1240 		list_del(&mapping->list);
1241 		spin_lock(&vm->it_lock);
1242 		interval_tree_remove(&mapping->it, &vm->va);
1243 		spin_unlock(&vm->it_lock);
1244 		kfree(mapping);
1245 	}
1246 	fence_put(bo_va->last_pt_update);
1247 	mutex_destroy(&bo_va->mutex);
1248 	kfree(bo_va);
1249 }
1250 
1251 /**
1252  * amdgpu_vm_bo_invalidate - mark the bo as invalid
1253  *
1254  * @adev: amdgpu_device pointer
1255  * @vm: requested vm
1256  * @bo: amdgpu buffer object
1257  *
1258  * Mark @bo as invalid (cayman+).
1259  */
1260 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
1261 			     struct amdgpu_bo *bo)
1262 {
1263 	struct amdgpu_bo_va *bo_va;
1264 
1265 	list_for_each_entry(bo_va, &bo->va, bo_list) {
1266 		spin_lock(&bo_va->vm->status_lock);
1267 		if (list_empty(&bo_va->vm_status))
1268 			list_add(&bo_va->vm_status, &bo_va->vm->invalidated);
1269 		spin_unlock(&bo_va->vm->status_lock);
1270 	}
1271 }
1272 
1273 /**
1274  * amdgpu_vm_init - initialize a vm instance
1275  *
1276  * @adev: amdgpu_device pointer
1277  * @vm: requested vm
1278  *
1279  * Init @vm fields (cayman+).
1280  */
1281 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1282 {
1283 	const unsigned align = min(AMDGPU_VM_PTB_ALIGN_SIZE,
1284 		AMDGPU_VM_PTE_COUNT * 8);
1285 	unsigned pd_size, pd_entries;
1286 	int i, r;
1287 
1288 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
1289 		vm->ids[i].id = 0;
1290 		vm->ids[i].flushed_updates = NULL;
1291 	}
1292 	vm->va = RB_ROOT;
1293 	spin_lock_init(&vm->status_lock);
1294 	INIT_LIST_HEAD(&vm->invalidated);
1295 	INIT_LIST_HEAD(&vm->cleared);
1296 	INIT_LIST_HEAD(&vm->freed);
1297 	spin_lock_init(&vm->it_lock);
1298 	spin_lock_init(&vm->freed_lock);
1299 	pd_size = amdgpu_vm_directory_size(adev);
1300 	pd_entries = amdgpu_vm_num_pdes(adev);
1301 
1302 	/* allocate page table array */
1303 	vm->page_tables = drm_calloc_large(pd_entries, sizeof(struct amdgpu_vm_pt));
1304 	if (vm->page_tables == NULL) {
1305 		DRM_ERROR("Cannot allocate memory for page table array\n");
1306 		return -ENOMEM;
1307 	}
1308 
1309 	vm->page_directory_fence = NULL;
1310 
1311 	r = amdgpu_bo_create(adev, pd_size, align, true,
1312 			     AMDGPU_GEM_DOMAIN_VRAM,
1313 			     AMDGPU_GEM_CREATE_NO_CPU_ACCESS,
1314 			     NULL, NULL, &vm->page_directory);
1315 	if (r)
1316 		return r;
1317 	r = amdgpu_bo_reserve(vm->page_directory, false);
1318 	if (r) {
1319 		amdgpu_bo_unref(&vm->page_directory);
1320 		vm->page_directory = NULL;
1321 		return r;
1322 	}
1323 	r = amdgpu_vm_clear_bo(adev, vm->page_directory);
1324 	amdgpu_bo_unreserve(vm->page_directory);
1325 	if (r) {
1326 		amdgpu_bo_unref(&vm->page_directory);
1327 		vm->page_directory = NULL;
1328 		return r;
1329 	}
1330 
1331 	return 0;
1332 }
1333 
1334 /**
1335  * amdgpu_vm_fini - tear down a vm instance
1336  *
1337  * @adev: amdgpu_device pointer
1338  * @vm: requested vm
1339  *
1340  * Tear down @vm (cayman+).
1341  * Unbind the VM and remove all bos from the vm bo list
1342  */
1343 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1344 {
1345 	struct amdgpu_bo_va_mapping *mapping, *tmp;
1346 	int i;
1347 
1348 	if (!RB_EMPTY_ROOT(&vm->va)) {
1349 		dev_err(adev->dev, "still active bo inside vm\n");
1350 	}
1351 	rbtree_postorder_for_each_entry_safe(mapping, tmp, &vm->va, it.rb) {
1352 		list_del(&mapping->list);
1353 		interval_tree_remove(&mapping->it, &vm->va);
1354 		kfree(mapping);
1355 	}
1356 	list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
1357 		list_del(&mapping->list);
1358 		kfree(mapping);
1359 	}
1360 
1361 	for (i = 0; i < amdgpu_vm_num_pdes(adev); i++)
1362 		amdgpu_bo_unref(&vm->page_tables[i].entry.robj);
1363 	drm_free_large(vm->page_tables);
1364 
1365 	amdgpu_bo_unref(&vm->page_directory);
1366 	fence_put(vm->page_directory_fence);
1367 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i) {
1368 		unsigned id = vm->ids[i].id;
1369 
1370 		atomic_long_cmpxchg(&adev->vm_manager.ids[id].owner,
1371 				    (long)vm, 0);
1372 		fence_put(vm->ids[i].flushed_updates);
1373 	}
1374 
1375 }
1376 
1377 /**
1378  * amdgpu_vm_manager_fini - cleanup VM manager
1379  *
1380  * @adev: amdgpu_device pointer
1381  *
1382  * Cleanup the VM manager and free resources.
1383  */
1384 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
1385 {
1386 	unsigned i;
1387 
1388 	for (i = 0; i < AMDGPU_NUM_VM; ++i)
1389 		fence_put(adev->vm_manager.ids[i].active);
1390 }
1391