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 <linux/dma-fence-array.h>
29 #include <linux/interval_tree_generic.h>
30 #include <linux/idr.h>
31 #include <drm/drmP.h>
32 #include <drm/amdgpu_drm.h>
33 #include "amdgpu.h"
34 #include "amdgpu_trace.h"
35 
36 /*
37  * PASID manager
38  *
39  * PASIDs are global address space identifiers that can be shared
40  * between the GPU, an IOMMU and the driver. VMs on different devices
41  * may use the same PASID if they share the same address
42  * space. Therefore PASIDs are allocated using a global IDA. VMs are
43  * looked up from the PASID per amdgpu_device.
44  */
45 static DEFINE_IDA(amdgpu_vm_pasid_ida);
46 
47 /**
48  * amdgpu_vm_alloc_pasid - Allocate a PASID
49  * @bits: Maximum width of the PASID in bits, must be at least 1
50  *
51  * Allocates a PASID of the given width while keeping smaller PASIDs
52  * available if possible.
53  *
54  * Returns a positive integer on success. Returns %-EINVAL if bits==0.
55  * Returns %-ENOSPC if no PASID was available. Returns %-ENOMEM on
56  * memory allocation failure.
57  */
58 int amdgpu_vm_alloc_pasid(unsigned int bits)
59 {
60 	int pasid = -EINVAL;
61 
62 	for (bits = min(bits, 31U); bits > 0; bits--) {
63 		pasid = ida_simple_get(&amdgpu_vm_pasid_ida,
64 				       1U << (bits - 1), 1U << bits,
65 				       GFP_KERNEL);
66 		if (pasid != -ENOSPC)
67 			break;
68 	}
69 
70 	return pasid;
71 }
72 
73 /**
74  * amdgpu_vm_free_pasid - Free a PASID
75  * @pasid: PASID to free
76  */
77 void amdgpu_vm_free_pasid(unsigned int pasid)
78 {
79 	ida_simple_remove(&amdgpu_vm_pasid_ida, pasid);
80 }
81 
82 /*
83  * GPUVM
84  * GPUVM is similar to the legacy gart on older asics, however
85  * rather than there being a single global gart table
86  * for the entire GPU, there are multiple VM page tables active
87  * at any given time.  The VM page tables can contain a mix
88  * vram pages and system memory pages and system memory pages
89  * can be mapped as snooped (cached system pages) or unsnooped
90  * (uncached system pages).
91  * Each VM has an ID associated with it and there is a page table
92  * associated with each VMID.  When execting a command buffer,
93  * the kernel tells the the ring what VMID to use for that command
94  * buffer.  VMIDs are allocated dynamically as commands are submitted.
95  * The userspace drivers maintain their own address space and the kernel
96  * sets up their pages tables accordingly when they submit their
97  * command buffers and a VMID is assigned.
98  * Cayman/Trinity support up to 8 active VMs at any given time;
99  * SI supports 16.
100  */
101 
102 #define START(node) ((node)->start)
103 #define LAST(node) ((node)->last)
104 
105 INTERVAL_TREE_DEFINE(struct amdgpu_bo_va_mapping, rb, uint64_t, __subtree_last,
106 		     START, LAST, static, amdgpu_vm_it)
107 
108 #undef START
109 #undef LAST
110 
111 /* Local structure. Encapsulate some VM table update parameters to reduce
112  * the number of function parameters
113  */
114 struct amdgpu_pte_update_params {
115 	/* amdgpu device we do this update for */
116 	struct amdgpu_device *adev;
117 	/* optional amdgpu_vm we do this update for */
118 	struct amdgpu_vm *vm;
119 	/* address where to copy page table entries from */
120 	uint64_t src;
121 	/* indirect buffer to fill with commands */
122 	struct amdgpu_ib *ib;
123 	/* Function which actually does the update */
124 	void (*func)(struct amdgpu_pte_update_params *params, uint64_t pe,
125 		     uint64_t addr, unsigned count, uint32_t incr,
126 		     uint64_t flags);
127 	/* The next two are used during VM update by CPU
128 	 *  DMA addresses to use for mapping
129 	 *  Kernel pointer of PD/PT BO that needs to be updated
130 	 */
131 	dma_addr_t *pages_addr;
132 	void *kptr;
133 };
134 
135 /* Helper to disable partial resident texture feature from a fence callback */
136 struct amdgpu_prt_cb {
137 	struct amdgpu_device *adev;
138 	struct dma_fence_cb cb;
139 };
140 
141 /**
142  * amdgpu_vm_num_entries - return the number of entries in a PD/PT
143  *
144  * @adev: amdgpu_device pointer
145  *
146  * Calculate the number of entries in a page directory or page table.
147  */
148 static unsigned amdgpu_vm_num_entries(struct amdgpu_device *adev,
149 				      unsigned level)
150 {
151 	if (level == 0)
152 		/* For the root directory */
153 		return adev->vm_manager.max_pfn >>
154 			(adev->vm_manager.block_size *
155 			 adev->vm_manager.num_level);
156 	else if (level == adev->vm_manager.num_level)
157 		/* For the page tables on the leaves */
158 		return AMDGPU_VM_PTE_COUNT(adev);
159 	else
160 		/* Everything in between */
161 		return 1 << adev->vm_manager.block_size;
162 }
163 
164 /**
165  * amdgpu_vm_bo_size - returns the size of the BOs in bytes
166  *
167  * @adev: amdgpu_device pointer
168  *
169  * Calculate the size of the BO for a page directory or page table in bytes.
170  */
171 static unsigned amdgpu_vm_bo_size(struct amdgpu_device *adev, unsigned level)
172 {
173 	return AMDGPU_GPU_PAGE_ALIGN(amdgpu_vm_num_entries(adev, level) * 8);
174 }
175 
176 /**
177  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
178  *
179  * @vm: vm providing the BOs
180  * @validated: head of validation list
181  * @entry: entry to add
182  *
183  * Add the page directory to the list of BOs to
184  * validate for command submission.
185  */
186 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
187 			 struct list_head *validated,
188 			 struct amdgpu_bo_list_entry *entry)
189 {
190 	entry->robj = vm->root.base.bo;
191 	entry->priority = 0;
192 	entry->tv.bo = &entry->robj->tbo;
193 	entry->tv.shared = true;
194 	entry->user_pages = NULL;
195 	list_add(&entry->tv.head, validated);
196 }
197 
198 /**
199  * amdgpu_vm_validate_pt_bos - validate the page table BOs
200  *
201  * @adev: amdgpu device pointer
202  * @vm: vm providing the BOs
203  * @validate: callback to do the validation
204  * @param: parameter for the validation callback
205  *
206  * Validate the page table BOs on command submission if neccessary.
207  */
208 int amdgpu_vm_validate_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
209 			      int (*validate)(void *p, struct amdgpu_bo *bo),
210 			      void *param)
211 {
212 	struct ttm_bo_global *glob = adev->mman.bdev.glob;
213 	int r;
214 
215 	spin_lock(&vm->status_lock);
216 	while (!list_empty(&vm->evicted)) {
217 		struct amdgpu_vm_bo_base *bo_base;
218 		struct amdgpu_bo *bo;
219 
220 		bo_base = list_first_entry(&vm->evicted,
221 					   struct amdgpu_vm_bo_base,
222 					   vm_status);
223 		spin_unlock(&vm->status_lock);
224 
225 		bo = bo_base->bo;
226 		BUG_ON(!bo);
227 		if (bo->parent) {
228 			r = validate(param, bo);
229 			if (r)
230 				return r;
231 
232 			spin_lock(&glob->lru_lock);
233 			ttm_bo_move_to_lru_tail(&bo->tbo);
234 			if (bo->shadow)
235 				ttm_bo_move_to_lru_tail(&bo->shadow->tbo);
236 			spin_unlock(&glob->lru_lock);
237 		}
238 
239 		if (bo->tbo.type == ttm_bo_type_kernel &&
240 		    vm->use_cpu_for_update) {
241 			r = amdgpu_bo_kmap(bo, NULL);
242 			if (r)
243 				return r;
244 		}
245 
246 		spin_lock(&vm->status_lock);
247 		if (bo->tbo.type != ttm_bo_type_kernel)
248 			list_move(&bo_base->vm_status, &vm->moved);
249 		else
250 			list_move(&bo_base->vm_status, &vm->relocated);
251 	}
252 	spin_unlock(&vm->status_lock);
253 
254 	return 0;
255 }
256 
257 /**
258  * amdgpu_vm_ready - check VM is ready for updates
259  *
260  * @vm: VM to check
261  *
262  * Check if all VM PDs/PTs are ready for updates
263  */
264 bool amdgpu_vm_ready(struct amdgpu_vm *vm)
265 {
266 	bool ready;
267 
268 	spin_lock(&vm->status_lock);
269 	ready = list_empty(&vm->evicted);
270 	spin_unlock(&vm->status_lock);
271 
272 	return ready;
273 }
274 
275 /**
276  * amdgpu_vm_alloc_levels - allocate the PD/PT levels
277  *
278  * @adev: amdgpu_device pointer
279  * @vm: requested vm
280  * @saddr: start of the address range
281  * @eaddr: end of the address range
282  *
283  * Make sure the page directories and page tables are allocated
284  */
285 static int amdgpu_vm_alloc_levels(struct amdgpu_device *adev,
286 				  struct amdgpu_vm *vm,
287 				  struct amdgpu_vm_pt *parent,
288 				  uint64_t saddr, uint64_t eaddr,
289 				  unsigned level)
290 {
291 	unsigned shift = (adev->vm_manager.num_level - level) *
292 		adev->vm_manager.block_size;
293 	unsigned pt_idx, from, to;
294 	int r;
295 	u64 flags;
296 	uint64_t init_value = 0;
297 
298 	if (!parent->entries) {
299 		unsigned num_entries = amdgpu_vm_num_entries(adev, level);
300 
301 		parent->entries = kvmalloc_array(num_entries,
302 						   sizeof(struct amdgpu_vm_pt),
303 						   GFP_KERNEL | __GFP_ZERO);
304 		if (!parent->entries)
305 			return -ENOMEM;
306 		memset(parent->entries, 0 , sizeof(struct amdgpu_vm_pt));
307 	}
308 
309 	from = saddr >> shift;
310 	to = eaddr >> shift;
311 	if (from >= amdgpu_vm_num_entries(adev, level) ||
312 	    to >= amdgpu_vm_num_entries(adev, level))
313 		return -EINVAL;
314 
315 	if (to > parent->last_entry_used)
316 		parent->last_entry_used = to;
317 
318 	++level;
319 	saddr = saddr & ((1 << shift) - 1);
320 	eaddr = eaddr & ((1 << shift) - 1);
321 
322 	flags = AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS |
323 			AMDGPU_GEM_CREATE_VRAM_CLEARED;
324 	if (vm->use_cpu_for_update)
325 		flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
326 	else
327 		flags |= (AMDGPU_GEM_CREATE_NO_CPU_ACCESS |
328 				AMDGPU_GEM_CREATE_SHADOW);
329 
330 	if (vm->pte_support_ats) {
331 		init_value = AMDGPU_PTE_DEFAULT_ATC;
332 		if (level != adev->vm_manager.num_level - 1)
333 			init_value |= AMDGPU_PDE_PTE;
334 
335 	}
336 
337 	/* walk over the address space and allocate the page tables */
338 	for (pt_idx = from; pt_idx <= to; ++pt_idx) {
339 		struct reservation_object *resv = vm->root.base.bo->tbo.resv;
340 		struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
341 		struct amdgpu_bo *pt;
342 
343 		if (!entry->base.bo) {
344 			r = amdgpu_bo_create(adev,
345 					     amdgpu_vm_bo_size(adev, level),
346 					     AMDGPU_GPU_PAGE_SIZE, true,
347 					     AMDGPU_GEM_DOMAIN_VRAM,
348 					     flags,
349 					     NULL, resv, init_value, &pt);
350 			if (r)
351 				return r;
352 
353 			if (vm->use_cpu_for_update) {
354 				r = amdgpu_bo_kmap(pt, NULL);
355 				if (r) {
356 					amdgpu_bo_unref(&pt);
357 					return r;
358 				}
359 			}
360 
361 			/* Keep a reference to the root directory to avoid
362 			* freeing them up in the wrong order.
363 			*/
364 			pt->parent = amdgpu_bo_ref(parent->base.bo);
365 
366 			entry->base.vm = vm;
367 			entry->base.bo = pt;
368 			list_add_tail(&entry->base.bo_list, &pt->va);
369 			spin_lock(&vm->status_lock);
370 			list_add(&entry->base.vm_status, &vm->relocated);
371 			spin_unlock(&vm->status_lock);
372 			entry->addr = 0;
373 		}
374 
375 		if (level < adev->vm_manager.num_level) {
376 			uint64_t sub_saddr = (pt_idx == from) ? saddr : 0;
377 			uint64_t sub_eaddr = (pt_idx == to) ? eaddr :
378 				((1 << shift) - 1);
379 			r = amdgpu_vm_alloc_levels(adev, vm, entry, sub_saddr,
380 						   sub_eaddr, level);
381 			if (r)
382 				return r;
383 		}
384 	}
385 
386 	return 0;
387 }
388 
389 /**
390  * amdgpu_vm_alloc_pts - Allocate page tables.
391  *
392  * @adev: amdgpu_device pointer
393  * @vm: VM to allocate page tables for
394  * @saddr: Start address which needs to be allocated
395  * @size: Size from start address we need.
396  *
397  * Make sure the page tables are allocated.
398  */
399 int amdgpu_vm_alloc_pts(struct amdgpu_device *adev,
400 			struct amdgpu_vm *vm,
401 			uint64_t saddr, uint64_t size)
402 {
403 	uint64_t last_pfn;
404 	uint64_t eaddr;
405 
406 	/* validate the parameters */
407 	if (saddr & AMDGPU_GPU_PAGE_MASK || size & AMDGPU_GPU_PAGE_MASK)
408 		return -EINVAL;
409 
410 	eaddr = saddr + size - 1;
411 	last_pfn = eaddr / AMDGPU_GPU_PAGE_SIZE;
412 	if (last_pfn >= adev->vm_manager.max_pfn) {
413 		dev_err(adev->dev, "va above limit (0x%08llX >= 0x%08llX)\n",
414 			last_pfn, adev->vm_manager.max_pfn);
415 		return -EINVAL;
416 	}
417 
418 	saddr /= AMDGPU_GPU_PAGE_SIZE;
419 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
420 
421 	return amdgpu_vm_alloc_levels(adev, vm, &vm->root, saddr, eaddr, 0);
422 }
423 
424 /**
425  * amdgpu_vm_had_gpu_reset - check if reset occured since last use
426  *
427  * @adev: amdgpu_device pointer
428  * @id: VMID structure
429  *
430  * Check if GPU reset occured since last use of the VMID.
431  */
432 static bool amdgpu_vm_had_gpu_reset(struct amdgpu_device *adev,
433 				    struct amdgpu_vm_id *id)
434 {
435 	return id->current_gpu_reset_count !=
436 		atomic_read(&adev->gpu_reset_counter);
437 }
438 
439 static bool amdgpu_vm_reserved_vmid_ready(struct amdgpu_vm *vm, unsigned vmhub)
440 {
441 	return !!vm->reserved_vmid[vmhub];
442 }
443 
444 /* idr_mgr->lock must be held */
445 static int amdgpu_vm_grab_reserved_vmid_locked(struct amdgpu_vm *vm,
446 					       struct amdgpu_ring *ring,
447 					       struct amdgpu_sync *sync,
448 					       struct dma_fence *fence,
449 					       struct amdgpu_job *job)
450 {
451 	struct amdgpu_device *adev = ring->adev;
452 	unsigned vmhub = ring->funcs->vmhub;
453 	uint64_t fence_context = adev->fence_context + ring->idx;
454 	struct amdgpu_vm_id *id = vm->reserved_vmid[vmhub];
455 	struct amdgpu_vm_id_manager *id_mgr = &adev->vm_manager.id_mgr[vmhub];
456 	struct dma_fence *updates = sync->last_vm_update;
457 	int r = 0;
458 	struct dma_fence *flushed, *tmp;
459 	bool needs_flush = vm->use_cpu_for_update;
460 
461 	flushed  = id->flushed_updates;
462 	if ((amdgpu_vm_had_gpu_reset(adev, id)) ||
463 	    (atomic64_read(&id->owner) != vm->client_id) ||
464 	    (job->vm_pd_addr != id->pd_gpu_addr) ||
465 	    (updates && (!flushed || updates->context != flushed->context ||
466 			dma_fence_is_later(updates, flushed))) ||
467 	    (!id->last_flush || (id->last_flush->context != fence_context &&
468 				 !dma_fence_is_signaled(id->last_flush)))) {
469 		needs_flush = true;
470 		/* to prevent one context starved by another context */
471 		id->pd_gpu_addr = 0;
472 		tmp = amdgpu_sync_peek_fence(&id->active, ring);
473 		if (tmp) {
474 			r = amdgpu_sync_fence(adev, sync, tmp);
475 			return r;
476 		}
477 	}
478 
479 	/* Good we can use this VMID. Remember this submission as
480 	* user of the VMID.
481 	*/
482 	r = amdgpu_sync_fence(ring->adev, &id->active, fence);
483 	if (r)
484 		goto out;
485 
486 	if (updates && (!flushed || updates->context != flushed->context ||
487 			dma_fence_is_later(updates, flushed))) {
488 		dma_fence_put(id->flushed_updates);
489 		id->flushed_updates = dma_fence_get(updates);
490 	}
491 	id->pd_gpu_addr = job->vm_pd_addr;
492 	atomic64_set(&id->owner, vm->client_id);
493 	job->vm_needs_flush = needs_flush;
494 	if (needs_flush) {
495 		dma_fence_put(id->last_flush);
496 		id->last_flush = NULL;
497 	}
498 	job->vm_id = id - id_mgr->ids;
499 	trace_amdgpu_vm_grab_id(vm, ring, job);
500 out:
501 	return r;
502 }
503 
504 /**
505  * amdgpu_vm_grab_id - allocate the next free VMID
506  *
507  * @vm: vm to allocate id for
508  * @ring: ring we want to submit job to
509  * @sync: sync object where we add dependencies
510  * @fence: fence protecting ID from reuse
511  *
512  * Allocate an id for the vm, adding fences to the sync obj as necessary.
513  */
514 int amdgpu_vm_grab_id(struct amdgpu_vm *vm, struct amdgpu_ring *ring,
515 		      struct amdgpu_sync *sync, struct dma_fence *fence,
516 		      struct amdgpu_job *job)
517 {
518 	struct amdgpu_device *adev = ring->adev;
519 	unsigned vmhub = ring->funcs->vmhub;
520 	struct amdgpu_vm_id_manager *id_mgr = &adev->vm_manager.id_mgr[vmhub];
521 	uint64_t fence_context = adev->fence_context + ring->idx;
522 	struct dma_fence *updates = sync->last_vm_update;
523 	struct amdgpu_vm_id *id, *idle;
524 	struct dma_fence **fences;
525 	unsigned i;
526 	int r = 0;
527 
528 	mutex_lock(&id_mgr->lock);
529 	if (amdgpu_vm_reserved_vmid_ready(vm, vmhub)) {
530 		r = amdgpu_vm_grab_reserved_vmid_locked(vm, ring, sync, fence, job);
531 		mutex_unlock(&id_mgr->lock);
532 		return r;
533 	}
534 	fences = kmalloc_array(sizeof(void *), id_mgr->num_ids, GFP_KERNEL);
535 	if (!fences) {
536 		mutex_unlock(&id_mgr->lock);
537 		return -ENOMEM;
538 	}
539 	/* Check if we have an idle VMID */
540 	i = 0;
541 	list_for_each_entry(idle, &id_mgr->ids_lru, list) {
542 		fences[i] = amdgpu_sync_peek_fence(&idle->active, ring);
543 		if (!fences[i])
544 			break;
545 		++i;
546 	}
547 
548 	/* If we can't find a idle VMID to use, wait till one becomes available */
549 	if (&idle->list == &id_mgr->ids_lru) {
550 		u64 fence_context = adev->vm_manager.fence_context + ring->idx;
551 		unsigned seqno = ++adev->vm_manager.seqno[ring->idx];
552 		struct dma_fence_array *array;
553 		unsigned j;
554 
555 		for (j = 0; j < i; ++j)
556 			dma_fence_get(fences[j]);
557 
558 		array = dma_fence_array_create(i, fences, fence_context,
559 					   seqno, true);
560 		if (!array) {
561 			for (j = 0; j < i; ++j)
562 				dma_fence_put(fences[j]);
563 			kfree(fences);
564 			r = -ENOMEM;
565 			goto error;
566 		}
567 
568 
569 		r = amdgpu_sync_fence(ring->adev, sync, &array->base);
570 		dma_fence_put(&array->base);
571 		if (r)
572 			goto error;
573 
574 		mutex_unlock(&id_mgr->lock);
575 		return 0;
576 
577 	}
578 	kfree(fences);
579 
580 	job->vm_needs_flush = vm->use_cpu_for_update;
581 	/* Check if we can use a VMID already assigned to this VM */
582 	list_for_each_entry_reverse(id, &id_mgr->ids_lru, list) {
583 		struct dma_fence *flushed;
584 		bool needs_flush = vm->use_cpu_for_update;
585 
586 		/* Check all the prerequisites to using this VMID */
587 		if (amdgpu_vm_had_gpu_reset(adev, id))
588 			continue;
589 
590 		if (atomic64_read(&id->owner) != vm->client_id)
591 			continue;
592 
593 		if (job->vm_pd_addr != id->pd_gpu_addr)
594 			continue;
595 
596 		if (!id->last_flush ||
597 		    (id->last_flush->context != fence_context &&
598 		     !dma_fence_is_signaled(id->last_flush)))
599 			needs_flush = true;
600 
601 		flushed  = id->flushed_updates;
602 		if (updates && (!flushed || dma_fence_is_later(updates, flushed)))
603 			needs_flush = true;
604 
605 		/* Concurrent flushes are only possible starting with Vega10 */
606 		if (adev->asic_type < CHIP_VEGA10 && needs_flush)
607 			continue;
608 
609 		/* Good we can use this VMID. Remember this submission as
610 		 * user of the VMID.
611 		 */
612 		r = amdgpu_sync_fence(ring->adev, &id->active, fence);
613 		if (r)
614 			goto error;
615 
616 		if (updates && (!flushed || dma_fence_is_later(updates, flushed))) {
617 			dma_fence_put(id->flushed_updates);
618 			id->flushed_updates = dma_fence_get(updates);
619 		}
620 
621 		if (needs_flush)
622 			goto needs_flush;
623 		else
624 			goto no_flush_needed;
625 
626 	};
627 
628 	/* Still no ID to use? Then use the idle one found earlier */
629 	id = idle;
630 
631 	/* Remember this submission as user of the VMID */
632 	r = amdgpu_sync_fence(ring->adev, &id->active, fence);
633 	if (r)
634 		goto error;
635 
636 	id->pd_gpu_addr = job->vm_pd_addr;
637 	dma_fence_put(id->flushed_updates);
638 	id->flushed_updates = dma_fence_get(updates);
639 	atomic64_set(&id->owner, vm->client_id);
640 
641 needs_flush:
642 	job->vm_needs_flush = true;
643 	dma_fence_put(id->last_flush);
644 	id->last_flush = NULL;
645 
646 no_flush_needed:
647 	list_move_tail(&id->list, &id_mgr->ids_lru);
648 
649 	job->vm_id = id - id_mgr->ids;
650 	trace_amdgpu_vm_grab_id(vm, ring, job);
651 
652 error:
653 	mutex_unlock(&id_mgr->lock);
654 	return r;
655 }
656 
657 static void amdgpu_vm_free_reserved_vmid(struct amdgpu_device *adev,
658 					  struct amdgpu_vm *vm,
659 					  unsigned vmhub)
660 {
661 	struct amdgpu_vm_id_manager *id_mgr = &adev->vm_manager.id_mgr[vmhub];
662 
663 	mutex_lock(&id_mgr->lock);
664 	if (vm->reserved_vmid[vmhub]) {
665 		list_add(&vm->reserved_vmid[vmhub]->list,
666 			&id_mgr->ids_lru);
667 		vm->reserved_vmid[vmhub] = NULL;
668 		atomic_dec(&id_mgr->reserved_vmid_num);
669 	}
670 	mutex_unlock(&id_mgr->lock);
671 }
672 
673 static int amdgpu_vm_alloc_reserved_vmid(struct amdgpu_device *adev,
674 					 struct amdgpu_vm *vm,
675 					 unsigned vmhub)
676 {
677 	struct amdgpu_vm_id_manager *id_mgr;
678 	struct amdgpu_vm_id *idle;
679 	int r = 0;
680 
681 	id_mgr = &adev->vm_manager.id_mgr[vmhub];
682 	mutex_lock(&id_mgr->lock);
683 	if (vm->reserved_vmid[vmhub])
684 		goto unlock;
685 	if (atomic_inc_return(&id_mgr->reserved_vmid_num) >
686 	    AMDGPU_VM_MAX_RESERVED_VMID) {
687 		DRM_ERROR("Over limitation of reserved vmid\n");
688 		atomic_dec(&id_mgr->reserved_vmid_num);
689 		r = -EINVAL;
690 		goto unlock;
691 	}
692 	/* Select the first entry VMID */
693 	idle = list_first_entry(&id_mgr->ids_lru, struct amdgpu_vm_id, list);
694 	list_del_init(&idle->list);
695 	vm->reserved_vmid[vmhub] = idle;
696 	mutex_unlock(&id_mgr->lock);
697 
698 	return 0;
699 unlock:
700 	mutex_unlock(&id_mgr->lock);
701 	return r;
702 }
703 
704 /**
705  * amdgpu_vm_check_compute_bug - check whether asic has compute vm bug
706  *
707  * @adev: amdgpu_device pointer
708  */
709 void amdgpu_vm_check_compute_bug(struct amdgpu_device *adev)
710 {
711 	const struct amdgpu_ip_block *ip_block;
712 	bool has_compute_vm_bug;
713 	struct amdgpu_ring *ring;
714 	int i;
715 
716 	has_compute_vm_bug = false;
717 
718 	ip_block = amdgpu_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
719 	if (ip_block) {
720 		/* Compute has a VM bug for GFX version < 7.
721 		   Compute has a VM bug for GFX 8 MEC firmware version < 673.*/
722 		if (ip_block->version->major <= 7)
723 			has_compute_vm_bug = true;
724 		else if (ip_block->version->major == 8)
725 			if (adev->gfx.mec_fw_version < 673)
726 				has_compute_vm_bug = true;
727 	}
728 
729 	for (i = 0; i < adev->num_rings; i++) {
730 		ring = adev->rings[i];
731 		if (ring->funcs->type == AMDGPU_RING_TYPE_COMPUTE)
732 			/* only compute rings */
733 			ring->has_compute_vm_bug = has_compute_vm_bug;
734 		else
735 			ring->has_compute_vm_bug = false;
736 	}
737 }
738 
739 bool amdgpu_vm_need_pipeline_sync(struct amdgpu_ring *ring,
740 				  struct amdgpu_job *job)
741 {
742 	struct amdgpu_device *adev = ring->adev;
743 	unsigned vmhub = ring->funcs->vmhub;
744 	struct amdgpu_vm_id_manager *id_mgr = &adev->vm_manager.id_mgr[vmhub];
745 	struct amdgpu_vm_id *id;
746 	bool gds_switch_needed;
747 	bool vm_flush_needed = job->vm_needs_flush || ring->has_compute_vm_bug;
748 
749 	if (job->vm_id == 0)
750 		return false;
751 	id = &id_mgr->ids[job->vm_id];
752 	gds_switch_needed = ring->funcs->emit_gds_switch && (
753 		id->gds_base != job->gds_base ||
754 		id->gds_size != job->gds_size ||
755 		id->gws_base != job->gws_base ||
756 		id->gws_size != job->gws_size ||
757 		id->oa_base != job->oa_base ||
758 		id->oa_size != job->oa_size);
759 
760 	if (amdgpu_vm_had_gpu_reset(adev, id))
761 		return true;
762 
763 	return vm_flush_needed || gds_switch_needed;
764 }
765 
766 static bool amdgpu_vm_is_large_bar(struct amdgpu_device *adev)
767 {
768 	return (adev->mc.real_vram_size == adev->mc.visible_vram_size);
769 }
770 
771 /**
772  * amdgpu_vm_flush - hardware flush the vm
773  *
774  * @ring: ring to use for flush
775  * @vm_id: vmid number to use
776  * @pd_addr: address of the page directory
777  *
778  * Emit a VM flush when it is necessary.
779  */
780 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job, bool need_pipe_sync)
781 {
782 	struct amdgpu_device *adev = ring->adev;
783 	unsigned vmhub = ring->funcs->vmhub;
784 	struct amdgpu_vm_id_manager *id_mgr = &adev->vm_manager.id_mgr[vmhub];
785 	struct amdgpu_vm_id *id = &id_mgr->ids[job->vm_id];
786 	bool gds_switch_needed = ring->funcs->emit_gds_switch && (
787 		id->gds_base != job->gds_base ||
788 		id->gds_size != job->gds_size ||
789 		id->gws_base != job->gws_base ||
790 		id->gws_size != job->gws_size ||
791 		id->oa_base != job->oa_base ||
792 		id->oa_size != job->oa_size);
793 	bool vm_flush_needed = job->vm_needs_flush;
794 	unsigned patch_offset = 0;
795 	int r;
796 
797 	if (amdgpu_vm_had_gpu_reset(adev, id)) {
798 		gds_switch_needed = true;
799 		vm_flush_needed = true;
800 	}
801 
802 	if (!vm_flush_needed && !gds_switch_needed && !need_pipe_sync)
803 		return 0;
804 
805 	if (ring->funcs->init_cond_exec)
806 		patch_offset = amdgpu_ring_init_cond_exec(ring);
807 
808 	if (need_pipe_sync)
809 		amdgpu_ring_emit_pipeline_sync(ring);
810 
811 	if (ring->funcs->emit_vm_flush && vm_flush_needed) {
812 		struct dma_fence *fence;
813 
814 		trace_amdgpu_vm_flush(ring, job->vm_id, job->vm_pd_addr);
815 		amdgpu_ring_emit_vm_flush(ring, job->vm_id, job->vm_pd_addr);
816 
817 		r = amdgpu_fence_emit(ring, &fence);
818 		if (r)
819 			return r;
820 
821 		mutex_lock(&id_mgr->lock);
822 		dma_fence_put(id->last_flush);
823 		id->last_flush = fence;
824 		id->current_gpu_reset_count = atomic_read(&adev->gpu_reset_counter);
825 		mutex_unlock(&id_mgr->lock);
826 	}
827 
828 	if (ring->funcs->emit_gds_switch && gds_switch_needed) {
829 		id->gds_base = job->gds_base;
830 		id->gds_size = job->gds_size;
831 		id->gws_base = job->gws_base;
832 		id->gws_size = job->gws_size;
833 		id->oa_base = job->oa_base;
834 		id->oa_size = job->oa_size;
835 		amdgpu_ring_emit_gds_switch(ring, job->vm_id, job->gds_base,
836 					    job->gds_size, job->gws_base,
837 					    job->gws_size, job->oa_base,
838 					    job->oa_size);
839 	}
840 
841 	if (ring->funcs->patch_cond_exec)
842 		amdgpu_ring_patch_cond_exec(ring, patch_offset);
843 
844 	/* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
845 	if (ring->funcs->emit_switch_buffer) {
846 		amdgpu_ring_emit_switch_buffer(ring);
847 		amdgpu_ring_emit_switch_buffer(ring);
848 	}
849 	return 0;
850 }
851 
852 /**
853  * amdgpu_vm_reset_id - reset VMID to zero
854  *
855  * @adev: amdgpu device structure
856  * @vm_id: vmid number to use
857  *
858  * Reset saved GDW, GWS and OA to force switch on next flush.
859  */
860 void amdgpu_vm_reset_id(struct amdgpu_device *adev, unsigned vmhub,
861 			unsigned vmid)
862 {
863 	struct amdgpu_vm_id_manager *id_mgr = &adev->vm_manager.id_mgr[vmhub];
864 	struct amdgpu_vm_id *id = &id_mgr->ids[vmid];
865 
866 	atomic64_set(&id->owner, 0);
867 	id->gds_base = 0;
868 	id->gds_size = 0;
869 	id->gws_base = 0;
870 	id->gws_size = 0;
871 	id->oa_base = 0;
872 	id->oa_size = 0;
873 }
874 
875 /**
876  * amdgpu_vm_reset_all_id - reset VMID to zero
877  *
878  * @adev: amdgpu device structure
879  *
880  * Reset VMID to force flush on next use
881  */
882 void amdgpu_vm_reset_all_ids(struct amdgpu_device *adev)
883 {
884 	unsigned i, j;
885 
886 	for (i = 0; i < AMDGPU_MAX_VMHUBS; ++i) {
887 		struct amdgpu_vm_id_manager *id_mgr =
888 			&adev->vm_manager.id_mgr[i];
889 
890 		for (j = 1; j < id_mgr->num_ids; ++j)
891 			amdgpu_vm_reset_id(adev, i, j);
892 	}
893 }
894 
895 /**
896  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
897  *
898  * @vm: requested vm
899  * @bo: requested buffer object
900  *
901  * Find @bo inside the requested vm.
902  * Search inside the @bos vm list for the requested vm
903  * Returns the found bo_va or NULL if none is found
904  *
905  * Object has to be reserved!
906  */
907 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
908 				       struct amdgpu_bo *bo)
909 {
910 	struct amdgpu_bo_va *bo_va;
911 
912 	list_for_each_entry(bo_va, &bo->va, base.bo_list) {
913 		if (bo_va->base.vm == vm) {
914 			return bo_va;
915 		}
916 	}
917 	return NULL;
918 }
919 
920 /**
921  * amdgpu_vm_do_set_ptes - helper to call the right asic function
922  *
923  * @params: see amdgpu_pte_update_params definition
924  * @pe: addr of the page entry
925  * @addr: dst addr to write into pe
926  * @count: number of page entries to update
927  * @incr: increase next addr by incr bytes
928  * @flags: hw access flags
929  *
930  * Traces the parameters and calls the right asic functions
931  * to setup the page table using the DMA.
932  */
933 static void amdgpu_vm_do_set_ptes(struct amdgpu_pte_update_params *params,
934 				  uint64_t pe, uint64_t addr,
935 				  unsigned count, uint32_t incr,
936 				  uint64_t flags)
937 {
938 	trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
939 
940 	if (count < 3) {
941 		amdgpu_vm_write_pte(params->adev, params->ib, pe,
942 				    addr | flags, count, incr);
943 
944 	} else {
945 		amdgpu_vm_set_pte_pde(params->adev, params->ib, pe, addr,
946 				      count, incr, flags);
947 	}
948 }
949 
950 /**
951  * amdgpu_vm_do_copy_ptes - copy the PTEs from the GART
952  *
953  * @params: see amdgpu_pte_update_params definition
954  * @pe: addr of the page entry
955  * @addr: dst addr to write into pe
956  * @count: number of page entries to update
957  * @incr: increase next addr by incr bytes
958  * @flags: hw access flags
959  *
960  * Traces the parameters and calls the DMA function to copy the PTEs.
961  */
962 static void amdgpu_vm_do_copy_ptes(struct amdgpu_pte_update_params *params,
963 				   uint64_t pe, uint64_t addr,
964 				   unsigned count, uint32_t incr,
965 				   uint64_t flags)
966 {
967 	uint64_t src = (params->src + (addr >> 12) * 8);
968 
969 
970 	trace_amdgpu_vm_copy_ptes(pe, src, count);
971 
972 	amdgpu_vm_copy_pte(params->adev, params->ib, pe, src, count);
973 }
974 
975 /**
976  * amdgpu_vm_map_gart - Resolve gart mapping of addr
977  *
978  * @pages_addr: optional DMA address to use for lookup
979  * @addr: the unmapped addr
980  *
981  * Look up the physical address of the page that the pte resolves
982  * to and return the pointer for the page table entry.
983  */
984 static uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
985 {
986 	uint64_t result;
987 
988 	/* page table offset */
989 	result = pages_addr[addr >> PAGE_SHIFT];
990 
991 	/* in case cpu page size != gpu page size*/
992 	result |= addr & (~PAGE_MASK);
993 
994 	result &= 0xFFFFFFFFFFFFF000ULL;
995 
996 	return result;
997 }
998 
999 /**
1000  * amdgpu_vm_cpu_set_ptes - helper to update page tables via CPU
1001  *
1002  * @params: see amdgpu_pte_update_params definition
1003  * @pe: kmap addr of the page entry
1004  * @addr: dst addr to write into pe
1005  * @count: number of page entries to update
1006  * @incr: increase next addr by incr bytes
1007  * @flags: hw access flags
1008  *
1009  * Write count number of PT/PD entries directly.
1010  */
1011 static void amdgpu_vm_cpu_set_ptes(struct amdgpu_pte_update_params *params,
1012 				   uint64_t pe, uint64_t addr,
1013 				   unsigned count, uint32_t incr,
1014 				   uint64_t flags)
1015 {
1016 	unsigned int i;
1017 	uint64_t value;
1018 
1019 	trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
1020 
1021 	for (i = 0; i < count; i++) {
1022 		value = params->pages_addr ?
1023 			amdgpu_vm_map_gart(params->pages_addr, addr) :
1024 			addr;
1025 		amdgpu_gart_set_pte_pde(params->adev, (void *)(uintptr_t)pe,
1026 					i, value, flags);
1027 		addr += incr;
1028 	}
1029 }
1030 
1031 static int amdgpu_vm_wait_pd(struct amdgpu_device *adev, struct amdgpu_vm *vm,
1032 			     void *owner)
1033 {
1034 	struct amdgpu_sync sync;
1035 	int r;
1036 
1037 	amdgpu_sync_create(&sync);
1038 	amdgpu_sync_resv(adev, &sync, vm->root.base.bo->tbo.resv, owner, false);
1039 	r = amdgpu_sync_wait(&sync, true);
1040 	amdgpu_sync_free(&sync);
1041 
1042 	return r;
1043 }
1044 
1045 /*
1046  * amdgpu_vm_update_level - update a single level in the hierarchy
1047  *
1048  * @adev: amdgpu_device pointer
1049  * @vm: requested vm
1050  * @parent: parent directory
1051  *
1052  * Makes sure all entries in @parent are up to date.
1053  * Returns 0 for success, error for failure.
1054  */
1055 static int amdgpu_vm_update_level(struct amdgpu_device *adev,
1056 				  struct amdgpu_vm *vm,
1057 				  struct amdgpu_vm_pt *parent)
1058 {
1059 	struct amdgpu_bo *shadow;
1060 	struct amdgpu_ring *ring = NULL;
1061 	uint64_t pd_addr, shadow_addr = 0;
1062 	uint64_t last_pde = ~0, last_pt = ~0, last_shadow = ~0;
1063 	unsigned count = 0, pt_idx, ndw = 0;
1064 	struct amdgpu_job *job;
1065 	struct amdgpu_pte_update_params params;
1066 	struct dma_fence *fence = NULL;
1067 	uint32_t incr;
1068 
1069 	int r;
1070 
1071 	if (!parent->entries)
1072 		return 0;
1073 
1074 	memset(&params, 0, sizeof(params));
1075 	params.adev = adev;
1076 	shadow = parent->base.bo->shadow;
1077 
1078 	if (vm->use_cpu_for_update) {
1079 		pd_addr = (unsigned long)amdgpu_bo_kptr(parent->base.bo);
1080 		r = amdgpu_vm_wait_pd(adev, vm, AMDGPU_FENCE_OWNER_VM);
1081 		if (unlikely(r))
1082 			return r;
1083 
1084 		params.func = amdgpu_vm_cpu_set_ptes;
1085 	} else {
1086 		ring = container_of(vm->entity.sched, struct amdgpu_ring,
1087 				    sched);
1088 
1089 		/* padding, etc. */
1090 		ndw = 64;
1091 
1092 		/* assume the worst case */
1093 		ndw += parent->last_entry_used * 6;
1094 
1095 		pd_addr = amdgpu_bo_gpu_offset(parent->base.bo);
1096 
1097 		if (shadow) {
1098 			shadow_addr = amdgpu_bo_gpu_offset(shadow);
1099 			ndw *= 2;
1100 		} else {
1101 			shadow_addr = 0;
1102 		}
1103 
1104 		r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1105 		if (r)
1106 			return r;
1107 
1108 		params.ib = &job->ibs[0];
1109 		params.func = amdgpu_vm_do_set_ptes;
1110 	}
1111 
1112 
1113 	/* walk over the address space and update the directory */
1114 	for (pt_idx = 0; pt_idx <= parent->last_entry_used; ++pt_idx) {
1115 		struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
1116 		struct amdgpu_bo *bo = entry->base.bo;
1117 		uint64_t pde, pt;
1118 
1119 		if (bo == NULL)
1120 			continue;
1121 
1122 		spin_lock(&vm->status_lock);
1123 		list_del_init(&entry->base.vm_status);
1124 		spin_unlock(&vm->status_lock);
1125 
1126 		pt = amdgpu_bo_gpu_offset(bo);
1127 		pt = amdgpu_gart_get_vm_pde(adev, pt);
1128 		/* Don't update huge pages here */
1129 		if ((parent->entries[pt_idx].addr & AMDGPU_PDE_PTE) ||
1130 		    parent->entries[pt_idx].addr == (pt | AMDGPU_PTE_VALID))
1131 			continue;
1132 
1133 		parent->entries[pt_idx].addr = pt | AMDGPU_PTE_VALID;
1134 
1135 		pde = pd_addr + pt_idx * 8;
1136 		incr = amdgpu_bo_size(bo);
1137 		if (((last_pde + 8 * count) != pde) ||
1138 		    ((last_pt + incr * count) != pt) ||
1139 		    (count == AMDGPU_VM_MAX_UPDATE_SIZE)) {
1140 
1141 			if (count) {
1142 				if (shadow)
1143 					params.func(&params,
1144 						    last_shadow,
1145 						    last_pt, count,
1146 						    incr,
1147 						    AMDGPU_PTE_VALID);
1148 
1149 				params.func(&params, last_pde,
1150 					    last_pt, count, incr,
1151 					    AMDGPU_PTE_VALID);
1152 			}
1153 
1154 			count = 1;
1155 			last_pde = pde;
1156 			last_shadow = shadow_addr + pt_idx * 8;
1157 			last_pt = pt;
1158 		} else {
1159 			++count;
1160 		}
1161 	}
1162 
1163 	if (count) {
1164 		if (vm->root.base.bo->shadow)
1165 			params.func(&params, last_shadow, last_pt,
1166 				    count, incr, AMDGPU_PTE_VALID);
1167 
1168 		params.func(&params, last_pde, last_pt,
1169 			    count, incr, AMDGPU_PTE_VALID);
1170 	}
1171 
1172 	if (!vm->use_cpu_for_update) {
1173 		if (params.ib->length_dw == 0) {
1174 			amdgpu_job_free(job);
1175 		} else {
1176 			amdgpu_ring_pad_ib(ring, params.ib);
1177 			amdgpu_sync_resv(adev, &job->sync,
1178 					 parent->base.bo->tbo.resv,
1179 					 AMDGPU_FENCE_OWNER_VM, false);
1180 			if (shadow)
1181 				amdgpu_sync_resv(adev, &job->sync,
1182 						 shadow->tbo.resv,
1183 						 AMDGPU_FENCE_OWNER_VM, false);
1184 
1185 			WARN_ON(params.ib->length_dw > ndw);
1186 			r = amdgpu_job_submit(job, ring, &vm->entity,
1187 					AMDGPU_FENCE_OWNER_VM, &fence);
1188 			if (r)
1189 				goto error_free;
1190 
1191 			amdgpu_bo_fence(parent->base.bo, fence, true);
1192 			dma_fence_put(vm->last_update);
1193 			vm->last_update = fence;
1194 		}
1195 	}
1196 
1197 	return 0;
1198 
1199 error_free:
1200 	amdgpu_job_free(job);
1201 	return r;
1202 }
1203 
1204 /*
1205  * amdgpu_vm_invalidate_level - mark all PD levels as invalid
1206  *
1207  * @parent: parent PD
1208  *
1209  * Mark all PD level as invalid after an error.
1210  */
1211 static void amdgpu_vm_invalidate_level(struct amdgpu_vm *vm,
1212 				       struct amdgpu_vm_pt *parent)
1213 {
1214 	unsigned pt_idx;
1215 
1216 	/*
1217 	 * Recurse into the subdirectories. This recursion is harmless because
1218 	 * we only have a maximum of 5 layers.
1219 	 */
1220 	for (pt_idx = 0; pt_idx <= parent->last_entry_used; ++pt_idx) {
1221 		struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
1222 
1223 		if (!entry->base.bo)
1224 			continue;
1225 
1226 		entry->addr = ~0ULL;
1227 		spin_lock(&vm->status_lock);
1228 		if (list_empty(&entry->base.vm_status))
1229 			list_add(&entry->base.vm_status, &vm->relocated);
1230 		spin_unlock(&vm->status_lock);
1231 		amdgpu_vm_invalidate_level(vm, entry);
1232 	}
1233 }
1234 
1235 /*
1236  * amdgpu_vm_update_directories - make sure that all directories are valid
1237  *
1238  * @adev: amdgpu_device pointer
1239  * @vm: requested vm
1240  *
1241  * Makes sure all directories are up to date.
1242  * Returns 0 for success, error for failure.
1243  */
1244 int amdgpu_vm_update_directories(struct amdgpu_device *adev,
1245 				 struct amdgpu_vm *vm)
1246 {
1247 	int r = 0;
1248 
1249 	spin_lock(&vm->status_lock);
1250 	while (!list_empty(&vm->relocated)) {
1251 		struct amdgpu_vm_bo_base *bo_base;
1252 		struct amdgpu_bo *bo;
1253 
1254 		bo_base = list_first_entry(&vm->relocated,
1255 					   struct amdgpu_vm_bo_base,
1256 					   vm_status);
1257 		spin_unlock(&vm->status_lock);
1258 
1259 		bo = bo_base->bo->parent;
1260 		if (bo) {
1261 			struct amdgpu_vm_bo_base *parent;
1262 			struct amdgpu_vm_pt *pt;
1263 
1264 			parent = list_first_entry(&bo->va,
1265 						  struct amdgpu_vm_bo_base,
1266 						  bo_list);
1267 			pt = container_of(parent, struct amdgpu_vm_pt, base);
1268 
1269 			r = amdgpu_vm_update_level(adev, vm, pt);
1270 			if (r) {
1271 				amdgpu_vm_invalidate_level(vm, &vm->root);
1272 				return r;
1273 			}
1274 			spin_lock(&vm->status_lock);
1275 		} else {
1276 			spin_lock(&vm->status_lock);
1277 			list_del_init(&bo_base->vm_status);
1278 		}
1279 	}
1280 	spin_unlock(&vm->status_lock);
1281 
1282 	if (vm->use_cpu_for_update) {
1283 		/* Flush HDP */
1284 		mb();
1285 		amdgpu_gart_flush_gpu_tlb(adev, 0);
1286 	}
1287 
1288 	return r;
1289 }
1290 
1291 /**
1292  * amdgpu_vm_find_entry - find the entry for an address
1293  *
1294  * @p: see amdgpu_pte_update_params definition
1295  * @addr: virtual address in question
1296  * @entry: resulting entry or NULL
1297  * @parent: parent entry
1298  *
1299  * Find the vm_pt entry and it's parent for the given address.
1300  */
1301 void amdgpu_vm_get_entry(struct amdgpu_pte_update_params *p, uint64_t addr,
1302 			 struct amdgpu_vm_pt **entry,
1303 			 struct amdgpu_vm_pt **parent)
1304 {
1305 	unsigned idx, level = p->adev->vm_manager.num_level;
1306 
1307 	*parent = NULL;
1308 	*entry = &p->vm->root;
1309 	while ((*entry)->entries) {
1310 		idx = addr >> (p->adev->vm_manager.block_size * level--);
1311 		idx %= amdgpu_bo_size((*entry)->base.bo) / 8;
1312 		*parent = *entry;
1313 		*entry = &(*entry)->entries[idx];
1314 	}
1315 
1316 	if (level)
1317 		*entry = NULL;
1318 }
1319 
1320 /**
1321  * amdgpu_vm_handle_huge_pages - handle updating the PD with huge pages
1322  *
1323  * @p: see amdgpu_pte_update_params definition
1324  * @entry: vm_pt entry to check
1325  * @parent: parent entry
1326  * @nptes: number of PTEs updated with this operation
1327  * @dst: destination address where the PTEs should point to
1328  * @flags: access flags fro the PTEs
1329  *
1330  * Check if we can update the PD with a huge page.
1331  */
1332 static void amdgpu_vm_handle_huge_pages(struct amdgpu_pte_update_params *p,
1333 					struct amdgpu_vm_pt *entry,
1334 					struct amdgpu_vm_pt *parent,
1335 					unsigned nptes, uint64_t dst,
1336 					uint64_t flags)
1337 {
1338 	bool use_cpu_update = (p->func == amdgpu_vm_cpu_set_ptes);
1339 	uint64_t pd_addr, pde;
1340 
1341 	/* In the case of a mixed PT the PDE must point to it*/
1342 	if (p->adev->asic_type < CHIP_VEGA10 ||
1343 	    nptes != AMDGPU_VM_PTE_COUNT(p->adev) ||
1344 	    p->src ||
1345 	    !(flags & AMDGPU_PTE_VALID)) {
1346 
1347 		dst = amdgpu_bo_gpu_offset(entry->base.bo);
1348 		dst = amdgpu_gart_get_vm_pde(p->adev, dst);
1349 		flags = AMDGPU_PTE_VALID;
1350 	} else {
1351 		/* Set the huge page flag to stop scanning at this PDE */
1352 		flags |= AMDGPU_PDE_PTE;
1353 	}
1354 
1355 	if (entry->addr == (dst | flags))
1356 		return;
1357 
1358 	entry->addr = (dst | flags);
1359 
1360 	if (use_cpu_update) {
1361 		/* In case a huge page is replaced with a system
1362 		 * memory mapping, p->pages_addr != NULL and
1363 		 * amdgpu_vm_cpu_set_ptes would try to translate dst
1364 		 * through amdgpu_vm_map_gart. But dst is already a
1365 		 * GPU address (of the page table). Disable
1366 		 * amdgpu_vm_map_gart temporarily.
1367 		 */
1368 		dma_addr_t *tmp;
1369 
1370 		tmp = p->pages_addr;
1371 		p->pages_addr = NULL;
1372 
1373 		pd_addr = (unsigned long)amdgpu_bo_kptr(parent->base.bo);
1374 		pde = pd_addr + (entry - parent->entries) * 8;
1375 		amdgpu_vm_cpu_set_ptes(p, pde, dst, 1, 0, flags);
1376 
1377 		p->pages_addr = tmp;
1378 	} else {
1379 		if (parent->base.bo->shadow) {
1380 			pd_addr = amdgpu_bo_gpu_offset(parent->base.bo->shadow);
1381 			pde = pd_addr + (entry - parent->entries) * 8;
1382 			amdgpu_vm_do_set_ptes(p, pde, dst, 1, 0, flags);
1383 		}
1384 		pd_addr = amdgpu_bo_gpu_offset(parent->base.bo);
1385 		pde = pd_addr + (entry - parent->entries) * 8;
1386 		amdgpu_vm_do_set_ptes(p, pde, dst, 1, 0, flags);
1387 	}
1388 }
1389 
1390 /**
1391  * amdgpu_vm_update_ptes - make sure that page tables are valid
1392  *
1393  * @params: see amdgpu_pte_update_params definition
1394  * @vm: requested vm
1395  * @start: start of GPU address range
1396  * @end: end of GPU address range
1397  * @dst: destination address to map to, the next dst inside the function
1398  * @flags: mapping flags
1399  *
1400  * Update the page tables in the range @start - @end.
1401  * Returns 0 for success, -EINVAL for failure.
1402  */
1403 static int amdgpu_vm_update_ptes(struct amdgpu_pte_update_params *params,
1404 				  uint64_t start, uint64_t end,
1405 				  uint64_t dst, uint64_t flags)
1406 {
1407 	struct amdgpu_device *adev = params->adev;
1408 	const uint64_t mask = AMDGPU_VM_PTE_COUNT(adev) - 1;
1409 
1410 	uint64_t addr, pe_start;
1411 	struct amdgpu_bo *pt;
1412 	unsigned nptes;
1413 	bool use_cpu_update = (params->func == amdgpu_vm_cpu_set_ptes);
1414 
1415 	/* walk over the address space and update the page tables */
1416 	for (addr = start; addr < end; addr += nptes,
1417 	     dst += nptes * AMDGPU_GPU_PAGE_SIZE) {
1418 		struct amdgpu_vm_pt *entry, *parent;
1419 
1420 		amdgpu_vm_get_entry(params, addr, &entry, &parent);
1421 		if (!entry)
1422 			return -ENOENT;
1423 
1424 		if ((addr & ~mask) == (end & ~mask))
1425 			nptes = end - addr;
1426 		else
1427 			nptes = AMDGPU_VM_PTE_COUNT(adev) - (addr & mask);
1428 
1429 		amdgpu_vm_handle_huge_pages(params, entry, parent,
1430 					    nptes, dst, flags);
1431 		/* We don't need to update PTEs for huge pages */
1432 		if (entry->addr & AMDGPU_PDE_PTE)
1433 			continue;
1434 
1435 		pt = entry->base.bo;
1436 		if (use_cpu_update) {
1437 			pe_start = (unsigned long)amdgpu_bo_kptr(pt);
1438 		} else {
1439 			if (pt->shadow) {
1440 				pe_start = amdgpu_bo_gpu_offset(pt->shadow);
1441 				pe_start += (addr & mask) * 8;
1442 				params->func(params, pe_start, dst, nptes,
1443 					     AMDGPU_GPU_PAGE_SIZE, flags);
1444 			}
1445 			pe_start = amdgpu_bo_gpu_offset(pt);
1446 		}
1447 
1448 		pe_start += (addr & mask) * 8;
1449 		params->func(params, pe_start, dst, nptes,
1450 			     AMDGPU_GPU_PAGE_SIZE, flags);
1451 	}
1452 
1453 	return 0;
1454 }
1455 
1456 /*
1457  * amdgpu_vm_frag_ptes - add fragment information to PTEs
1458  *
1459  * @params: see amdgpu_pte_update_params definition
1460  * @vm: requested vm
1461  * @start: first PTE to handle
1462  * @end: last PTE to handle
1463  * @dst: addr those PTEs should point to
1464  * @flags: hw mapping flags
1465  * Returns 0 for success, -EINVAL for failure.
1466  */
1467 static int amdgpu_vm_frag_ptes(struct amdgpu_pte_update_params	*params,
1468 				uint64_t start, uint64_t end,
1469 				uint64_t dst, uint64_t flags)
1470 {
1471 	/**
1472 	 * The MC L1 TLB supports variable sized pages, based on a fragment
1473 	 * field in the PTE. When this field is set to a non-zero value, page
1474 	 * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
1475 	 * flags are considered valid for all PTEs within the fragment range
1476 	 * and corresponding mappings are assumed to be physically contiguous.
1477 	 *
1478 	 * The L1 TLB can store a single PTE for the whole fragment,
1479 	 * significantly increasing the space available for translation
1480 	 * caching. This leads to large improvements in throughput when the
1481 	 * TLB is under pressure.
1482 	 *
1483 	 * The L2 TLB distributes small and large fragments into two
1484 	 * asymmetric partitions. The large fragment cache is significantly
1485 	 * larger. Thus, we try to use large fragments wherever possible.
1486 	 * Userspace can support this by aligning virtual base address and
1487 	 * allocation size to the fragment size.
1488 	 */
1489 	unsigned max_frag = params->adev->vm_manager.fragment_size;
1490 	int r;
1491 
1492 	/* system pages are non continuously */
1493 	if (params->src || !(flags & AMDGPU_PTE_VALID))
1494 		return amdgpu_vm_update_ptes(params, start, end, dst, flags);
1495 
1496 	while (start != end) {
1497 		uint64_t frag_flags, frag_end;
1498 		unsigned frag;
1499 
1500 		/* This intentionally wraps around if no bit is set */
1501 		frag = min((unsigned)ffs(start) - 1,
1502 			   (unsigned)fls64(end - start) - 1);
1503 		if (frag >= max_frag) {
1504 			frag_flags = AMDGPU_PTE_FRAG(max_frag);
1505 			frag_end = end & ~((1ULL << max_frag) - 1);
1506 		} else {
1507 			frag_flags = AMDGPU_PTE_FRAG(frag);
1508 			frag_end = start + (1 << frag);
1509 		}
1510 
1511 		r = amdgpu_vm_update_ptes(params, start, frag_end, dst,
1512 					  flags | frag_flags);
1513 		if (r)
1514 			return r;
1515 
1516 		dst += (frag_end - start) * AMDGPU_GPU_PAGE_SIZE;
1517 		start = frag_end;
1518 	}
1519 
1520 	return 0;
1521 }
1522 
1523 /**
1524  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
1525  *
1526  * @adev: amdgpu_device pointer
1527  * @exclusive: fence we need to sync to
1528  * @pages_addr: DMA addresses to use for mapping
1529  * @vm: requested vm
1530  * @start: start of mapped range
1531  * @last: last mapped entry
1532  * @flags: flags for the entries
1533  * @addr: addr to set the area to
1534  * @fence: optional resulting fence
1535  *
1536  * Fill in the page table entries between @start and @last.
1537  * Returns 0 for success, -EINVAL for failure.
1538  */
1539 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
1540 				       struct dma_fence *exclusive,
1541 				       dma_addr_t *pages_addr,
1542 				       struct amdgpu_vm *vm,
1543 				       uint64_t start, uint64_t last,
1544 				       uint64_t flags, uint64_t addr,
1545 				       struct dma_fence **fence)
1546 {
1547 	struct amdgpu_ring *ring;
1548 	void *owner = AMDGPU_FENCE_OWNER_VM;
1549 	unsigned nptes, ncmds, ndw;
1550 	struct amdgpu_job *job;
1551 	struct amdgpu_pte_update_params params;
1552 	struct dma_fence *f = NULL;
1553 	int r;
1554 
1555 	memset(&params, 0, sizeof(params));
1556 	params.adev = adev;
1557 	params.vm = vm;
1558 
1559 	/* sync to everything on unmapping */
1560 	if (!(flags & AMDGPU_PTE_VALID))
1561 		owner = AMDGPU_FENCE_OWNER_UNDEFINED;
1562 
1563 	if (vm->use_cpu_for_update) {
1564 		/* params.src is used as flag to indicate system Memory */
1565 		if (pages_addr)
1566 			params.src = ~0;
1567 
1568 		/* Wait for PT BOs to be free. PTs share the same resv. object
1569 		 * as the root PD BO
1570 		 */
1571 		r = amdgpu_vm_wait_pd(adev, vm, owner);
1572 		if (unlikely(r))
1573 			return r;
1574 
1575 		params.func = amdgpu_vm_cpu_set_ptes;
1576 		params.pages_addr = pages_addr;
1577 		return amdgpu_vm_frag_ptes(&params, start, last + 1,
1578 					   addr, flags);
1579 	}
1580 
1581 	ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
1582 
1583 	nptes = last - start + 1;
1584 
1585 	/*
1586 	 * reserve space for two commands every (1 << BLOCK_SIZE)
1587 	 *  entries or 2k dwords (whatever is smaller)
1588          *
1589          * The second command is for the shadow pagetables.
1590 	 */
1591 	ncmds = ((nptes >> min(adev->vm_manager.block_size, 11u)) + 1) * 2;
1592 
1593 	/* padding, etc. */
1594 	ndw = 64;
1595 
1596 	/* one PDE write for each huge page */
1597 	ndw += ((nptes >> adev->vm_manager.block_size) + 1) * 6;
1598 
1599 	if (pages_addr) {
1600 		/* copy commands needed */
1601 		ndw += ncmds * adev->vm_manager.vm_pte_funcs->copy_pte_num_dw;
1602 
1603 		/* and also PTEs */
1604 		ndw += nptes * 2;
1605 
1606 		params.func = amdgpu_vm_do_copy_ptes;
1607 
1608 	} else {
1609 		/* set page commands needed */
1610 		ndw += ncmds * adev->vm_manager.vm_pte_funcs->set_pte_pde_num_dw;
1611 
1612 		/* extra commands for begin/end fragments */
1613 		ndw += 2 * adev->vm_manager.vm_pte_funcs->set_pte_pde_num_dw
1614 				* adev->vm_manager.fragment_size;
1615 
1616 		params.func = amdgpu_vm_do_set_ptes;
1617 	}
1618 
1619 	r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1620 	if (r)
1621 		return r;
1622 
1623 	params.ib = &job->ibs[0];
1624 
1625 	if (pages_addr) {
1626 		uint64_t *pte;
1627 		unsigned i;
1628 
1629 		/* Put the PTEs at the end of the IB. */
1630 		i = ndw - nptes * 2;
1631 		pte= (uint64_t *)&(job->ibs->ptr[i]);
1632 		params.src = job->ibs->gpu_addr + i * 4;
1633 
1634 		for (i = 0; i < nptes; ++i) {
1635 			pte[i] = amdgpu_vm_map_gart(pages_addr, addr + i *
1636 						    AMDGPU_GPU_PAGE_SIZE);
1637 			pte[i] |= flags;
1638 		}
1639 		addr = 0;
1640 	}
1641 
1642 	r = amdgpu_sync_fence(adev, &job->sync, exclusive);
1643 	if (r)
1644 		goto error_free;
1645 
1646 	r = amdgpu_sync_resv(adev, &job->sync, vm->root.base.bo->tbo.resv,
1647 			     owner, false);
1648 	if (r)
1649 		goto error_free;
1650 
1651 	r = reservation_object_reserve_shared(vm->root.base.bo->tbo.resv);
1652 	if (r)
1653 		goto error_free;
1654 
1655 	r = amdgpu_vm_frag_ptes(&params, start, last + 1, addr, flags);
1656 	if (r)
1657 		goto error_free;
1658 
1659 	amdgpu_ring_pad_ib(ring, params.ib);
1660 	WARN_ON(params.ib->length_dw > ndw);
1661 	r = amdgpu_job_submit(job, ring, &vm->entity,
1662 			      AMDGPU_FENCE_OWNER_VM, &f);
1663 	if (r)
1664 		goto error_free;
1665 
1666 	amdgpu_bo_fence(vm->root.base.bo, f, true);
1667 	dma_fence_put(*fence);
1668 	*fence = f;
1669 	return 0;
1670 
1671 error_free:
1672 	amdgpu_job_free(job);
1673 	amdgpu_vm_invalidate_level(vm, &vm->root);
1674 	return r;
1675 }
1676 
1677 /**
1678  * amdgpu_vm_bo_split_mapping - split a mapping into smaller chunks
1679  *
1680  * @adev: amdgpu_device pointer
1681  * @exclusive: fence we need to sync to
1682  * @pages_addr: DMA addresses to use for mapping
1683  * @vm: requested vm
1684  * @mapping: mapped range and flags to use for the update
1685  * @flags: HW flags for the mapping
1686  * @nodes: array of drm_mm_nodes with the MC addresses
1687  * @fence: optional resulting fence
1688  *
1689  * Split the mapping into smaller chunks so that each update fits
1690  * into a SDMA IB.
1691  * Returns 0 for success, -EINVAL for failure.
1692  */
1693 static int amdgpu_vm_bo_split_mapping(struct amdgpu_device *adev,
1694 				      struct dma_fence *exclusive,
1695 				      dma_addr_t *pages_addr,
1696 				      struct amdgpu_vm *vm,
1697 				      struct amdgpu_bo_va_mapping *mapping,
1698 				      uint64_t flags,
1699 				      struct drm_mm_node *nodes,
1700 				      struct dma_fence **fence)
1701 {
1702 	unsigned min_linear_pages = 1 << adev->vm_manager.fragment_size;
1703 	uint64_t pfn, start = mapping->start;
1704 	int r;
1705 
1706 	/* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1707 	 * but in case of something, we filter the flags in first place
1708 	 */
1709 	if (!(mapping->flags & AMDGPU_PTE_READABLE))
1710 		flags &= ~AMDGPU_PTE_READABLE;
1711 	if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1712 		flags &= ~AMDGPU_PTE_WRITEABLE;
1713 
1714 	flags &= ~AMDGPU_PTE_EXECUTABLE;
1715 	flags |= mapping->flags & AMDGPU_PTE_EXECUTABLE;
1716 
1717 	flags &= ~AMDGPU_PTE_MTYPE_MASK;
1718 	flags |= (mapping->flags & AMDGPU_PTE_MTYPE_MASK);
1719 
1720 	if ((mapping->flags & AMDGPU_PTE_PRT) &&
1721 	    (adev->asic_type >= CHIP_VEGA10)) {
1722 		flags |= AMDGPU_PTE_PRT;
1723 		flags &= ~AMDGPU_PTE_VALID;
1724 	}
1725 
1726 	trace_amdgpu_vm_bo_update(mapping);
1727 
1728 	pfn = mapping->offset >> PAGE_SHIFT;
1729 	if (nodes) {
1730 		while (pfn >= nodes->size) {
1731 			pfn -= nodes->size;
1732 			++nodes;
1733 		}
1734 	}
1735 
1736 	do {
1737 		dma_addr_t *dma_addr = NULL;
1738 		uint64_t max_entries;
1739 		uint64_t addr, last;
1740 
1741 		if (nodes) {
1742 			addr = nodes->start << PAGE_SHIFT;
1743 			max_entries = (nodes->size - pfn) *
1744 				(PAGE_SIZE / AMDGPU_GPU_PAGE_SIZE);
1745 		} else {
1746 			addr = 0;
1747 			max_entries = S64_MAX;
1748 		}
1749 
1750 		if (pages_addr) {
1751 			uint64_t count;
1752 
1753 			max_entries = min(max_entries, 16ull * 1024ull);
1754 			for (count = 1; count < max_entries; ++count) {
1755 				uint64_t idx = pfn + count;
1756 
1757 				if (pages_addr[idx] !=
1758 				    (pages_addr[idx - 1] + PAGE_SIZE))
1759 					break;
1760 			}
1761 
1762 			if (count < min_linear_pages) {
1763 				addr = pfn << PAGE_SHIFT;
1764 				dma_addr = pages_addr;
1765 			} else {
1766 				addr = pages_addr[pfn];
1767 				max_entries = count;
1768 			}
1769 
1770 		} else if (flags & AMDGPU_PTE_VALID) {
1771 			addr += adev->vm_manager.vram_base_offset;
1772 			addr += pfn << PAGE_SHIFT;
1773 		}
1774 
1775 		last = min((uint64_t)mapping->last, start + max_entries - 1);
1776 		r = amdgpu_vm_bo_update_mapping(adev, exclusive, dma_addr, vm,
1777 						start, last, flags, addr,
1778 						fence);
1779 		if (r)
1780 			return r;
1781 
1782 		pfn += last - start + 1;
1783 		if (nodes && nodes->size == pfn) {
1784 			pfn = 0;
1785 			++nodes;
1786 		}
1787 		start = last + 1;
1788 
1789 	} while (unlikely(start != mapping->last + 1));
1790 
1791 	return 0;
1792 }
1793 
1794 /**
1795  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1796  *
1797  * @adev: amdgpu_device pointer
1798  * @bo_va: requested BO and VM object
1799  * @clear: if true clear the entries
1800  *
1801  * Fill in the page table entries for @bo_va.
1802  * Returns 0 for success, -EINVAL for failure.
1803  */
1804 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
1805 			struct amdgpu_bo_va *bo_va,
1806 			bool clear)
1807 {
1808 	struct amdgpu_bo *bo = bo_va->base.bo;
1809 	struct amdgpu_vm *vm = bo_va->base.vm;
1810 	struct amdgpu_bo_va_mapping *mapping;
1811 	dma_addr_t *pages_addr = NULL;
1812 	struct ttm_mem_reg *mem;
1813 	struct drm_mm_node *nodes;
1814 	struct dma_fence *exclusive, **last_update;
1815 	uint64_t flags;
1816 	int r;
1817 
1818 	if (clear || !bo_va->base.bo) {
1819 		mem = NULL;
1820 		nodes = NULL;
1821 		exclusive = NULL;
1822 	} else {
1823 		struct ttm_dma_tt *ttm;
1824 
1825 		mem = &bo_va->base.bo->tbo.mem;
1826 		nodes = mem->mm_node;
1827 		if (mem->mem_type == TTM_PL_TT) {
1828 			ttm = container_of(bo_va->base.bo->tbo.ttm,
1829 					   struct ttm_dma_tt, ttm);
1830 			pages_addr = ttm->dma_address;
1831 		}
1832 		exclusive = reservation_object_get_excl(bo->tbo.resv);
1833 	}
1834 
1835 	if (bo)
1836 		flags = amdgpu_ttm_tt_pte_flags(adev, bo->tbo.ttm, mem);
1837 	else
1838 		flags = 0x0;
1839 
1840 	if (clear || (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv))
1841 		last_update = &vm->last_update;
1842 	else
1843 		last_update = &bo_va->last_pt_update;
1844 
1845 	if (!clear && bo_va->base.moved) {
1846 		bo_va->base.moved = false;
1847 		list_splice_init(&bo_va->valids, &bo_va->invalids);
1848 
1849 	} else if (bo_va->cleared != clear) {
1850 		list_splice_init(&bo_va->valids, &bo_va->invalids);
1851 	}
1852 
1853 	list_for_each_entry(mapping, &bo_va->invalids, list) {
1854 		r = amdgpu_vm_bo_split_mapping(adev, exclusive, pages_addr, vm,
1855 					       mapping, flags, nodes,
1856 					       last_update);
1857 		if (r)
1858 			return r;
1859 	}
1860 
1861 	if (vm->use_cpu_for_update) {
1862 		/* Flush HDP */
1863 		mb();
1864 		amdgpu_gart_flush_gpu_tlb(adev, 0);
1865 	}
1866 
1867 	spin_lock(&vm->status_lock);
1868 	list_del_init(&bo_va->base.vm_status);
1869 	spin_unlock(&vm->status_lock);
1870 
1871 	list_splice_init(&bo_va->invalids, &bo_va->valids);
1872 	bo_va->cleared = clear;
1873 
1874 	if (trace_amdgpu_vm_bo_mapping_enabled()) {
1875 		list_for_each_entry(mapping, &bo_va->valids, list)
1876 			trace_amdgpu_vm_bo_mapping(mapping);
1877 	}
1878 
1879 	return 0;
1880 }
1881 
1882 /**
1883  * amdgpu_vm_update_prt_state - update the global PRT state
1884  */
1885 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1886 {
1887 	unsigned long flags;
1888 	bool enable;
1889 
1890 	spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1891 	enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1892 	adev->gart.gart_funcs->set_prt(adev, enable);
1893 	spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1894 }
1895 
1896 /**
1897  * amdgpu_vm_prt_get - add a PRT user
1898  */
1899 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1900 {
1901 	if (!adev->gart.gart_funcs->set_prt)
1902 		return;
1903 
1904 	if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1905 		amdgpu_vm_update_prt_state(adev);
1906 }
1907 
1908 /**
1909  * amdgpu_vm_prt_put - drop a PRT user
1910  */
1911 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1912 {
1913 	if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1914 		amdgpu_vm_update_prt_state(adev);
1915 }
1916 
1917 /**
1918  * amdgpu_vm_prt_cb - callback for updating the PRT status
1919  */
1920 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1921 {
1922 	struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1923 
1924 	amdgpu_vm_prt_put(cb->adev);
1925 	kfree(cb);
1926 }
1927 
1928 /**
1929  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1930  */
1931 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1932 				 struct dma_fence *fence)
1933 {
1934 	struct amdgpu_prt_cb *cb;
1935 
1936 	if (!adev->gart.gart_funcs->set_prt)
1937 		return;
1938 
1939 	cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
1940 	if (!cb) {
1941 		/* Last resort when we are OOM */
1942 		if (fence)
1943 			dma_fence_wait(fence, false);
1944 
1945 		amdgpu_vm_prt_put(adev);
1946 	} else {
1947 		cb->adev = adev;
1948 		if (!fence || dma_fence_add_callback(fence, &cb->cb,
1949 						     amdgpu_vm_prt_cb))
1950 			amdgpu_vm_prt_cb(fence, &cb->cb);
1951 	}
1952 }
1953 
1954 /**
1955  * amdgpu_vm_free_mapping - free a mapping
1956  *
1957  * @adev: amdgpu_device pointer
1958  * @vm: requested vm
1959  * @mapping: mapping to be freed
1960  * @fence: fence of the unmap operation
1961  *
1962  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1963  */
1964 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1965 				   struct amdgpu_vm *vm,
1966 				   struct amdgpu_bo_va_mapping *mapping,
1967 				   struct dma_fence *fence)
1968 {
1969 	if (mapping->flags & AMDGPU_PTE_PRT)
1970 		amdgpu_vm_add_prt_cb(adev, fence);
1971 	kfree(mapping);
1972 }
1973 
1974 /**
1975  * amdgpu_vm_prt_fini - finish all prt mappings
1976  *
1977  * @adev: amdgpu_device pointer
1978  * @vm: requested vm
1979  *
1980  * Register a cleanup callback to disable PRT support after VM dies.
1981  */
1982 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1983 {
1984 	struct reservation_object *resv = vm->root.base.bo->tbo.resv;
1985 	struct dma_fence *excl, **shared;
1986 	unsigned i, shared_count;
1987 	int r;
1988 
1989 	r = reservation_object_get_fences_rcu(resv, &excl,
1990 					      &shared_count, &shared);
1991 	if (r) {
1992 		/* Not enough memory to grab the fence list, as last resort
1993 		 * block for all the fences to complete.
1994 		 */
1995 		reservation_object_wait_timeout_rcu(resv, true, false,
1996 						    MAX_SCHEDULE_TIMEOUT);
1997 		return;
1998 	}
1999 
2000 	/* Add a callback for each fence in the reservation object */
2001 	amdgpu_vm_prt_get(adev);
2002 	amdgpu_vm_add_prt_cb(adev, excl);
2003 
2004 	for (i = 0; i < shared_count; ++i) {
2005 		amdgpu_vm_prt_get(adev);
2006 		amdgpu_vm_add_prt_cb(adev, shared[i]);
2007 	}
2008 
2009 	kfree(shared);
2010 }
2011 
2012 /**
2013  * amdgpu_vm_clear_freed - clear freed BOs in the PT
2014  *
2015  * @adev: amdgpu_device pointer
2016  * @vm: requested vm
2017  * @fence: optional resulting fence (unchanged if no work needed to be done
2018  * or if an error occurred)
2019  *
2020  * Make sure all freed BOs are cleared in the PT.
2021  * Returns 0 for success.
2022  *
2023  * PTs have to be reserved and mutex must be locked!
2024  */
2025 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
2026 			  struct amdgpu_vm *vm,
2027 			  struct dma_fence **fence)
2028 {
2029 	struct amdgpu_bo_va_mapping *mapping;
2030 	struct dma_fence *f = NULL;
2031 	int r;
2032 	uint64_t init_pte_value = 0;
2033 
2034 	while (!list_empty(&vm->freed)) {
2035 		mapping = list_first_entry(&vm->freed,
2036 			struct amdgpu_bo_va_mapping, list);
2037 		list_del(&mapping->list);
2038 
2039 		if (vm->pte_support_ats)
2040 			init_pte_value = AMDGPU_PTE_DEFAULT_ATC;
2041 
2042 		r = amdgpu_vm_bo_update_mapping(adev, NULL, NULL, vm,
2043 						mapping->start, mapping->last,
2044 						init_pte_value, 0, &f);
2045 		amdgpu_vm_free_mapping(adev, vm, mapping, f);
2046 		if (r) {
2047 			dma_fence_put(f);
2048 			return r;
2049 		}
2050 	}
2051 
2052 	if (fence && f) {
2053 		dma_fence_put(*fence);
2054 		*fence = f;
2055 	} else {
2056 		dma_fence_put(f);
2057 	}
2058 
2059 	return 0;
2060 
2061 }
2062 
2063 /**
2064  * amdgpu_vm_handle_moved - handle moved BOs in the PT
2065  *
2066  * @adev: amdgpu_device pointer
2067  * @vm: requested vm
2068  * @sync: sync object to add fences to
2069  *
2070  * Make sure all BOs which are moved are updated in the PTs.
2071  * Returns 0 for success.
2072  *
2073  * PTs have to be reserved!
2074  */
2075 int amdgpu_vm_handle_moved(struct amdgpu_device *adev,
2076 			   struct amdgpu_vm *vm)
2077 {
2078 	bool clear;
2079 	int r = 0;
2080 
2081 	spin_lock(&vm->status_lock);
2082 	while (!list_empty(&vm->moved)) {
2083 		struct amdgpu_bo_va *bo_va;
2084 
2085 		bo_va = list_first_entry(&vm->moved,
2086 			struct amdgpu_bo_va, base.vm_status);
2087 		spin_unlock(&vm->status_lock);
2088 
2089 		/* Per VM BOs never need to bo cleared in the page tables */
2090 		clear = bo_va->base.bo->tbo.resv != vm->root.base.bo->tbo.resv;
2091 
2092 		r = amdgpu_vm_bo_update(adev, bo_va, clear);
2093 		if (r)
2094 			return r;
2095 
2096 		spin_lock(&vm->status_lock);
2097 	}
2098 	spin_unlock(&vm->status_lock);
2099 
2100 	return r;
2101 }
2102 
2103 /**
2104  * amdgpu_vm_bo_add - add a bo to a specific vm
2105  *
2106  * @adev: amdgpu_device pointer
2107  * @vm: requested vm
2108  * @bo: amdgpu buffer object
2109  *
2110  * Add @bo into the requested vm.
2111  * Add @bo to the list of bos associated with the vm
2112  * Returns newly added bo_va or NULL for failure
2113  *
2114  * Object has to be reserved!
2115  */
2116 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
2117 				      struct amdgpu_vm *vm,
2118 				      struct amdgpu_bo *bo)
2119 {
2120 	struct amdgpu_bo_va *bo_va;
2121 
2122 	bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
2123 	if (bo_va == NULL) {
2124 		return NULL;
2125 	}
2126 	bo_va->base.vm = vm;
2127 	bo_va->base.bo = bo;
2128 	INIT_LIST_HEAD(&bo_va->base.bo_list);
2129 	INIT_LIST_HEAD(&bo_va->base.vm_status);
2130 
2131 	bo_va->ref_count = 1;
2132 	INIT_LIST_HEAD(&bo_va->valids);
2133 	INIT_LIST_HEAD(&bo_va->invalids);
2134 
2135 	if (bo)
2136 		list_add_tail(&bo_va->base.bo_list, &bo->va);
2137 
2138 	return bo_va;
2139 }
2140 
2141 
2142 /**
2143  * amdgpu_vm_bo_insert_mapping - insert a new mapping
2144  *
2145  * @adev: amdgpu_device pointer
2146  * @bo_va: bo_va to store the address
2147  * @mapping: the mapping to insert
2148  *
2149  * Insert a new mapping into all structures.
2150  */
2151 static void amdgpu_vm_bo_insert_map(struct amdgpu_device *adev,
2152 				    struct amdgpu_bo_va *bo_va,
2153 				    struct amdgpu_bo_va_mapping *mapping)
2154 {
2155 	struct amdgpu_vm *vm = bo_va->base.vm;
2156 	struct amdgpu_bo *bo = bo_va->base.bo;
2157 
2158 	mapping->bo_va = bo_va;
2159 	list_add(&mapping->list, &bo_va->invalids);
2160 	amdgpu_vm_it_insert(mapping, &vm->va);
2161 
2162 	if (mapping->flags & AMDGPU_PTE_PRT)
2163 		amdgpu_vm_prt_get(adev);
2164 
2165 	if (bo && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
2166 		spin_lock(&vm->status_lock);
2167 		if (list_empty(&bo_va->base.vm_status))
2168 			list_add(&bo_va->base.vm_status, &vm->moved);
2169 		spin_unlock(&vm->status_lock);
2170 	}
2171 	trace_amdgpu_vm_bo_map(bo_va, mapping);
2172 }
2173 
2174 /**
2175  * amdgpu_vm_bo_map - map bo inside a vm
2176  *
2177  * @adev: amdgpu_device pointer
2178  * @bo_va: bo_va to store the address
2179  * @saddr: where to map the BO
2180  * @offset: requested offset in the BO
2181  * @flags: attributes of pages (read/write/valid/etc.)
2182  *
2183  * Add a mapping of the BO at the specefied addr into the VM.
2184  * Returns 0 for success, error for failure.
2185  *
2186  * Object has to be reserved and unreserved outside!
2187  */
2188 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
2189 		     struct amdgpu_bo_va *bo_va,
2190 		     uint64_t saddr, uint64_t offset,
2191 		     uint64_t size, uint64_t flags)
2192 {
2193 	struct amdgpu_bo_va_mapping *mapping, *tmp;
2194 	struct amdgpu_bo *bo = bo_va->base.bo;
2195 	struct amdgpu_vm *vm = bo_va->base.vm;
2196 	uint64_t eaddr;
2197 
2198 	/* validate the parameters */
2199 	if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
2200 	    size == 0 || size & AMDGPU_GPU_PAGE_MASK)
2201 		return -EINVAL;
2202 
2203 	/* make sure object fit at this offset */
2204 	eaddr = saddr + size - 1;
2205 	if (saddr >= eaddr ||
2206 	    (bo && offset + size > amdgpu_bo_size(bo)))
2207 		return -EINVAL;
2208 
2209 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2210 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
2211 
2212 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2213 	if (tmp) {
2214 		/* bo and tmp overlap, invalid addr */
2215 		dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
2216 			"0x%010Lx-0x%010Lx\n", bo, saddr, eaddr,
2217 			tmp->start, tmp->last + 1);
2218 		return -EINVAL;
2219 	}
2220 
2221 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2222 	if (!mapping)
2223 		return -ENOMEM;
2224 
2225 	mapping->start = saddr;
2226 	mapping->last = eaddr;
2227 	mapping->offset = offset;
2228 	mapping->flags = flags;
2229 
2230 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2231 
2232 	return 0;
2233 }
2234 
2235 /**
2236  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
2237  *
2238  * @adev: amdgpu_device pointer
2239  * @bo_va: bo_va to store the address
2240  * @saddr: where to map the BO
2241  * @offset: requested offset in the BO
2242  * @flags: attributes of pages (read/write/valid/etc.)
2243  *
2244  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
2245  * mappings as we do so.
2246  * Returns 0 for success, error for failure.
2247  *
2248  * Object has to be reserved and unreserved outside!
2249  */
2250 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
2251 			     struct amdgpu_bo_va *bo_va,
2252 			     uint64_t saddr, uint64_t offset,
2253 			     uint64_t size, uint64_t flags)
2254 {
2255 	struct amdgpu_bo_va_mapping *mapping;
2256 	struct amdgpu_bo *bo = bo_va->base.bo;
2257 	uint64_t eaddr;
2258 	int r;
2259 
2260 	/* validate the parameters */
2261 	if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
2262 	    size == 0 || size & AMDGPU_GPU_PAGE_MASK)
2263 		return -EINVAL;
2264 
2265 	/* make sure object fit at this offset */
2266 	eaddr = saddr + size - 1;
2267 	if (saddr >= eaddr ||
2268 	    (bo && offset + size > amdgpu_bo_size(bo)))
2269 		return -EINVAL;
2270 
2271 	/* Allocate all the needed memory */
2272 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
2273 	if (!mapping)
2274 		return -ENOMEM;
2275 
2276 	r = amdgpu_vm_bo_clear_mappings(adev, bo_va->base.vm, saddr, size);
2277 	if (r) {
2278 		kfree(mapping);
2279 		return r;
2280 	}
2281 
2282 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2283 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
2284 
2285 	mapping->start = saddr;
2286 	mapping->last = eaddr;
2287 	mapping->offset = offset;
2288 	mapping->flags = flags;
2289 
2290 	amdgpu_vm_bo_insert_map(adev, bo_va, mapping);
2291 
2292 	return 0;
2293 }
2294 
2295 /**
2296  * amdgpu_vm_bo_unmap - remove bo mapping from vm
2297  *
2298  * @adev: amdgpu_device pointer
2299  * @bo_va: bo_va to remove the address from
2300  * @saddr: where to the BO is mapped
2301  *
2302  * Remove a mapping of the BO at the specefied addr from the VM.
2303  * Returns 0 for success, error for failure.
2304  *
2305  * Object has to be reserved and unreserved outside!
2306  */
2307 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
2308 		       struct amdgpu_bo_va *bo_va,
2309 		       uint64_t saddr)
2310 {
2311 	struct amdgpu_bo_va_mapping *mapping;
2312 	struct amdgpu_vm *vm = bo_va->base.vm;
2313 	bool valid = true;
2314 
2315 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2316 
2317 	list_for_each_entry(mapping, &bo_va->valids, list) {
2318 		if (mapping->start == saddr)
2319 			break;
2320 	}
2321 
2322 	if (&mapping->list == &bo_va->valids) {
2323 		valid = false;
2324 
2325 		list_for_each_entry(mapping, &bo_va->invalids, list) {
2326 			if (mapping->start == saddr)
2327 				break;
2328 		}
2329 
2330 		if (&mapping->list == &bo_va->invalids)
2331 			return -ENOENT;
2332 	}
2333 
2334 	list_del(&mapping->list);
2335 	amdgpu_vm_it_remove(mapping, &vm->va);
2336 	mapping->bo_va = NULL;
2337 	trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2338 
2339 	if (valid)
2340 		list_add(&mapping->list, &vm->freed);
2341 	else
2342 		amdgpu_vm_free_mapping(adev, vm, mapping,
2343 				       bo_va->last_pt_update);
2344 
2345 	return 0;
2346 }
2347 
2348 /**
2349  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
2350  *
2351  * @adev: amdgpu_device pointer
2352  * @vm: VM structure to use
2353  * @saddr: start of the range
2354  * @size: size of the range
2355  *
2356  * Remove all mappings in a range, split them as appropriate.
2357  * Returns 0 for success, error for failure.
2358  */
2359 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
2360 				struct amdgpu_vm *vm,
2361 				uint64_t saddr, uint64_t size)
2362 {
2363 	struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
2364 	LIST_HEAD(removed);
2365 	uint64_t eaddr;
2366 
2367 	eaddr = saddr + size - 1;
2368 	saddr /= AMDGPU_GPU_PAGE_SIZE;
2369 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
2370 
2371 	/* Allocate all the needed memory */
2372 	before = kzalloc(sizeof(*before), GFP_KERNEL);
2373 	if (!before)
2374 		return -ENOMEM;
2375 	INIT_LIST_HEAD(&before->list);
2376 
2377 	after = kzalloc(sizeof(*after), GFP_KERNEL);
2378 	if (!after) {
2379 		kfree(before);
2380 		return -ENOMEM;
2381 	}
2382 	INIT_LIST_HEAD(&after->list);
2383 
2384 	/* Now gather all removed mappings */
2385 	tmp = amdgpu_vm_it_iter_first(&vm->va, saddr, eaddr);
2386 	while (tmp) {
2387 		/* Remember mapping split at the start */
2388 		if (tmp->start < saddr) {
2389 			before->start = tmp->start;
2390 			before->last = saddr - 1;
2391 			before->offset = tmp->offset;
2392 			before->flags = tmp->flags;
2393 			list_add(&before->list, &tmp->list);
2394 		}
2395 
2396 		/* Remember mapping split at the end */
2397 		if (tmp->last > eaddr) {
2398 			after->start = eaddr + 1;
2399 			after->last = tmp->last;
2400 			after->offset = tmp->offset;
2401 			after->offset += after->start - tmp->start;
2402 			after->flags = tmp->flags;
2403 			list_add(&after->list, &tmp->list);
2404 		}
2405 
2406 		list_del(&tmp->list);
2407 		list_add(&tmp->list, &removed);
2408 
2409 		tmp = amdgpu_vm_it_iter_next(tmp, saddr, eaddr);
2410 	}
2411 
2412 	/* And free them up */
2413 	list_for_each_entry_safe(tmp, next, &removed, list) {
2414 		amdgpu_vm_it_remove(tmp, &vm->va);
2415 		list_del(&tmp->list);
2416 
2417 		if (tmp->start < saddr)
2418 		    tmp->start = saddr;
2419 		if (tmp->last > eaddr)
2420 		    tmp->last = eaddr;
2421 
2422 		tmp->bo_va = NULL;
2423 		list_add(&tmp->list, &vm->freed);
2424 		trace_amdgpu_vm_bo_unmap(NULL, tmp);
2425 	}
2426 
2427 	/* Insert partial mapping before the range */
2428 	if (!list_empty(&before->list)) {
2429 		amdgpu_vm_it_insert(before, &vm->va);
2430 		if (before->flags & AMDGPU_PTE_PRT)
2431 			amdgpu_vm_prt_get(adev);
2432 	} else {
2433 		kfree(before);
2434 	}
2435 
2436 	/* Insert partial mapping after the range */
2437 	if (!list_empty(&after->list)) {
2438 		amdgpu_vm_it_insert(after, &vm->va);
2439 		if (after->flags & AMDGPU_PTE_PRT)
2440 			amdgpu_vm_prt_get(adev);
2441 	} else {
2442 		kfree(after);
2443 	}
2444 
2445 	return 0;
2446 }
2447 
2448 /**
2449  * amdgpu_vm_bo_lookup_mapping - find mapping by address
2450  *
2451  * @vm: the requested VM
2452  *
2453  * Find a mapping by it's address.
2454  */
2455 struct amdgpu_bo_va_mapping *amdgpu_vm_bo_lookup_mapping(struct amdgpu_vm *vm,
2456 							 uint64_t addr)
2457 {
2458 	return amdgpu_vm_it_iter_first(&vm->va, addr, addr);
2459 }
2460 
2461 /**
2462  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
2463  *
2464  * @adev: amdgpu_device pointer
2465  * @bo_va: requested bo_va
2466  *
2467  * Remove @bo_va->bo from the requested vm.
2468  *
2469  * Object have to be reserved!
2470  */
2471 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
2472 		      struct amdgpu_bo_va *bo_va)
2473 {
2474 	struct amdgpu_bo_va_mapping *mapping, *next;
2475 	struct amdgpu_vm *vm = bo_va->base.vm;
2476 
2477 	list_del(&bo_va->base.bo_list);
2478 
2479 	spin_lock(&vm->status_lock);
2480 	list_del(&bo_va->base.vm_status);
2481 	spin_unlock(&vm->status_lock);
2482 
2483 	list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
2484 		list_del(&mapping->list);
2485 		amdgpu_vm_it_remove(mapping, &vm->va);
2486 		mapping->bo_va = NULL;
2487 		trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2488 		list_add(&mapping->list, &vm->freed);
2489 	}
2490 	list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
2491 		list_del(&mapping->list);
2492 		amdgpu_vm_it_remove(mapping, &vm->va);
2493 		amdgpu_vm_free_mapping(adev, vm, mapping,
2494 				       bo_va->last_pt_update);
2495 	}
2496 
2497 	dma_fence_put(bo_va->last_pt_update);
2498 	kfree(bo_va);
2499 }
2500 
2501 /**
2502  * amdgpu_vm_bo_invalidate - mark the bo as invalid
2503  *
2504  * @adev: amdgpu_device pointer
2505  * @vm: requested vm
2506  * @bo: amdgpu buffer object
2507  *
2508  * Mark @bo as invalid.
2509  */
2510 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
2511 			     struct amdgpu_bo *bo, bool evicted)
2512 {
2513 	struct amdgpu_vm_bo_base *bo_base;
2514 
2515 	list_for_each_entry(bo_base, &bo->va, bo_list) {
2516 		struct amdgpu_vm *vm = bo_base->vm;
2517 
2518 		bo_base->moved = true;
2519 		if (evicted && bo->tbo.resv == vm->root.base.bo->tbo.resv) {
2520 			spin_lock(&bo_base->vm->status_lock);
2521 			if (bo->tbo.type == ttm_bo_type_kernel)
2522 				list_move(&bo_base->vm_status, &vm->evicted);
2523 			else
2524 				list_move_tail(&bo_base->vm_status,
2525 					       &vm->evicted);
2526 			spin_unlock(&bo_base->vm->status_lock);
2527 			continue;
2528 		}
2529 
2530 		if (bo->tbo.type == ttm_bo_type_kernel) {
2531 			spin_lock(&bo_base->vm->status_lock);
2532 			if (list_empty(&bo_base->vm_status))
2533 				list_add(&bo_base->vm_status, &vm->relocated);
2534 			spin_unlock(&bo_base->vm->status_lock);
2535 			continue;
2536 		}
2537 
2538 		spin_lock(&bo_base->vm->status_lock);
2539 		if (list_empty(&bo_base->vm_status))
2540 			list_add(&bo_base->vm_status, &vm->moved);
2541 		spin_unlock(&bo_base->vm->status_lock);
2542 	}
2543 }
2544 
2545 static uint32_t amdgpu_vm_get_block_size(uint64_t vm_size)
2546 {
2547 	/* Total bits covered by PD + PTs */
2548 	unsigned bits = ilog2(vm_size) + 18;
2549 
2550 	/* Make sure the PD is 4K in size up to 8GB address space.
2551 	   Above that split equal between PD and PTs */
2552 	if (vm_size <= 8)
2553 		return (bits - 9);
2554 	else
2555 		return ((bits + 3) / 2);
2556 }
2557 
2558 /**
2559  * amdgpu_vm_set_fragment_size - adjust fragment size in PTE
2560  *
2561  * @adev: amdgpu_device pointer
2562  * @fragment_size_default: the default fragment size if it's set auto
2563  */
2564 void amdgpu_vm_set_fragment_size(struct amdgpu_device *adev,
2565 				 uint32_t fragment_size_default)
2566 {
2567 	if (amdgpu_vm_fragment_size == -1)
2568 		adev->vm_manager.fragment_size = fragment_size_default;
2569 	else
2570 		adev->vm_manager.fragment_size = amdgpu_vm_fragment_size;
2571 }
2572 
2573 /**
2574  * amdgpu_vm_adjust_size - adjust vm size, block size and fragment size
2575  *
2576  * @adev: amdgpu_device pointer
2577  * @vm_size: the default vm size if it's set auto
2578  */
2579 void amdgpu_vm_adjust_size(struct amdgpu_device *adev, uint64_t vm_size,
2580 			   uint32_t fragment_size_default)
2581 {
2582 	/* adjust vm size firstly */
2583 	if (amdgpu_vm_size == -1)
2584 		adev->vm_manager.vm_size = vm_size;
2585 	else
2586 		adev->vm_manager.vm_size = amdgpu_vm_size;
2587 
2588 	/* block size depends on vm size */
2589 	if (amdgpu_vm_block_size == -1)
2590 		adev->vm_manager.block_size =
2591 			amdgpu_vm_get_block_size(adev->vm_manager.vm_size);
2592 	else
2593 		adev->vm_manager.block_size = amdgpu_vm_block_size;
2594 
2595 	amdgpu_vm_set_fragment_size(adev, fragment_size_default);
2596 
2597 	DRM_INFO("vm size is %llu GB, block size is %u-bit, fragment size is %u-bit\n",
2598 		adev->vm_manager.vm_size, adev->vm_manager.block_size,
2599 		adev->vm_manager.fragment_size);
2600 }
2601 
2602 /**
2603  * amdgpu_vm_init - initialize a vm instance
2604  *
2605  * @adev: amdgpu_device pointer
2606  * @vm: requested vm
2607  * @vm_context: Indicates if it GFX or Compute context
2608  *
2609  * Init @vm fields.
2610  */
2611 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm,
2612 		   int vm_context, unsigned int pasid)
2613 {
2614 	const unsigned align = min(AMDGPU_VM_PTB_ALIGN_SIZE,
2615 		AMDGPU_VM_PTE_COUNT(adev) * 8);
2616 	unsigned ring_instance;
2617 	struct amdgpu_ring *ring;
2618 	struct amd_sched_rq *rq;
2619 	int r, i;
2620 	u64 flags;
2621 	uint64_t init_pde_value = 0;
2622 
2623 	vm->va = RB_ROOT_CACHED;
2624 	vm->client_id = atomic64_inc_return(&adev->vm_manager.client_counter);
2625 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2626 		vm->reserved_vmid[i] = NULL;
2627 	spin_lock_init(&vm->status_lock);
2628 	INIT_LIST_HEAD(&vm->evicted);
2629 	INIT_LIST_HEAD(&vm->relocated);
2630 	INIT_LIST_HEAD(&vm->moved);
2631 	INIT_LIST_HEAD(&vm->freed);
2632 
2633 	/* create scheduler entity for page table updates */
2634 
2635 	ring_instance = atomic_inc_return(&adev->vm_manager.vm_pte_next_ring);
2636 	ring_instance %= adev->vm_manager.vm_pte_num_rings;
2637 	ring = adev->vm_manager.vm_pte_rings[ring_instance];
2638 	rq = &ring->sched.sched_rq[AMD_SCHED_PRIORITY_KERNEL];
2639 	r = amd_sched_entity_init(&ring->sched, &vm->entity,
2640 				  rq, amdgpu_sched_jobs);
2641 	if (r)
2642 		return r;
2643 
2644 	vm->pte_support_ats = false;
2645 
2646 	if (vm_context == AMDGPU_VM_CONTEXT_COMPUTE) {
2647 		vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2648 						AMDGPU_VM_USE_CPU_FOR_COMPUTE);
2649 
2650 		if (adev->asic_type == CHIP_RAVEN) {
2651 			vm->pte_support_ats = true;
2652 			init_pde_value = AMDGPU_PTE_DEFAULT_ATC
2653 					| AMDGPU_PDE_PTE;
2654 
2655 		}
2656 	} else
2657 		vm->use_cpu_for_update = !!(adev->vm_manager.vm_update_mode &
2658 						AMDGPU_VM_USE_CPU_FOR_GFX);
2659 	DRM_DEBUG_DRIVER("VM update mode is %s\n",
2660 			 vm->use_cpu_for_update ? "CPU" : "SDMA");
2661 	WARN_ONCE((vm->use_cpu_for_update & !amdgpu_vm_is_large_bar(adev)),
2662 		  "CPU update of VM recommended only for large BAR system\n");
2663 	vm->last_update = NULL;
2664 
2665 	flags = AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS |
2666 			AMDGPU_GEM_CREATE_VRAM_CLEARED;
2667 	if (vm->use_cpu_for_update)
2668 		flags |= AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED;
2669 	else
2670 		flags |= (AMDGPU_GEM_CREATE_NO_CPU_ACCESS |
2671 				AMDGPU_GEM_CREATE_SHADOW);
2672 
2673 	r = amdgpu_bo_create(adev, amdgpu_vm_bo_size(adev, 0), align, true,
2674 			     AMDGPU_GEM_DOMAIN_VRAM,
2675 			     flags,
2676 			     NULL, NULL, init_pde_value, &vm->root.base.bo);
2677 	if (r)
2678 		goto error_free_sched_entity;
2679 
2680 	vm->root.base.vm = vm;
2681 	list_add_tail(&vm->root.base.bo_list, &vm->root.base.bo->va);
2682 	INIT_LIST_HEAD(&vm->root.base.vm_status);
2683 
2684 	if (vm->use_cpu_for_update) {
2685 		r = amdgpu_bo_reserve(vm->root.base.bo, false);
2686 		if (r)
2687 			goto error_free_root;
2688 
2689 		r = amdgpu_bo_kmap(vm->root.base.bo, NULL);
2690 		amdgpu_bo_unreserve(vm->root.base.bo);
2691 		if (r)
2692 			goto error_free_root;
2693 	}
2694 
2695 	if (pasid) {
2696 		unsigned long flags;
2697 
2698 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2699 		r = idr_alloc(&adev->vm_manager.pasid_idr, vm, pasid, pasid + 1,
2700 			      GFP_ATOMIC);
2701 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2702 		if (r < 0)
2703 			goto error_free_root;
2704 
2705 		vm->pasid = pasid;
2706 	}
2707 
2708 	INIT_KFIFO(vm->faults);
2709 	vm->fault_credit = 16;
2710 
2711 	return 0;
2712 
2713 error_free_root:
2714 	amdgpu_bo_unref(&vm->root.base.bo->shadow);
2715 	amdgpu_bo_unref(&vm->root.base.bo);
2716 	vm->root.base.bo = NULL;
2717 
2718 error_free_sched_entity:
2719 	amd_sched_entity_fini(&ring->sched, &vm->entity);
2720 
2721 	return r;
2722 }
2723 
2724 /**
2725  * amdgpu_vm_free_levels - free PD/PT levels
2726  *
2727  * @level: PD/PT starting level to free
2728  *
2729  * Free the page directory or page table level and all sub levels.
2730  */
2731 static void amdgpu_vm_free_levels(struct amdgpu_vm_pt *level)
2732 {
2733 	unsigned i;
2734 
2735 	if (level->base.bo) {
2736 		list_del(&level->base.bo_list);
2737 		list_del(&level->base.vm_status);
2738 		amdgpu_bo_unref(&level->base.bo->shadow);
2739 		amdgpu_bo_unref(&level->base.bo);
2740 	}
2741 
2742 	if (level->entries)
2743 		for (i = 0; i <= level->last_entry_used; i++)
2744 			amdgpu_vm_free_levels(&level->entries[i]);
2745 
2746 	kvfree(level->entries);
2747 }
2748 
2749 /**
2750  * amdgpu_vm_fini - tear down a vm instance
2751  *
2752  * @adev: amdgpu_device pointer
2753  * @vm: requested vm
2754  *
2755  * Tear down @vm.
2756  * Unbind the VM and remove all bos from the vm bo list
2757  */
2758 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2759 {
2760 	struct amdgpu_bo_va_mapping *mapping, *tmp;
2761 	bool prt_fini_needed = !!adev->gart.gart_funcs->set_prt;
2762 	struct amdgpu_bo *root;
2763 	u64 fault;
2764 	int i, r;
2765 
2766 	/* Clear pending page faults from IH when the VM is destroyed */
2767 	while (kfifo_get(&vm->faults, &fault))
2768 		amdgpu_ih_clear_fault(adev, fault);
2769 
2770 	if (vm->pasid) {
2771 		unsigned long flags;
2772 
2773 		spin_lock_irqsave(&adev->vm_manager.pasid_lock, flags);
2774 		idr_remove(&adev->vm_manager.pasid_idr, vm->pasid);
2775 		spin_unlock_irqrestore(&adev->vm_manager.pasid_lock, flags);
2776 	}
2777 
2778 	amd_sched_entity_fini(vm->entity.sched, &vm->entity);
2779 
2780 	if (!RB_EMPTY_ROOT(&vm->va.rb_root)) {
2781 		dev_err(adev->dev, "still active bo inside vm\n");
2782 	}
2783 	rbtree_postorder_for_each_entry_safe(mapping, tmp,
2784 					     &vm->va.rb_root, rb) {
2785 		list_del(&mapping->list);
2786 		amdgpu_vm_it_remove(mapping, &vm->va);
2787 		kfree(mapping);
2788 	}
2789 	list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2790 		if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
2791 			amdgpu_vm_prt_fini(adev, vm);
2792 			prt_fini_needed = false;
2793 		}
2794 
2795 		list_del(&mapping->list);
2796 		amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2797 	}
2798 
2799 	root = amdgpu_bo_ref(vm->root.base.bo);
2800 	r = amdgpu_bo_reserve(root, true);
2801 	if (r) {
2802 		dev_err(adev->dev, "Leaking page tables because BO reservation failed\n");
2803 	} else {
2804 		amdgpu_vm_free_levels(&vm->root);
2805 		amdgpu_bo_unreserve(root);
2806 	}
2807 	amdgpu_bo_unref(&root);
2808 	dma_fence_put(vm->last_update);
2809 	for (i = 0; i < AMDGPU_MAX_VMHUBS; i++)
2810 		amdgpu_vm_free_reserved_vmid(adev, vm, i);
2811 }
2812 
2813 /**
2814  * amdgpu_vm_pasid_fault_credit - Check fault credit for given PASID
2815  *
2816  * @adev: amdgpu_device pointer
2817  * @pasid: PASID do identify the VM
2818  *
2819  * This function is expected to be called in interrupt context. Returns
2820  * true if there was fault credit, false otherwise
2821  */
2822 bool amdgpu_vm_pasid_fault_credit(struct amdgpu_device *adev,
2823 				  unsigned int pasid)
2824 {
2825 	struct amdgpu_vm *vm;
2826 
2827 	spin_lock(&adev->vm_manager.pasid_lock);
2828 	vm = idr_find(&adev->vm_manager.pasid_idr, pasid);
2829 	spin_unlock(&adev->vm_manager.pasid_lock);
2830 	if (!vm)
2831 		/* VM not found, can't track fault credit */
2832 		return true;
2833 
2834 	/* No lock needed. only accessed by IRQ handler */
2835 	if (!vm->fault_credit)
2836 		/* Too many faults in this VM */
2837 		return false;
2838 
2839 	vm->fault_credit--;
2840 	return true;
2841 }
2842 
2843 /**
2844  * amdgpu_vm_manager_init - init the VM manager
2845  *
2846  * @adev: amdgpu_device pointer
2847  *
2848  * Initialize the VM manager structures
2849  */
2850 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
2851 {
2852 	unsigned i, j;
2853 
2854 	for (i = 0; i < AMDGPU_MAX_VMHUBS; ++i) {
2855 		struct amdgpu_vm_id_manager *id_mgr =
2856 			&adev->vm_manager.id_mgr[i];
2857 
2858 		mutex_init(&id_mgr->lock);
2859 		INIT_LIST_HEAD(&id_mgr->ids_lru);
2860 		atomic_set(&id_mgr->reserved_vmid_num, 0);
2861 
2862 		/* skip over VMID 0, since it is the system VM */
2863 		for (j = 1; j < id_mgr->num_ids; ++j) {
2864 			amdgpu_vm_reset_id(adev, i, j);
2865 			amdgpu_sync_create(&id_mgr->ids[i].active);
2866 			list_add_tail(&id_mgr->ids[j].list, &id_mgr->ids_lru);
2867 		}
2868 	}
2869 
2870 	adev->vm_manager.fence_context =
2871 		dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2872 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
2873 		adev->vm_manager.seqno[i] = 0;
2874 
2875 	atomic_set(&adev->vm_manager.vm_pte_next_ring, 0);
2876 	atomic64_set(&adev->vm_manager.client_counter, 0);
2877 	spin_lock_init(&adev->vm_manager.prt_lock);
2878 	atomic_set(&adev->vm_manager.num_prt_users, 0);
2879 
2880 	/* If not overridden by the user, by default, only in large BAR systems
2881 	 * Compute VM tables will be updated by CPU
2882 	 */
2883 #ifdef CONFIG_X86_64
2884 	if (amdgpu_vm_update_mode == -1) {
2885 		if (amdgpu_vm_is_large_bar(adev))
2886 			adev->vm_manager.vm_update_mode =
2887 				AMDGPU_VM_USE_CPU_FOR_COMPUTE;
2888 		else
2889 			adev->vm_manager.vm_update_mode = 0;
2890 	} else
2891 		adev->vm_manager.vm_update_mode = amdgpu_vm_update_mode;
2892 #else
2893 	adev->vm_manager.vm_update_mode = 0;
2894 #endif
2895 
2896 	idr_init(&adev->vm_manager.pasid_idr);
2897 	spin_lock_init(&adev->vm_manager.pasid_lock);
2898 }
2899 
2900 /**
2901  * amdgpu_vm_manager_fini - cleanup VM manager
2902  *
2903  * @adev: amdgpu_device pointer
2904  *
2905  * Cleanup the VM manager and free resources.
2906  */
2907 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
2908 {
2909 	unsigned i, j;
2910 
2911 	WARN_ON(!idr_is_empty(&adev->vm_manager.pasid_idr));
2912 	idr_destroy(&adev->vm_manager.pasid_idr);
2913 
2914 	for (i = 0; i < AMDGPU_MAX_VMHUBS; ++i) {
2915 		struct amdgpu_vm_id_manager *id_mgr =
2916 			&adev->vm_manager.id_mgr[i];
2917 
2918 		mutex_destroy(&id_mgr->lock);
2919 		for (j = 0; j < AMDGPU_NUM_VM; ++j) {
2920 			struct amdgpu_vm_id *id = &id_mgr->ids[j];
2921 
2922 			amdgpu_sync_free(&id->active);
2923 			dma_fence_put(id->flushed_updates);
2924 			dma_fence_put(id->last_flush);
2925 		}
2926 	}
2927 }
2928 
2929 int amdgpu_vm_ioctl(struct drm_device *dev, void *data, struct drm_file *filp)
2930 {
2931 	union drm_amdgpu_vm *args = data;
2932 	struct amdgpu_device *adev = dev->dev_private;
2933 	struct amdgpu_fpriv *fpriv = filp->driver_priv;
2934 	int r;
2935 
2936 	switch (args->in.op) {
2937 	case AMDGPU_VM_OP_RESERVE_VMID:
2938 		/* current, we only have requirement to reserve vmid from gfxhub */
2939 		r = amdgpu_vm_alloc_reserved_vmid(adev, &fpriv->vm,
2940 						  AMDGPU_GFXHUB);
2941 		if (r)
2942 			return r;
2943 		break;
2944 	case AMDGPU_VM_OP_UNRESERVE_VMID:
2945 		amdgpu_vm_free_reserved_vmid(adev, &fpriv->vm, AMDGPU_GFXHUB);
2946 		break;
2947 	default:
2948 		return -EINVAL;
2949 	}
2950 
2951 	return 0;
2952 }
2953