xref: /openbmc/linux/drivers/gpu/drm/amd/amdgpu/amdgpu_vm.c (revision e5f586c763a079349398e2b0c7c271386193ac34)
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 <drm/drmP.h>
30 #include <drm/amdgpu_drm.h>
31 #include "amdgpu.h"
32 #include "amdgpu_trace.h"
33 
34 /*
35  * GPUVM
36  * GPUVM is similar to the legacy gart on older asics, however
37  * rather than there being a single global gart table
38  * for the entire GPU, there are multiple VM page tables active
39  * at any given time.  The VM page tables can contain a mix
40  * vram pages and system memory pages and system memory pages
41  * can be mapped as snooped (cached system pages) or unsnooped
42  * (uncached system pages).
43  * Each VM has an ID associated with it and there is a page table
44  * associated with each VMID.  When execting a command buffer,
45  * the kernel tells the the ring what VMID to use for that command
46  * buffer.  VMIDs are allocated dynamically as commands are submitted.
47  * The userspace drivers maintain their own address space and the kernel
48  * sets up their pages tables accordingly when they submit their
49  * command buffers and a VMID is assigned.
50  * Cayman/Trinity support up to 8 active VMs at any given time;
51  * SI supports 16.
52  */
53 
54 /* Local structure. Encapsulate some VM table update parameters to reduce
55  * the number of function parameters
56  */
57 struct amdgpu_pte_update_params {
58 	/* amdgpu device we do this update for */
59 	struct amdgpu_device *adev;
60 	/* optional amdgpu_vm we do this update for */
61 	struct amdgpu_vm *vm;
62 	/* address where to copy page table entries from */
63 	uint64_t src;
64 	/* indirect buffer to fill with commands */
65 	struct amdgpu_ib *ib;
66 	/* Function which actually does the update */
67 	void (*func)(struct amdgpu_pte_update_params *params, uint64_t pe,
68 		     uint64_t addr, unsigned count, uint32_t incr,
69 		     uint64_t flags);
70 	/* indicate update pt or its shadow */
71 	bool shadow;
72 };
73 
74 /* Helper to disable partial resident texture feature from a fence callback */
75 struct amdgpu_prt_cb {
76 	struct amdgpu_device *adev;
77 	struct dma_fence_cb cb;
78 };
79 
80 /**
81  * amdgpu_vm_num_entries - return the number of entries in a PD/PT
82  *
83  * @adev: amdgpu_device pointer
84  *
85  * Calculate the number of entries in a page directory or page table.
86  */
87 static unsigned amdgpu_vm_num_entries(struct amdgpu_device *adev,
88 				      unsigned level)
89 {
90 	if (level == 0)
91 		/* For the root directory */
92 		return adev->vm_manager.max_pfn >>
93 			(amdgpu_vm_block_size * adev->vm_manager.num_level);
94 	else if (level == adev->vm_manager.num_level)
95 		/* For the page tables on the leaves */
96 		return AMDGPU_VM_PTE_COUNT;
97 	else
98 		/* Everything in between */
99 		return 1 << amdgpu_vm_block_size;
100 }
101 
102 /**
103  * amdgpu_vm_bo_size - returns the size of the BOs in bytes
104  *
105  * @adev: amdgpu_device pointer
106  *
107  * Calculate the size of the BO for a page directory or page table in bytes.
108  */
109 static unsigned amdgpu_vm_bo_size(struct amdgpu_device *adev, unsigned level)
110 {
111 	return AMDGPU_GPU_PAGE_ALIGN(amdgpu_vm_num_entries(adev, level) * 8);
112 }
113 
114 /**
115  * amdgpu_vm_get_pd_bo - add the VM PD to a validation list
116  *
117  * @vm: vm providing the BOs
118  * @validated: head of validation list
119  * @entry: entry to add
120  *
121  * Add the page directory to the list of BOs to
122  * validate for command submission.
123  */
124 void amdgpu_vm_get_pd_bo(struct amdgpu_vm *vm,
125 			 struct list_head *validated,
126 			 struct amdgpu_bo_list_entry *entry)
127 {
128 	entry->robj = vm->root.bo;
129 	entry->priority = 0;
130 	entry->tv.bo = &entry->robj->tbo;
131 	entry->tv.shared = true;
132 	entry->user_pages = NULL;
133 	list_add(&entry->tv.head, validated);
134 }
135 
136 /**
137  * amdgpu_vm_validate_layer - validate a single page table level
138  *
139  * @parent: parent page table level
140  * @validate: callback to do the validation
141  * @param: parameter for the validation callback
142  *
143  * Validate the page table BOs on command submission if neccessary.
144  */
145 static int amdgpu_vm_validate_level(struct amdgpu_vm_pt *parent,
146 				    int (*validate)(void *, struct amdgpu_bo *),
147 				    void *param)
148 {
149 	unsigned i;
150 	int r;
151 
152 	if (!parent->entries)
153 		return 0;
154 
155 	for (i = 0; i <= parent->last_entry_used; ++i) {
156 		struct amdgpu_vm_pt *entry = &parent->entries[i];
157 
158 		if (!entry->bo)
159 			continue;
160 
161 		r = validate(param, entry->bo);
162 		if (r)
163 			return r;
164 
165 		/*
166 		 * Recurse into the sub directory. This is harmless because we
167 		 * have only a maximum of 5 layers.
168 		 */
169 		r = amdgpu_vm_validate_level(entry, validate, param);
170 		if (r)
171 			return r;
172 	}
173 
174 	return r;
175 }
176 
177 /**
178  * amdgpu_vm_validate_pt_bos - validate the page table BOs
179  *
180  * @adev: amdgpu device pointer
181  * @vm: vm providing the BOs
182  * @validate: callback to do the validation
183  * @param: parameter for the validation callback
184  *
185  * Validate the page table BOs on command submission if neccessary.
186  */
187 int amdgpu_vm_validate_pt_bos(struct amdgpu_device *adev, struct amdgpu_vm *vm,
188 			      int (*validate)(void *p, struct amdgpu_bo *bo),
189 			      void *param)
190 {
191 	uint64_t num_evictions;
192 
193 	/* We only need to validate the page tables
194 	 * if they aren't already valid.
195 	 */
196 	num_evictions = atomic64_read(&adev->num_evictions);
197 	if (num_evictions == vm->last_eviction_counter)
198 		return 0;
199 
200 	return amdgpu_vm_validate_level(&vm->root, validate, param);
201 }
202 
203 /**
204  * amdgpu_vm_move_level_in_lru - move one level of PT BOs to the LRU tail
205  *
206  * @adev: amdgpu device instance
207  * @vm: vm providing the BOs
208  *
209  * Move the PT BOs to the tail of the LRU.
210  */
211 static void amdgpu_vm_move_level_in_lru(struct amdgpu_vm_pt *parent)
212 {
213 	unsigned i;
214 
215 	if (!parent->entries)
216 		return;
217 
218 	for (i = 0; i <= parent->last_entry_used; ++i) {
219 		struct amdgpu_vm_pt *entry = &parent->entries[i];
220 
221 		if (!entry->bo)
222 			continue;
223 
224 		ttm_bo_move_to_lru_tail(&entry->bo->tbo);
225 		amdgpu_vm_move_level_in_lru(entry);
226 	}
227 }
228 
229 /**
230  * amdgpu_vm_move_pt_bos_in_lru - move the PT BOs to the LRU tail
231  *
232  * @adev: amdgpu device instance
233  * @vm: vm providing the BOs
234  *
235  * Move the PT BOs to the tail of the LRU.
236  */
237 void amdgpu_vm_move_pt_bos_in_lru(struct amdgpu_device *adev,
238 				  struct amdgpu_vm *vm)
239 {
240 	struct ttm_bo_global *glob = adev->mman.bdev.glob;
241 
242 	spin_lock(&glob->lru_lock);
243 	amdgpu_vm_move_level_in_lru(&vm->root);
244 	spin_unlock(&glob->lru_lock);
245 }
246 
247  /**
248  * amdgpu_vm_alloc_levels - allocate the PD/PT levels
249  *
250  * @adev: amdgpu_device pointer
251  * @vm: requested vm
252  * @saddr: start of the address range
253  * @eaddr: end of the address range
254  *
255  * Make sure the page directories and page tables are allocated
256  */
257 static int amdgpu_vm_alloc_levels(struct amdgpu_device *adev,
258 				  struct amdgpu_vm *vm,
259 				  struct amdgpu_vm_pt *parent,
260 				  uint64_t saddr, uint64_t eaddr,
261 				  unsigned level)
262 {
263 	unsigned shift = (adev->vm_manager.num_level - level) *
264 		amdgpu_vm_block_size;
265 	unsigned pt_idx, from, to;
266 	int r;
267 
268 	if (!parent->entries) {
269 		unsigned num_entries = amdgpu_vm_num_entries(adev, level);
270 
271 		parent->entries = drm_calloc_large(num_entries,
272 						   sizeof(struct amdgpu_vm_pt));
273 		if (!parent->entries)
274 			return -ENOMEM;
275 		memset(parent->entries, 0 , sizeof(struct amdgpu_vm_pt));
276 	}
277 
278 	from = (saddr >> shift) % amdgpu_vm_num_entries(adev, level);
279 	to = (eaddr >> shift) % amdgpu_vm_num_entries(adev, level);
280 
281 	if (to > parent->last_entry_used)
282 		parent->last_entry_used = to;
283 
284 	++level;
285 
286 	/* walk over the address space and allocate the page tables */
287 	for (pt_idx = from; pt_idx <= to; ++pt_idx) {
288 		struct reservation_object *resv = vm->root.bo->tbo.resv;
289 		struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
290 		struct amdgpu_bo *pt;
291 
292 		if (!entry->bo) {
293 			r = amdgpu_bo_create(adev,
294 					     amdgpu_vm_bo_size(adev, level),
295 					     AMDGPU_GPU_PAGE_SIZE, true,
296 					     AMDGPU_GEM_DOMAIN_VRAM,
297 					     AMDGPU_GEM_CREATE_NO_CPU_ACCESS |
298 					     AMDGPU_GEM_CREATE_SHADOW |
299 					     AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS |
300 					     AMDGPU_GEM_CREATE_VRAM_CLEARED,
301 					     NULL, resv, &pt);
302 			if (r)
303 				return r;
304 
305 			/* Keep a reference to the root directory to avoid
306 			* freeing them up in the wrong order.
307 			*/
308 			pt->parent = amdgpu_bo_ref(vm->root.bo);
309 
310 			entry->bo = pt;
311 			entry->addr = 0;
312 		}
313 
314 		if (level < adev->vm_manager.num_level) {
315 			r = amdgpu_vm_alloc_levels(adev, vm, entry, saddr,
316 						   eaddr, level);
317 			if (r)
318 				return r;
319 		}
320 	}
321 
322 	return 0;
323 }
324 
325 /**
326  * amdgpu_vm_alloc_pts - Allocate page tables.
327  *
328  * @adev: amdgpu_device pointer
329  * @vm: VM to allocate page tables for
330  * @saddr: Start address which needs to be allocated
331  * @size: Size from start address we need.
332  *
333  * Make sure the page tables are allocated.
334  */
335 int amdgpu_vm_alloc_pts(struct amdgpu_device *adev,
336 			struct amdgpu_vm *vm,
337 			uint64_t saddr, uint64_t size)
338 {
339 	unsigned last_pfn;
340 	uint64_t eaddr;
341 
342 	/* validate the parameters */
343 	if (saddr & AMDGPU_GPU_PAGE_MASK || size & AMDGPU_GPU_PAGE_MASK)
344 		return -EINVAL;
345 
346 	eaddr = saddr + size - 1;
347 	last_pfn = eaddr / AMDGPU_GPU_PAGE_SIZE;
348 	if (last_pfn >= adev->vm_manager.max_pfn) {
349 		dev_err(adev->dev, "va above limit (0x%08X >= 0x%08X)\n",
350 			last_pfn, adev->vm_manager.max_pfn);
351 		return -EINVAL;
352 	}
353 
354 	saddr /= AMDGPU_GPU_PAGE_SIZE;
355 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
356 
357 	return amdgpu_vm_alloc_levels(adev, vm, &vm->root, saddr, eaddr, 0);
358 }
359 
360 static bool amdgpu_vm_is_gpu_reset(struct amdgpu_device *adev,
361 			      struct amdgpu_vm_id *id)
362 {
363 	return id->current_gpu_reset_count !=
364 		atomic_read(&adev->gpu_reset_counter) ? true : false;
365 }
366 
367 /**
368  * amdgpu_vm_grab_id - allocate the next free VMID
369  *
370  * @vm: vm to allocate id for
371  * @ring: ring we want to submit job to
372  * @sync: sync object where we add dependencies
373  * @fence: fence protecting ID from reuse
374  *
375  * Allocate an id for the vm, adding fences to the sync obj as necessary.
376  */
377 int amdgpu_vm_grab_id(struct amdgpu_vm *vm, struct amdgpu_ring *ring,
378 		      struct amdgpu_sync *sync, struct dma_fence *fence,
379 		      struct amdgpu_job *job)
380 {
381 	struct amdgpu_device *adev = ring->adev;
382 	uint64_t fence_context = adev->fence_context + ring->idx;
383 	struct dma_fence *updates = sync->last_vm_update;
384 	struct amdgpu_vm_id *id, *idle;
385 	struct dma_fence **fences;
386 	unsigned i;
387 	int r = 0;
388 
389 	fences = kmalloc_array(sizeof(void *), adev->vm_manager.num_ids,
390 			       GFP_KERNEL);
391 	if (!fences)
392 		return -ENOMEM;
393 
394 	mutex_lock(&adev->vm_manager.lock);
395 
396 	/* Check if we have an idle VMID */
397 	i = 0;
398 	list_for_each_entry(idle, &adev->vm_manager.ids_lru, list) {
399 		fences[i] = amdgpu_sync_peek_fence(&idle->active, ring);
400 		if (!fences[i])
401 			break;
402 		++i;
403 	}
404 
405 	/* If we can't find a idle VMID to use, wait till one becomes available */
406 	if (&idle->list == &adev->vm_manager.ids_lru) {
407 		u64 fence_context = adev->vm_manager.fence_context + ring->idx;
408 		unsigned seqno = ++adev->vm_manager.seqno[ring->idx];
409 		struct dma_fence_array *array;
410 		unsigned j;
411 
412 		for (j = 0; j < i; ++j)
413 			dma_fence_get(fences[j]);
414 
415 		array = dma_fence_array_create(i, fences, fence_context,
416 					   seqno, true);
417 		if (!array) {
418 			for (j = 0; j < i; ++j)
419 				dma_fence_put(fences[j]);
420 			kfree(fences);
421 			r = -ENOMEM;
422 			goto error;
423 		}
424 
425 
426 		r = amdgpu_sync_fence(ring->adev, sync, &array->base);
427 		dma_fence_put(&array->base);
428 		if (r)
429 			goto error;
430 
431 		mutex_unlock(&adev->vm_manager.lock);
432 		return 0;
433 
434 	}
435 	kfree(fences);
436 
437 	job->vm_needs_flush = true;
438 	/* Check if we can use a VMID already assigned to this VM */
439 	i = ring->idx;
440 	do {
441 		struct dma_fence *flushed;
442 
443 		id = vm->ids[i++];
444 		if (i == AMDGPU_MAX_RINGS)
445 			i = 0;
446 
447 		/* Check all the prerequisites to using this VMID */
448 		if (!id)
449 			continue;
450 		if (amdgpu_vm_is_gpu_reset(adev, id))
451 			continue;
452 
453 		if (atomic64_read(&id->owner) != vm->client_id)
454 			continue;
455 
456 		if (job->vm_pd_addr != id->pd_gpu_addr)
457 			continue;
458 
459 		if (!id->last_flush)
460 			continue;
461 
462 		if (id->last_flush->context != fence_context &&
463 		    !dma_fence_is_signaled(id->last_flush))
464 			continue;
465 
466 		flushed  = id->flushed_updates;
467 		if (updates &&
468 		    (!flushed || dma_fence_is_later(updates, flushed)))
469 			continue;
470 
471 		/* Good we can use this VMID. Remember this submission as
472 		 * user of the VMID.
473 		 */
474 		r = amdgpu_sync_fence(ring->adev, &id->active, fence);
475 		if (r)
476 			goto error;
477 
478 		id->current_gpu_reset_count = atomic_read(&adev->gpu_reset_counter);
479 		list_move_tail(&id->list, &adev->vm_manager.ids_lru);
480 		vm->ids[ring->idx] = id;
481 
482 		job->vm_id = id - adev->vm_manager.ids;
483 		job->vm_needs_flush = false;
484 		trace_amdgpu_vm_grab_id(vm, ring->idx, job);
485 
486 		mutex_unlock(&adev->vm_manager.lock);
487 		return 0;
488 
489 	} while (i != ring->idx);
490 
491 	/* Still no ID to use? Then use the idle one found earlier */
492 	id = idle;
493 
494 	/* Remember this submission as user of the VMID */
495 	r = amdgpu_sync_fence(ring->adev, &id->active, fence);
496 	if (r)
497 		goto error;
498 
499 	dma_fence_put(id->first);
500 	id->first = dma_fence_get(fence);
501 
502 	dma_fence_put(id->last_flush);
503 	id->last_flush = NULL;
504 
505 	dma_fence_put(id->flushed_updates);
506 	id->flushed_updates = dma_fence_get(updates);
507 
508 	id->pd_gpu_addr = job->vm_pd_addr;
509 	id->current_gpu_reset_count = atomic_read(&adev->gpu_reset_counter);
510 	list_move_tail(&id->list, &adev->vm_manager.ids_lru);
511 	atomic64_set(&id->owner, vm->client_id);
512 	vm->ids[ring->idx] = id;
513 
514 	job->vm_id = id - adev->vm_manager.ids;
515 	trace_amdgpu_vm_grab_id(vm, ring->idx, job);
516 
517 error:
518 	mutex_unlock(&adev->vm_manager.lock);
519 	return r;
520 }
521 
522 static bool amdgpu_vm_ring_has_compute_vm_bug(struct amdgpu_ring *ring)
523 {
524 	struct amdgpu_device *adev = ring->adev;
525 	const struct amdgpu_ip_block *ip_block;
526 
527 	if (ring->funcs->type != AMDGPU_RING_TYPE_COMPUTE)
528 		/* only compute rings */
529 		return false;
530 
531 	ip_block = amdgpu_get_ip_block(adev, AMD_IP_BLOCK_TYPE_GFX);
532 	if (!ip_block)
533 		return false;
534 
535 	if (ip_block->version->major <= 7) {
536 		/* gfx7 has no workaround */
537 		return true;
538 	} else if (ip_block->version->major == 8) {
539 		if (adev->gfx.mec_fw_version >= 673)
540 			/* gfx8 is fixed in MEC firmware 673 */
541 			return false;
542 		else
543 			return true;
544 	}
545 	return false;
546 }
547 
548 static u64 amdgpu_vm_adjust_mc_addr(struct amdgpu_device *adev, u64 mc_addr)
549 {
550 	u64 addr = mc_addr;
551 
552 	if (adev->mc.mc_funcs && adev->mc.mc_funcs->adjust_mc_addr)
553 		addr = adev->mc.mc_funcs->adjust_mc_addr(adev, addr);
554 
555 	return addr;
556 }
557 
558 /**
559  * amdgpu_vm_flush - hardware flush the vm
560  *
561  * @ring: ring to use for flush
562  * @vm_id: vmid number to use
563  * @pd_addr: address of the page directory
564  *
565  * Emit a VM flush when it is necessary.
566  */
567 int amdgpu_vm_flush(struct amdgpu_ring *ring, struct amdgpu_job *job)
568 {
569 	struct amdgpu_device *adev = ring->adev;
570 	struct amdgpu_vm_id *id = &adev->vm_manager.ids[job->vm_id];
571 	bool gds_switch_needed = ring->funcs->emit_gds_switch && (
572 		id->gds_base != job->gds_base ||
573 		id->gds_size != job->gds_size ||
574 		id->gws_base != job->gws_base ||
575 		id->gws_size != job->gws_size ||
576 		id->oa_base != job->oa_base ||
577 		id->oa_size != job->oa_size);
578 	int r;
579 
580 	if (job->vm_needs_flush || gds_switch_needed ||
581 		amdgpu_vm_is_gpu_reset(adev, id) ||
582 		amdgpu_vm_ring_has_compute_vm_bug(ring)) {
583 		unsigned patch_offset = 0;
584 
585 		if (ring->funcs->init_cond_exec)
586 			patch_offset = amdgpu_ring_init_cond_exec(ring);
587 
588 		if (ring->funcs->emit_pipeline_sync &&
589 			(job->vm_needs_flush || gds_switch_needed ||
590 			amdgpu_vm_ring_has_compute_vm_bug(ring)))
591 			amdgpu_ring_emit_pipeline_sync(ring);
592 
593 		if (ring->funcs->emit_vm_flush && (job->vm_needs_flush ||
594 			amdgpu_vm_is_gpu_reset(adev, id))) {
595 			struct dma_fence *fence;
596 			u64 pd_addr = amdgpu_vm_adjust_mc_addr(adev, job->vm_pd_addr);
597 
598 			trace_amdgpu_vm_flush(pd_addr, ring->idx, job->vm_id);
599 			amdgpu_ring_emit_vm_flush(ring, job->vm_id, pd_addr);
600 
601 			r = amdgpu_fence_emit(ring, &fence);
602 			if (r)
603 				return r;
604 
605 			mutex_lock(&adev->vm_manager.lock);
606 			dma_fence_put(id->last_flush);
607 			id->last_flush = fence;
608 			mutex_unlock(&adev->vm_manager.lock);
609 		}
610 
611 		if (gds_switch_needed) {
612 			id->gds_base = job->gds_base;
613 			id->gds_size = job->gds_size;
614 			id->gws_base = job->gws_base;
615 			id->gws_size = job->gws_size;
616 			id->oa_base = job->oa_base;
617 			id->oa_size = job->oa_size;
618 			amdgpu_ring_emit_gds_switch(ring, job->vm_id,
619 							job->gds_base, job->gds_size,
620 							job->gws_base, job->gws_size,
621 							job->oa_base, job->oa_size);
622 		}
623 
624 		if (ring->funcs->patch_cond_exec)
625 			amdgpu_ring_patch_cond_exec(ring, patch_offset);
626 
627 		/* the double SWITCH_BUFFER here *cannot* be skipped by COND_EXEC */
628 		if (ring->funcs->emit_switch_buffer) {
629 			amdgpu_ring_emit_switch_buffer(ring);
630 			amdgpu_ring_emit_switch_buffer(ring);
631 		}
632 	}
633 	return 0;
634 }
635 
636 /**
637  * amdgpu_vm_reset_id - reset VMID to zero
638  *
639  * @adev: amdgpu device structure
640  * @vm_id: vmid number to use
641  *
642  * Reset saved GDW, GWS and OA to force switch on next flush.
643  */
644 void amdgpu_vm_reset_id(struct amdgpu_device *adev, unsigned vm_id)
645 {
646 	struct amdgpu_vm_id *id = &adev->vm_manager.ids[vm_id];
647 
648 	id->gds_base = 0;
649 	id->gds_size = 0;
650 	id->gws_base = 0;
651 	id->gws_size = 0;
652 	id->oa_base = 0;
653 	id->oa_size = 0;
654 }
655 
656 /**
657  * amdgpu_vm_bo_find - find the bo_va for a specific vm & bo
658  *
659  * @vm: requested vm
660  * @bo: requested buffer object
661  *
662  * Find @bo inside the requested vm.
663  * Search inside the @bos vm list for the requested vm
664  * Returns the found bo_va or NULL if none is found
665  *
666  * Object has to be reserved!
667  */
668 struct amdgpu_bo_va *amdgpu_vm_bo_find(struct amdgpu_vm *vm,
669 				       struct amdgpu_bo *bo)
670 {
671 	struct amdgpu_bo_va *bo_va;
672 
673 	list_for_each_entry(bo_va, &bo->va, bo_list) {
674 		if (bo_va->vm == vm) {
675 			return bo_va;
676 		}
677 	}
678 	return NULL;
679 }
680 
681 /**
682  * amdgpu_vm_do_set_ptes - helper to call the right asic function
683  *
684  * @params: see amdgpu_pte_update_params definition
685  * @pe: addr of the page entry
686  * @addr: dst addr to write into pe
687  * @count: number of page entries to update
688  * @incr: increase next addr by incr bytes
689  * @flags: hw access flags
690  *
691  * Traces the parameters and calls the right asic functions
692  * to setup the page table using the DMA.
693  */
694 static void amdgpu_vm_do_set_ptes(struct amdgpu_pte_update_params *params,
695 				  uint64_t pe, uint64_t addr,
696 				  unsigned count, uint32_t incr,
697 				  uint64_t flags)
698 {
699 	trace_amdgpu_vm_set_ptes(pe, addr, count, incr, flags);
700 
701 	if (count < 3) {
702 		amdgpu_vm_write_pte(params->adev, params->ib, pe,
703 				    addr | flags, count, incr);
704 
705 	} else {
706 		amdgpu_vm_set_pte_pde(params->adev, params->ib, pe, addr,
707 				      count, incr, flags);
708 	}
709 }
710 
711 /**
712  * amdgpu_vm_do_copy_ptes - copy the PTEs from the GART
713  *
714  * @params: see amdgpu_pte_update_params definition
715  * @pe: addr of the page entry
716  * @addr: dst addr to write into pe
717  * @count: number of page entries to update
718  * @incr: increase next addr by incr bytes
719  * @flags: hw access flags
720  *
721  * Traces the parameters and calls the DMA function to copy the PTEs.
722  */
723 static void amdgpu_vm_do_copy_ptes(struct amdgpu_pte_update_params *params,
724 				   uint64_t pe, uint64_t addr,
725 				   unsigned count, uint32_t incr,
726 				   uint64_t flags)
727 {
728 	uint64_t src = (params->src + (addr >> 12) * 8);
729 
730 
731 	trace_amdgpu_vm_copy_ptes(pe, src, count);
732 
733 	amdgpu_vm_copy_pte(params->adev, params->ib, pe, src, count);
734 }
735 
736 /**
737  * amdgpu_vm_map_gart - Resolve gart mapping of addr
738  *
739  * @pages_addr: optional DMA address to use for lookup
740  * @addr: the unmapped addr
741  *
742  * Look up the physical address of the page that the pte resolves
743  * to and return the pointer for the page table entry.
744  */
745 static uint64_t amdgpu_vm_map_gart(const dma_addr_t *pages_addr, uint64_t addr)
746 {
747 	uint64_t result;
748 
749 	/* page table offset */
750 	result = pages_addr[addr >> PAGE_SHIFT];
751 
752 	/* in case cpu page size != gpu page size*/
753 	result |= addr & (~PAGE_MASK);
754 
755 	result &= 0xFFFFFFFFFFFFF000ULL;
756 
757 	return result;
758 }
759 
760 /*
761  * amdgpu_vm_update_level - update a single level in the hierarchy
762  *
763  * @adev: amdgpu_device pointer
764  * @vm: requested vm
765  * @parent: parent directory
766  *
767  * Makes sure all entries in @parent are up to date.
768  * Returns 0 for success, error for failure.
769  */
770 static int amdgpu_vm_update_level(struct amdgpu_device *adev,
771 				  struct amdgpu_vm *vm,
772 				  struct amdgpu_vm_pt *parent,
773 				  unsigned level)
774 {
775 	struct amdgpu_bo *shadow;
776 	struct amdgpu_ring *ring;
777 	uint64_t pd_addr, shadow_addr;
778 	uint32_t incr = amdgpu_vm_bo_size(adev, level + 1);
779 	uint64_t last_pde = ~0, last_pt = ~0, last_shadow = ~0;
780 	unsigned count = 0, pt_idx, ndw;
781 	struct amdgpu_job *job;
782 	struct amdgpu_pte_update_params params;
783 	struct dma_fence *fence = NULL;
784 
785 	int r;
786 
787 	if (!parent->entries)
788 		return 0;
789 	ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
790 
791 	/* padding, etc. */
792 	ndw = 64;
793 
794 	/* assume the worst case */
795 	ndw += parent->last_entry_used * 6;
796 
797 	pd_addr = amdgpu_bo_gpu_offset(parent->bo);
798 
799 	shadow = parent->bo->shadow;
800 	if (shadow) {
801 		r = amdgpu_ttm_bind(&shadow->tbo, &shadow->tbo.mem);
802 		if (r)
803 			return r;
804 		shadow_addr = amdgpu_bo_gpu_offset(shadow);
805 		ndw *= 2;
806 	} else {
807 		shadow_addr = 0;
808 	}
809 
810 	r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
811 	if (r)
812 		return r;
813 
814 	memset(&params, 0, sizeof(params));
815 	params.adev = adev;
816 	params.ib = &job->ibs[0];
817 
818 	/* walk over the address space and update the directory */
819 	for (pt_idx = 0; pt_idx <= parent->last_entry_used; ++pt_idx) {
820 		struct amdgpu_bo *bo = parent->entries[pt_idx].bo;
821 		uint64_t pde, pt;
822 
823 		if (bo == NULL)
824 			continue;
825 
826 		if (bo->shadow) {
827 			struct amdgpu_bo *pt_shadow = bo->shadow;
828 
829 			r = amdgpu_ttm_bind(&pt_shadow->tbo,
830 					    &pt_shadow->tbo.mem);
831 			if (r)
832 				return r;
833 		}
834 
835 		pt = amdgpu_bo_gpu_offset(bo);
836 		if (parent->entries[pt_idx].addr == pt)
837 			continue;
838 
839 		parent->entries[pt_idx].addr = pt;
840 
841 		pde = pd_addr + pt_idx * 8;
842 		if (((last_pde + 8 * count) != pde) ||
843 		    ((last_pt + incr * count) != pt) ||
844 		    (count == AMDGPU_VM_MAX_UPDATE_SIZE)) {
845 
846 			if (count) {
847 				uint64_t pt_addr =
848 					amdgpu_vm_adjust_mc_addr(adev, last_pt);
849 
850 				if (shadow)
851 					amdgpu_vm_do_set_ptes(&params,
852 							      last_shadow,
853 							      pt_addr, count,
854 							      incr,
855 							      AMDGPU_PTE_VALID);
856 
857 				amdgpu_vm_do_set_ptes(&params, last_pde,
858 						      pt_addr, count, incr,
859 						      AMDGPU_PTE_VALID);
860 			}
861 
862 			count = 1;
863 			last_pde = pde;
864 			last_shadow = shadow_addr + pt_idx * 8;
865 			last_pt = pt;
866 		} else {
867 			++count;
868 		}
869 	}
870 
871 	if (count) {
872 		uint64_t pt_addr = amdgpu_vm_adjust_mc_addr(adev, last_pt);
873 
874 		if (vm->root.bo->shadow)
875 			amdgpu_vm_do_set_ptes(&params, last_shadow, pt_addr,
876 					      count, incr, AMDGPU_PTE_VALID);
877 
878 		amdgpu_vm_do_set_ptes(&params, last_pde, pt_addr,
879 				      count, incr, AMDGPU_PTE_VALID);
880 	}
881 
882 	if (params.ib->length_dw == 0) {
883 		amdgpu_job_free(job);
884 	} else {
885 		amdgpu_ring_pad_ib(ring, params.ib);
886 		amdgpu_sync_resv(adev, &job->sync, parent->bo->tbo.resv,
887 				 AMDGPU_FENCE_OWNER_VM);
888 		if (shadow)
889 			amdgpu_sync_resv(adev, &job->sync, shadow->tbo.resv,
890 					 AMDGPU_FENCE_OWNER_VM);
891 
892 		WARN_ON(params.ib->length_dw > ndw);
893 		r = amdgpu_job_submit(job, ring, &vm->entity,
894 				AMDGPU_FENCE_OWNER_VM, &fence);
895 		if (r)
896 			goto error_free;
897 
898 		amdgpu_bo_fence(parent->bo, fence, true);
899 		dma_fence_put(vm->last_dir_update);
900 		vm->last_dir_update = dma_fence_get(fence);
901 		dma_fence_put(fence);
902 	}
903 	/*
904 	 * Recurse into the subdirectories. This recursion is harmless because
905 	 * we only have a maximum of 5 layers.
906 	 */
907 	for (pt_idx = 0; pt_idx <= parent->last_entry_used; ++pt_idx) {
908 		struct amdgpu_vm_pt *entry = &parent->entries[pt_idx];
909 
910 		if (!entry->bo)
911 			continue;
912 
913 		r = amdgpu_vm_update_level(adev, vm, entry, level + 1);
914 		if (r)
915 			return r;
916 	}
917 
918 	return 0;
919 
920 error_free:
921 	amdgpu_job_free(job);
922 	return r;
923 }
924 
925 /*
926  * amdgpu_vm_update_directories - make sure that all directories are valid
927  *
928  * @adev: amdgpu_device pointer
929  * @vm: requested vm
930  *
931  * Makes sure all directories are up to date.
932  * Returns 0 for success, error for failure.
933  */
934 int amdgpu_vm_update_directories(struct amdgpu_device *adev,
935 				 struct amdgpu_vm *vm)
936 {
937 	return amdgpu_vm_update_level(adev, vm, &vm->root, 0);
938 }
939 
940 /**
941  * amdgpu_vm_find_pt - find the page table for an address
942  *
943  * @p: see amdgpu_pte_update_params definition
944  * @addr: virtual address in question
945  *
946  * Find the page table BO for a virtual address, return NULL when none found.
947  */
948 static struct amdgpu_bo *amdgpu_vm_get_pt(struct amdgpu_pte_update_params *p,
949 					  uint64_t addr)
950 {
951 	struct amdgpu_vm_pt *entry = &p->vm->root;
952 	unsigned idx, level = p->adev->vm_manager.num_level;
953 
954 	while (entry->entries) {
955 		idx = addr >> (amdgpu_vm_block_size * level--);
956 		idx %= amdgpu_bo_size(entry->bo) / 8;
957 		entry = &entry->entries[idx];
958 	}
959 
960 	if (level)
961 		return NULL;
962 
963 	return entry->bo;
964 }
965 
966 /**
967  * amdgpu_vm_update_ptes - make sure that page tables are valid
968  *
969  * @params: see amdgpu_pte_update_params definition
970  * @vm: requested vm
971  * @start: start of GPU address range
972  * @end: end of GPU address range
973  * @dst: destination address to map to, the next dst inside the function
974  * @flags: mapping flags
975  *
976  * Update the page tables in the range @start - @end.
977  */
978 static void amdgpu_vm_update_ptes(struct amdgpu_pte_update_params *params,
979 				  uint64_t start, uint64_t end,
980 				  uint64_t dst, uint64_t flags)
981 {
982 	const uint64_t mask = AMDGPU_VM_PTE_COUNT - 1;
983 
984 	uint64_t cur_pe_start, cur_nptes, cur_dst;
985 	uint64_t addr; /* next GPU address to be updated */
986 	struct amdgpu_bo *pt;
987 	unsigned nptes; /* next number of ptes to be updated */
988 	uint64_t next_pe_start;
989 
990 	/* initialize the variables */
991 	addr = start;
992 	pt = amdgpu_vm_get_pt(params, addr);
993 	if (!pt)
994 		return;
995 
996 	if (params->shadow) {
997 		if (!pt->shadow)
998 			return;
999 		pt = pt->shadow;
1000 	}
1001 	if ((addr & ~mask) == (end & ~mask))
1002 		nptes = end - addr;
1003 	else
1004 		nptes = AMDGPU_VM_PTE_COUNT - (addr & mask);
1005 
1006 	cur_pe_start = amdgpu_bo_gpu_offset(pt);
1007 	cur_pe_start += (addr & mask) * 8;
1008 	cur_nptes = nptes;
1009 	cur_dst = dst;
1010 
1011 	/* for next ptb*/
1012 	addr += nptes;
1013 	dst += nptes * AMDGPU_GPU_PAGE_SIZE;
1014 
1015 	/* walk over the address space and update the page tables */
1016 	while (addr < end) {
1017 		pt = amdgpu_vm_get_pt(params, addr);
1018 		if (!pt)
1019 			return;
1020 
1021 		if (params->shadow) {
1022 			if (!pt->shadow)
1023 				return;
1024 			pt = pt->shadow;
1025 		}
1026 
1027 		if ((addr & ~mask) == (end & ~mask))
1028 			nptes = end - addr;
1029 		else
1030 			nptes = AMDGPU_VM_PTE_COUNT - (addr & mask);
1031 
1032 		next_pe_start = amdgpu_bo_gpu_offset(pt);
1033 		next_pe_start += (addr & mask) * 8;
1034 
1035 		if ((cur_pe_start + 8 * cur_nptes) == next_pe_start &&
1036 		    ((cur_nptes + nptes) <= AMDGPU_VM_MAX_UPDATE_SIZE)) {
1037 			/* The next ptb is consecutive to current ptb.
1038 			 * Don't call the update function now.
1039 			 * Will update two ptbs together in future.
1040 			*/
1041 			cur_nptes += nptes;
1042 		} else {
1043 			params->func(params, cur_pe_start, cur_dst, cur_nptes,
1044 				     AMDGPU_GPU_PAGE_SIZE, flags);
1045 
1046 			cur_pe_start = next_pe_start;
1047 			cur_nptes = nptes;
1048 			cur_dst = dst;
1049 		}
1050 
1051 		/* for next ptb*/
1052 		addr += nptes;
1053 		dst += nptes * AMDGPU_GPU_PAGE_SIZE;
1054 	}
1055 
1056 	params->func(params, cur_pe_start, cur_dst, cur_nptes,
1057 		     AMDGPU_GPU_PAGE_SIZE, flags);
1058 }
1059 
1060 /*
1061  * amdgpu_vm_frag_ptes - add fragment information to PTEs
1062  *
1063  * @params: see amdgpu_pte_update_params definition
1064  * @vm: requested vm
1065  * @start: first PTE to handle
1066  * @end: last PTE to handle
1067  * @dst: addr those PTEs should point to
1068  * @flags: hw mapping flags
1069  */
1070 static void amdgpu_vm_frag_ptes(struct amdgpu_pte_update_params	*params,
1071 				uint64_t start, uint64_t end,
1072 				uint64_t dst, uint64_t flags)
1073 {
1074 	/**
1075 	 * The MC L1 TLB supports variable sized pages, based on a fragment
1076 	 * field in the PTE. When this field is set to a non-zero value, page
1077 	 * granularity is increased from 4KB to (1 << (12 + frag)). The PTE
1078 	 * flags are considered valid for all PTEs within the fragment range
1079 	 * and corresponding mappings are assumed to be physically contiguous.
1080 	 *
1081 	 * The L1 TLB can store a single PTE for the whole fragment,
1082 	 * significantly increasing the space available for translation
1083 	 * caching. This leads to large improvements in throughput when the
1084 	 * TLB is under pressure.
1085 	 *
1086 	 * The L2 TLB distributes small and large fragments into two
1087 	 * asymmetric partitions. The large fragment cache is significantly
1088 	 * larger. Thus, we try to use large fragments wherever possible.
1089 	 * Userspace can support this by aligning virtual base address and
1090 	 * allocation size to the fragment size.
1091 	 */
1092 
1093 	/* SI and newer are optimized for 64KB */
1094 	uint64_t frag_flags = AMDGPU_PTE_FRAG(AMDGPU_LOG2_PAGES_PER_FRAG);
1095 	uint64_t frag_align = 1 << AMDGPU_LOG2_PAGES_PER_FRAG;
1096 
1097 	uint64_t frag_start = ALIGN(start, frag_align);
1098 	uint64_t frag_end = end & ~(frag_align - 1);
1099 
1100 	/* system pages are non continuously */
1101 	if (params->src || !(flags & AMDGPU_PTE_VALID) ||
1102 	    (frag_start >= frag_end)) {
1103 
1104 		amdgpu_vm_update_ptes(params, start, end, dst, flags);
1105 		return;
1106 	}
1107 
1108 	/* handle the 4K area at the beginning */
1109 	if (start != frag_start) {
1110 		amdgpu_vm_update_ptes(params, start, frag_start,
1111 				      dst, flags);
1112 		dst += (frag_start - start) * AMDGPU_GPU_PAGE_SIZE;
1113 	}
1114 
1115 	/* handle the area in the middle */
1116 	amdgpu_vm_update_ptes(params, frag_start, frag_end, dst,
1117 			      flags | frag_flags);
1118 
1119 	/* handle the 4K area at the end */
1120 	if (frag_end != end) {
1121 		dst += (frag_end - frag_start) * AMDGPU_GPU_PAGE_SIZE;
1122 		amdgpu_vm_update_ptes(params, frag_end, end, dst, flags);
1123 	}
1124 }
1125 
1126 /**
1127  * amdgpu_vm_bo_update_mapping - update a mapping in the vm page table
1128  *
1129  * @adev: amdgpu_device pointer
1130  * @exclusive: fence we need to sync to
1131  * @src: address where to copy page table entries from
1132  * @pages_addr: DMA addresses to use for mapping
1133  * @vm: requested vm
1134  * @start: start of mapped range
1135  * @last: last mapped entry
1136  * @flags: flags for the entries
1137  * @addr: addr to set the area to
1138  * @fence: optional resulting fence
1139  *
1140  * Fill in the page table entries between @start and @last.
1141  * Returns 0 for success, -EINVAL for failure.
1142  */
1143 static int amdgpu_vm_bo_update_mapping(struct amdgpu_device *adev,
1144 				       struct dma_fence *exclusive,
1145 				       uint64_t src,
1146 				       dma_addr_t *pages_addr,
1147 				       struct amdgpu_vm *vm,
1148 				       uint64_t start, uint64_t last,
1149 				       uint64_t flags, uint64_t addr,
1150 				       struct dma_fence **fence)
1151 {
1152 	struct amdgpu_ring *ring;
1153 	void *owner = AMDGPU_FENCE_OWNER_VM;
1154 	unsigned nptes, ncmds, ndw;
1155 	struct amdgpu_job *job;
1156 	struct amdgpu_pte_update_params params;
1157 	struct dma_fence *f = NULL;
1158 	int r;
1159 
1160 	memset(&params, 0, sizeof(params));
1161 	params.adev = adev;
1162 	params.vm = vm;
1163 	params.src = src;
1164 
1165 	ring = container_of(vm->entity.sched, struct amdgpu_ring, sched);
1166 
1167 	/* sync to everything on unmapping */
1168 	if (!(flags & AMDGPU_PTE_VALID))
1169 		owner = AMDGPU_FENCE_OWNER_UNDEFINED;
1170 
1171 	nptes = last - start + 1;
1172 
1173 	/*
1174 	 * reserve space for one command every (1 << BLOCK_SIZE)
1175 	 *  entries or 2k dwords (whatever is smaller)
1176 	 */
1177 	ncmds = (nptes >> min(amdgpu_vm_block_size, 11)) + 1;
1178 
1179 	/* padding, etc. */
1180 	ndw = 64;
1181 
1182 	if (src) {
1183 		/* only copy commands needed */
1184 		ndw += ncmds * 7;
1185 
1186 		params.func = amdgpu_vm_do_copy_ptes;
1187 
1188 	} else if (pages_addr) {
1189 		/* copy commands needed */
1190 		ndw += ncmds * 7;
1191 
1192 		/* and also PTEs */
1193 		ndw += nptes * 2;
1194 
1195 		params.func = amdgpu_vm_do_copy_ptes;
1196 
1197 	} else {
1198 		/* set page commands needed */
1199 		ndw += ncmds * 10;
1200 
1201 		/* two extra commands for begin/end of fragment */
1202 		ndw += 2 * 10;
1203 
1204 		params.func = amdgpu_vm_do_set_ptes;
1205 	}
1206 
1207 	r = amdgpu_job_alloc_with_ib(adev, ndw * 4, &job);
1208 	if (r)
1209 		return r;
1210 
1211 	params.ib = &job->ibs[0];
1212 
1213 	if (!src && pages_addr) {
1214 		uint64_t *pte;
1215 		unsigned i;
1216 
1217 		/* Put the PTEs at the end of the IB. */
1218 		i = ndw - nptes * 2;
1219 		pte= (uint64_t *)&(job->ibs->ptr[i]);
1220 		params.src = job->ibs->gpu_addr + i * 4;
1221 
1222 		for (i = 0; i < nptes; ++i) {
1223 			pte[i] = amdgpu_vm_map_gart(pages_addr, addr + i *
1224 						    AMDGPU_GPU_PAGE_SIZE);
1225 			pte[i] |= flags;
1226 		}
1227 		addr = 0;
1228 	}
1229 
1230 	r = amdgpu_sync_fence(adev, &job->sync, exclusive);
1231 	if (r)
1232 		goto error_free;
1233 
1234 	r = amdgpu_sync_resv(adev, &job->sync, vm->root.bo->tbo.resv,
1235 			     owner);
1236 	if (r)
1237 		goto error_free;
1238 
1239 	r = reservation_object_reserve_shared(vm->root.bo->tbo.resv);
1240 	if (r)
1241 		goto error_free;
1242 
1243 	params.shadow = true;
1244 	amdgpu_vm_frag_ptes(&params, start, last + 1, addr, flags);
1245 	params.shadow = false;
1246 	amdgpu_vm_frag_ptes(&params, start, last + 1, addr, flags);
1247 
1248 	amdgpu_ring_pad_ib(ring, params.ib);
1249 	WARN_ON(params.ib->length_dw > ndw);
1250 	r = amdgpu_job_submit(job, ring, &vm->entity,
1251 			      AMDGPU_FENCE_OWNER_VM, &f);
1252 	if (r)
1253 		goto error_free;
1254 
1255 	amdgpu_bo_fence(vm->root.bo, f, true);
1256 	dma_fence_put(*fence);
1257 	*fence = f;
1258 	return 0;
1259 
1260 error_free:
1261 	amdgpu_job_free(job);
1262 	return r;
1263 }
1264 
1265 /**
1266  * amdgpu_vm_bo_split_mapping - split a mapping into smaller chunks
1267  *
1268  * @adev: amdgpu_device pointer
1269  * @exclusive: fence we need to sync to
1270  * @gtt_flags: flags as they are used for GTT
1271  * @pages_addr: DMA addresses to use for mapping
1272  * @vm: requested vm
1273  * @mapping: mapped range and flags to use for the update
1274  * @flags: HW flags for the mapping
1275  * @nodes: array of drm_mm_nodes with the MC addresses
1276  * @fence: optional resulting fence
1277  *
1278  * Split the mapping into smaller chunks so that each update fits
1279  * into a SDMA IB.
1280  * Returns 0 for success, -EINVAL for failure.
1281  */
1282 static int amdgpu_vm_bo_split_mapping(struct amdgpu_device *adev,
1283 				      struct dma_fence *exclusive,
1284 				      uint64_t gtt_flags,
1285 				      dma_addr_t *pages_addr,
1286 				      struct amdgpu_vm *vm,
1287 				      struct amdgpu_bo_va_mapping *mapping,
1288 				      uint64_t flags,
1289 				      struct drm_mm_node *nodes,
1290 				      struct dma_fence **fence)
1291 {
1292 	uint64_t pfn, src = 0, start = mapping->it.start;
1293 	int r;
1294 
1295 	/* normally,bo_va->flags only contians READABLE and WIRTEABLE bit go here
1296 	 * but in case of something, we filter the flags in first place
1297 	 */
1298 	if (!(mapping->flags & AMDGPU_PTE_READABLE))
1299 		flags &= ~AMDGPU_PTE_READABLE;
1300 	if (!(mapping->flags & AMDGPU_PTE_WRITEABLE))
1301 		flags &= ~AMDGPU_PTE_WRITEABLE;
1302 
1303 	flags &= ~AMDGPU_PTE_EXECUTABLE;
1304 	flags |= mapping->flags & AMDGPU_PTE_EXECUTABLE;
1305 
1306 	flags &= ~AMDGPU_PTE_MTYPE_MASK;
1307 	flags |= (mapping->flags & AMDGPU_PTE_MTYPE_MASK);
1308 
1309 	trace_amdgpu_vm_bo_update(mapping);
1310 
1311 	pfn = mapping->offset >> PAGE_SHIFT;
1312 	if (nodes) {
1313 		while (pfn >= nodes->size) {
1314 			pfn -= nodes->size;
1315 			++nodes;
1316 		}
1317 	}
1318 
1319 	do {
1320 		uint64_t max_entries;
1321 		uint64_t addr, last;
1322 
1323 		if (nodes) {
1324 			addr = nodes->start << PAGE_SHIFT;
1325 			max_entries = (nodes->size - pfn) *
1326 				(PAGE_SIZE / AMDGPU_GPU_PAGE_SIZE);
1327 		} else {
1328 			addr = 0;
1329 			max_entries = S64_MAX;
1330 		}
1331 
1332 		if (pages_addr) {
1333 			if (flags == gtt_flags)
1334 				src = adev->gart.table_addr +
1335 					(addr >> AMDGPU_GPU_PAGE_SHIFT) * 8;
1336 			else
1337 				max_entries = min(max_entries, 16ull * 1024ull);
1338 			addr = 0;
1339 		} else if (flags & AMDGPU_PTE_VALID) {
1340 			addr += adev->vm_manager.vram_base_offset;
1341 		}
1342 		addr += pfn << PAGE_SHIFT;
1343 
1344 		last = min((uint64_t)mapping->it.last, start + max_entries - 1);
1345 		r = amdgpu_vm_bo_update_mapping(adev, exclusive,
1346 						src, pages_addr, vm,
1347 						start, last, flags, addr,
1348 						fence);
1349 		if (r)
1350 			return r;
1351 
1352 		pfn += last - start + 1;
1353 		if (nodes && nodes->size == pfn) {
1354 			pfn = 0;
1355 			++nodes;
1356 		}
1357 		start = last + 1;
1358 
1359 	} while (unlikely(start != mapping->it.last + 1));
1360 
1361 	return 0;
1362 }
1363 
1364 /**
1365  * amdgpu_vm_bo_update - update all BO mappings in the vm page table
1366  *
1367  * @adev: amdgpu_device pointer
1368  * @bo_va: requested BO and VM object
1369  * @clear: if true clear the entries
1370  *
1371  * Fill in the page table entries for @bo_va.
1372  * Returns 0 for success, -EINVAL for failure.
1373  */
1374 int amdgpu_vm_bo_update(struct amdgpu_device *adev,
1375 			struct amdgpu_bo_va *bo_va,
1376 			bool clear)
1377 {
1378 	struct amdgpu_vm *vm = bo_va->vm;
1379 	struct amdgpu_bo_va_mapping *mapping;
1380 	dma_addr_t *pages_addr = NULL;
1381 	uint64_t gtt_flags, flags;
1382 	struct ttm_mem_reg *mem;
1383 	struct drm_mm_node *nodes;
1384 	struct dma_fence *exclusive;
1385 	int r;
1386 
1387 	if (clear || !bo_va->bo) {
1388 		mem = NULL;
1389 		nodes = NULL;
1390 		exclusive = NULL;
1391 	} else {
1392 		struct ttm_dma_tt *ttm;
1393 
1394 		mem = &bo_va->bo->tbo.mem;
1395 		nodes = mem->mm_node;
1396 		if (mem->mem_type == TTM_PL_TT) {
1397 			ttm = container_of(bo_va->bo->tbo.ttm, struct
1398 					   ttm_dma_tt, ttm);
1399 			pages_addr = ttm->dma_address;
1400 		}
1401 		exclusive = reservation_object_get_excl(bo_va->bo->tbo.resv);
1402 	}
1403 
1404 	if (bo_va->bo) {
1405 		flags = amdgpu_ttm_tt_pte_flags(adev, bo_va->bo->tbo.ttm, mem);
1406 		gtt_flags = (amdgpu_ttm_is_bound(bo_va->bo->tbo.ttm) &&
1407 			adev == amdgpu_ttm_adev(bo_va->bo->tbo.bdev)) ?
1408 			flags : 0;
1409 	} else {
1410 		flags = 0x0;
1411 		gtt_flags = ~0x0;
1412 	}
1413 
1414 	spin_lock(&vm->status_lock);
1415 	if (!list_empty(&bo_va->vm_status))
1416 		list_splice_init(&bo_va->valids, &bo_va->invalids);
1417 	spin_unlock(&vm->status_lock);
1418 
1419 	list_for_each_entry(mapping, &bo_va->invalids, list) {
1420 		r = amdgpu_vm_bo_split_mapping(adev, exclusive,
1421 					       gtt_flags, pages_addr, vm,
1422 					       mapping, flags, nodes,
1423 					       &bo_va->last_pt_update);
1424 		if (r)
1425 			return r;
1426 	}
1427 
1428 	if (trace_amdgpu_vm_bo_mapping_enabled()) {
1429 		list_for_each_entry(mapping, &bo_va->valids, list)
1430 			trace_amdgpu_vm_bo_mapping(mapping);
1431 
1432 		list_for_each_entry(mapping, &bo_va->invalids, list)
1433 			trace_amdgpu_vm_bo_mapping(mapping);
1434 	}
1435 
1436 	spin_lock(&vm->status_lock);
1437 	list_splice_init(&bo_va->invalids, &bo_va->valids);
1438 	list_del_init(&bo_va->vm_status);
1439 	if (clear)
1440 		list_add(&bo_va->vm_status, &vm->cleared);
1441 	spin_unlock(&vm->status_lock);
1442 
1443 	return 0;
1444 }
1445 
1446 /**
1447  * amdgpu_vm_update_prt_state - update the global PRT state
1448  */
1449 static void amdgpu_vm_update_prt_state(struct amdgpu_device *adev)
1450 {
1451 	unsigned long flags;
1452 	bool enable;
1453 
1454 	spin_lock_irqsave(&adev->vm_manager.prt_lock, flags);
1455 	enable = !!atomic_read(&adev->vm_manager.num_prt_users);
1456 	adev->gart.gart_funcs->set_prt(adev, enable);
1457 	spin_unlock_irqrestore(&adev->vm_manager.prt_lock, flags);
1458 }
1459 
1460 /**
1461  * amdgpu_vm_prt_get - add a PRT user
1462  */
1463 static void amdgpu_vm_prt_get(struct amdgpu_device *adev)
1464 {
1465 	if (!adev->gart.gart_funcs->set_prt)
1466 		return;
1467 
1468 	if (atomic_inc_return(&adev->vm_manager.num_prt_users) == 1)
1469 		amdgpu_vm_update_prt_state(adev);
1470 }
1471 
1472 /**
1473  * amdgpu_vm_prt_put - drop a PRT user
1474  */
1475 static void amdgpu_vm_prt_put(struct amdgpu_device *adev)
1476 {
1477 	if (atomic_dec_return(&adev->vm_manager.num_prt_users) == 0)
1478 		amdgpu_vm_update_prt_state(adev);
1479 }
1480 
1481 /**
1482  * amdgpu_vm_prt_cb - callback for updating the PRT status
1483  */
1484 static void amdgpu_vm_prt_cb(struct dma_fence *fence, struct dma_fence_cb *_cb)
1485 {
1486 	struct amdgpu_prt_cb *cb = container_of(_cb, struct amdgpu_prt_cb, cb);
1487 
1488 	amdgpu_vm_prt_put(cb->adev);
1489 	kfree(cb);
1490 }
1491 
1492 /**
1493  * amdgpu_vm_add_prt_cb - add callback for updating the PRT status
1494  */
1495 static void amdgpu_vm_add_prt_cb(struct amdgpu_device *adev,
1496 				 struct dma_fence *fence)
1497 {
1498 	struct amdgpu_prt_cb *cb;
1499 
1500 	if (!adev->gart.gart_funcs->set_prt)
1501 		return;
1502 
1503 	cb = kmalloc(sizeof(struct amdgpu_prt_cb), GFP_KERNEL);
1504 	if (!cb) {
1505 		/* Last resort when we are OOM */
1506 		if (fence)
1507 			dma_fence_wait(fence, false);
1508 
1509 		amdgpu_vm_prt_put(cb->adev);
1510 	} else {
1511 		cb->adev = adev;
1512 		if (!fence || dma_fence_add_callback(fence, &cb->cb,
1513 						     amdgpu_vm_prt_cb))
1514 			amdgpu_vm_prt_cb(fence, &cb->cb);
1515 	}
1516 }
1517 
1518 /**
1519  * amdgpu_vm_free_mapping - free a mapping
1520  *
1521  * @adev: amdgpu_device pointer
1522  * @vm: requested vm
1523  * @mapping: mapping to be freed
1524  * @fence: fence of the unmap operation
1525  *
1526  * Free a mapping and make sure we decrease the PRT usage count if applicable.
1527  */
1528 static void amdgpu_vm_free_mapping(struct amdgpu_device *adev,
1529 				   struct amdgpu_vm *vm,
1530 				   struct amdgpu_bo_va_mapping *mapping,
1531 				   struct dma_fence *fence)
1532 {
1533 	if (mapping->flags & AMDGPU_PTE_PRT)
1534 		amdgpu_vm_add_prt_cb(adev, fence);
1535 	kfree(mapping);
1536 }
1537 
1538 /**
1539  * amdgpu_vm_prt_fini - finish all prt mappings
1540  *
1541  * @adev: amdgpu_device pointer
1542  * @vm: requested vm
1543  *
1544  * Register a cleanup callback to disable PRT support after VM dies.
1545  */
1546 static void amdgpu_vm_prt_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
1547 {
1548 	struct reservation_object *resv = vm->root.bo->tbo.resv;
1549 	struct dma_fence *excl, **shared;
1550 	unsigned i, shared_count;
1551 	int r;
1552 
1553 	r = reservation_object_get_fences_rcu(resv, &excl,
1554 					      &shared_count, &shared);
1555 	if (r) {
1556 		/* Not enough memory to grab the fence list, as last resort
1557 		 * block for all the fences to complete.
1558 		 */
1559 		reservation_object_wait_timeout_rcu(resv, true, false,
1560 						    MAX_SCHEDULE_TIMEOUT);
1561 		return;
1562 	}
1563 
1564 	/* Add a callback for each fence in the reservation object */
1565 	amdgpu_vm_prt_get(adev);
1566 	amdgpu_vm_add_prt_cb(adev, excl);
1567 
1568 	for (i = 0; i < shared_count; ++i) {
1569 		amdgpu_vm_prt_get(adev);
1570 		amdgpu_vm_add_prt_cb(adev, shared[i]);
1571 	}
1572 
1573 	kfree(shared);
1574 }
1575 
1576 /**
1577  * amdgpu_vm_clear_freed - clear freed BOs in the PT
1578  *
1579  * @adev: amdgpu_device pointer
1580  * @vm: requested vm
1581  * @fence: optional resulting fence (unchanged if no work needed to be done
1582  * or if an error occurred)
1583  *
1584  * Make sure all freed BOs are cleared in the PT.
1585  * Returns 0 for success.
1586  *
1587  * PTs have to be reserved and mutex must be locked!
1588  */
1589 int amdgpu_vm_clear_freed(struct amdgpu_device *adev,
1590 			  struct amdgpu_vm *vm,
1591 			  struct dma_fence **fence)
1592 {
1593 	struct amdgpu_bo_va_mapping *mapping;
1594 	struct dma_fence *f = NULL;
1595 	int r;
1596 
1597 	while (!list_empty(&vm->freed)) {
1598 		mapping = list_first_entry(&vm->freed,
1599 			struct amdgpu_bo_va_mapping, list);
1600 		list_del(&mapping->list);
1601 
1602 		r = amdgpu_vm_bo_split_mapping(adev, NULL, 0, NULL, vm, mapping,
1603 					       0, 0, &f);
1604 		amdgpu_vm_free_mapping(adev, vm, mapping, f);
1605 		if (r) {
1606 			dma_fence_put(f);
1607 			return r;
1608 		}
1609 	}
1610 
1611 	if (fence && f) {
1612 		dma_fence_put(*fence);
1613 		*fence = f;
1614 	} else {
1615 		dma_fence_put(f);
1616 	}
1617 
1618 	return 0;
1619 
1620 }
1621 
1622 /**
1623  * amdgpu_vm_clear_invalids - clear invalidated BOs in the PT
1624  *
1625  * @adev: amdgpu_device pointer
1626  * @vm: requested vm
1627  *
1628  * Make sure all invalidated BOs are cleared in the PT.
1629  * Returns 0 for success.
1630  *
1631  * PTs have to be reserved and mutex must be locked!
1632  */
1633 int amdgpu_vm_clear_invalids(struct amdgpu_device *adev,
1634 			     struct amdgpu_vm *vm, struct amdgpu_sync *sync)
1635 {
1636 	struct amdgpu_bo_va *bo_va = NULL;
1637 	int r = 0;
1638 
1639 	spin_lock(&vm->status_lock);
1640 	while (!list_empty(&vm->invalidated)) {
1641 		bo_va = list_first_entry(&vm->invalidated,
1642 			struct amdgpu_bo_va, vm_status);
1643 		spin_unlock(&vm->status_lock);
1644 
1645 		r = amdgpu_vm_bo_update(adev, bo_va, true);
1646 		if (r)
1647 			return r;
1648 
1649 		spin_lock(&vm->status_lock);
1650 	}
1651 	spin_unlock(&vm->status_lock);
1652 
1653 	if (bo_va)
1654 		r = amdgpu_sync_fence(adev, sync, bo_va->last_pt_update);
1655 
1656 	return r;
1657 }
1658 
1659 /**
1660  * amdgpu_vm_bo_add - add a bo to a specific vm
1661  *
1662  * @adev: amdgpu_device pointer
1663  * @vm: requested vm
1664  * @bo: amdgpu buffer object
1665  *
1666  * Add @bo into the requested vm.
1667  * Add @bo to the list of bos associated with the vm
1668  * Returns newly added bo_va or NULL for failure
1669  *
1670  * Object has to be reserved!
1671  */
1672 struct amdgpu_bo_va *amdgpu_vm_bo_add(struct amdgpu_device *adev,
1673 				      struct amdgpu_vm *vm,
1674 				      struct amdgpu_bo *bo)
1675 {
1676 	struct amdgpu_bo_va *bo_va;
1677 
1678 	bo_va = kzalloc(sizeof(struct amdgpu_bo_va), GFP_KERNEL);
1679 	if (bo_va == NULL) {
1680 		return NULL;
1681 	}
1682 	bo_va->vm = vm;
1683 	bo_va->bo = bo;
1684 	bo_va->ref_count = 1;
1685 	INIT_LIST_HEAD(&bo_va->bo_list);
1686 	INIT_LIST_HEAD(&bo_va->valids);
1687 	INIT_LIST_HEAD(&bo_va->invalids);
1688 	INIT_LIST_HEAD(&bo_va->vm_status);
1689 
1690 	if (bo)
1691 		list_add_tail(&bo_va->bo_list, &bo->va);
1692 
1693 	return bo_va;
1694 }
1695 
1696 /**
1697  * amdgpu_vm_bo_map - map bo inside a vm
1698  *
1699  * @adev: amdgpu_device pointer
1700  * @bo_va: bo_va to store the address
1701  * @saddr: where to map the BO
1702  * @offset: requested offset in the BO
1703  * @flags: attributes of pages (read/write/valid/etc.)
1704  *
1705  * Add a mapping of the BO at the specefied addr into the VM.
1706  * Returns 0 for success, error for failure.
1707  *
1708  * Object has to be reserved and unreserved outside!
1709  */
1710 int amdgpu_vm_bo_map(struct amdgpu_device *adev,
1711 		     struct amdgpu_bo_va *bo_va,
1712 		     uint64_t saddr, uint64_t offset,
1713 		     uint64_t size, uint64_t flags)
1714 {
1715 	struct amdgpu_bo_va_mapping *mapping;
1716 	struct amdgpu_vm *vm = bo_va->vm;
1717 	struct interval_tree_node *it;
1718 	uint64_t eaddr;
1719 
1720 	/* validate the parameters */
1721 	if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1722 	    size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1723 		return -EINVAL;
1724 
1725 	/* make sure object fit at this offset */
1726 	eaddr = saddr + size - 1;
1727 	if (saddr >= eaddr ||
1728 	    (bo_va->bo && offset + size > amdgpu_bo_size(bo_va->bo)))
1729 		return -EINVAL;
1730 
1731 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1732 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
1733 
1734 	it = interval_tree_iter_first(&vm->va, saddr, eaddr);
1735 	if (it) {
1736 		struct amdgpu_bo_va_mapping *tmp;
1737 		tmp = container_of(it, struct amdgpu_bo_va_mapping, it);
1738 		/* bo and tmp overlap, invalid addr */
1739 		dev_err(adev->dev, "bo %p va 0x%010Lx-0x%010Lx conflict with "
1740 			"0x%010lx-0x%010lx\n", bo_va->bo, saddr, eaddr,
1741 			tmp->it.start, tmp->it.last + 1);
1742 		return -EINVAL;
1743 	}
1744 
1745 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1746 	if (!mapping)
1747 		return -ENOMEM;
1748 
1749 	INIT_LIST_HEAD(&mapping->list);
1750 	mapping->it.start = saddr;
1751 	mapping->it.last = eaddr;
1752 	mapping->offset = offset;
1753 	mapping->flags = flags;
1754 
1755 	list_add(&mapping->list, &bo_va->invalids);
1756 	interval_tree_insert(&mapping->it, &vm->va);
1757 
1758 	if (flags & AMDGPU_PTE_PRT)
1759 		amdgpu_vm_prt_get(adev);
1760 
1761 	return 0;
1762 }
1763 
1764 /**
1765  * amdgpu_vm_bo_replace_map - map bo inside a vm, replacing existing mappings
1766  *
1767  * @adev: amdgpu_device pointer
1768  * @bo_va: bo_va to store the address
1769  * @saddr: where to map the BO
1770  * @offset: requested offset in the BO
1771  * @flags: attributes of pages (read/write/valid/etc.)
1772  *
1773  * Add a mapping of the BO at the specefied addr into the VM. Replace existing
1774  * mappings as we do so.
1775  * Returns 0 for success, error for failure.
1776  *
1777  * Object has to be reserved and unreserved outside!
1778  */
1779 int amdgpu_vm_bo_replace_map(struct amdgpu_device *adev,
1780 			     struct amdgpu_bo_va *bo_va,
1781 			     uint64_t saddr, uint64_t offset,
1782 			     uint64_t size, uint64_t flags)
1783 {
1784 	struct amdgpu_bo_va_mapping *mapping;
1785 	struct amdgpu_vm *vm = bo_va->vm;
1786 	uint64_t eaddr;
1787 	int r;
1788 
1789 	/* validate the parameters */
1790 	if (saddr & AMDGPU_GPU_PAGE_MASK || offset & AMDGPU_GPU_PAGE_MASK ||
1791 	    size == 0 || size & AMDGPU_GPU_PAGE_MASK)
1792 		return -EINVAL;
1793 
1794 	/* make sure object fit at this offset */
1795 	eaddr = saddr + size - 1;
1796 	if (saddr >= eaddr ||
1797 	    (bo_va->bo && offset + size > amdgpu_bo_size(bo_va->bo)))
1798 		return -EINVAL;
1799 
1800 	/* Allocate all the needed memory */
1801 	mapping = kmalloc(sizeof(*mapping), GFP_KERNEL);
1802 	if (!mapping)
1803 		return -ENOMEM;
1804 
1805 	r = amdgpu_vm_bo_clear_mappings(adev, bo_va->vm, saddr, size);
1806 	if (r) {
1807 		kfree(mapping);
1808 		return r;
1809 	}
1810 
1811 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1812 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
1813 
1814 	mapping->it.start = saddr;
1815 	mapping->it.last = eaddr;
1816 	mapping->offset = offset;
1817 	mapping->flags = flags;
1818 
1819 	list_add(&mapping->list, &bo_va->invalids);
1820 	interval_tree_insert(&mapping->it, &vm->va);
1821 
1822 	if (flags & AMDGPU_PTE_PRT)
1823 		amdgpu_vm_prt_get(adev);
1824 
1825 	return 0;
1826 }
1827 
1828 /**
1829  * amdgpu_vm_bo_unmap - remove bo mapping from vm
1830  *
1831  * @adev: amdgpu_device pointer
1832  * @bo_va: bo_va to remove the address from
1833  * @saddr: where to the BO is mapped
1834  *
1835  * Remove a mapping of the BO at the specefied addr from the VM.
1836  * Returns 0 for success, error for failure.
1837  *
1838  * Object has to be reserved and unreserved outside!
1839  */
1840 int amdgpu_vm_bo_unmap(struct amdgpu_device *adev,
1841 		       struct amdgpu_bo_va *bo_va,
1842 		       uint64_t saddr)
1843 {
1844 	struct amdgpu_bo_va_mapping *mapping;
1845 	struct amdgpu_vm *vm = bo_va->vm;
1846 	bool valid = true;
1847 
1848 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1849 
1850 	list_for_each_entry(mapping, &bo_va->valids, list) {
1851 		if (mapping->it.start == saddr)
1852 			break;
1853 	}
1854 
1855 	if (&mapping->list == &bo_va->valids) {
1856 		valid = false;
1857 
1858 		list_for_each_entry(mapping, &bo_va->invalids, list) {
1859 			if (mapping->it.start == saddr)
1860 				break;
1861 		}
1862 
1863 		if (&mapping->list == &bo_va->invalids)
1864 			return -ENOENT;
1865 	}
1866 
1867 	list_del(&mapping->list);
1868 	interval_tree_remove(&mapping->it, &vm->va);
1869 	trace_amdgpu_vm_bo_unmap(bo_va, mapping);
1870 
1871 	if (valid)
1872 		list_add(&mapping->list, &vm->freed);
1873 	else
1874 		amdgpu_vm_free_mapping(adev, vm, mapping,
1875 				       bo_va->last_pt_update);
1876 
1877 	return 0;
1878 }
1879 
1880 /**
1881  * amdgpu_vm_bo_clear_mappings - remove all mappings in a specific range
1882  *
1883  * @adev: amdgpu_device pointer
1884  * @vm: VM structure to use
1885  * @saddr: start of the range
1886  * @size: size of the range
1887  *
1888  * Remove all mappings in a range, split them as appropriate.
1889  * Returns 0 for success, error for failure.
1890  */
1891 int amdgpu_vm_bo_clear_mappings(struct amdgpu_device *adev,
1892 				struct amdgpu_vm *vm,
1893 				uint64_t saddr, uint64_t size)
1894 {
1895 	struct amdgpu_bo_va_mapping *before, *after, *tmp, *next;
1896 	struct interval_tree_node *it;
1897 	LIST_HEAD(removed);
1898 	uint64_t eaddr;
1899 
1900 	eaddr = saddr + size - 1;
1901 	saddr /= AMDGPU_GPU_PAGE_SIZE;
1902 	eaddr /= AMDGPU_GPU_PAGE_SIZE;
1903 
1904 	/* Allocate all the needed memory */
1905 	before = kzalloc(sizeof(*before), GFP_KERNEL);
1906 	if (!before)
1907 		return -ENOMEM;
1908 	INIT_LIST_HEAD(&before->list);
1909 
1910 	after = kzalloc(sizeof(*after), GFP_KERNEL);
1911 	if (!after) {
1912 		kfree(before);
1913 		return -ENOMEM;
1914 	}
1915 	INIT_LIST_HEAD(&after->list);
1916 
1917 	/* Now gather all removed mappings */
1918 	it = interval_tree_iter_first(&vm->va, saddr, eaddr);
1919 	while (it) {
1920 		tmp = container_of(it, struct amdgpu_bo_va_mapping, it);
1921 		it = interval_tree_iter_next(it, saddr, eaddr);
1922 
1923 		/* Remember mapping split at the start */
1924 		if (tmp->it.start < saddr) {
1925 			before->it.start = tmp->it.start;
1926 			before->it.last = saddr - 1;
1927 			before->offset = tmp->offset;
1928 			before->flags = tmp->flags;
1929 			list_add(&before->list, &tmp->list);
1930 		}
1931 
1932 		/* Remember mapping split at the end */
1933 		if (tmp->it.last > eaddr) {
1934 			after->it.start = eaddr + 1;
1935 			after->it.last = tmp->it.last;
1936 			after->offset = tmp->offset;
1937 			after->offset += after->it.start - tmp->it.start;
1938 			after->flags = tmp->flags;
1939 			list_add(&after->list, &tmp->list);
1940 		}
1941 
1942 		list_del(&tmp->list);
1943 		list_add(&tmp->list, &removed);
1944 	}
1945 
1946 	/* And free them up */
1947 	list_for_each_entry_safe(tmp, next, &removed, list) {
1948 		interval_tree_remove(&tmp->it, &vm->va);
1949 		list_del(&tmp->list);
1950 
1951 		if (tmp->it.start < saddr)
1952 		    tmp->it.start = saddr;
1953 		if (tmp->it.last > eaddr)
1954 		    tmp->it.last = eaddr;
1955 
1956 		list_add(&tmp->list, &vm->freed);
1957 		trace_amdgpu_vm_bo_unmap(NULL, tmp);
1958 	}
1959 
1960 	/* Insert partial mapping before the range */
1961 	if (!list_empty(&before->list)) {
1962 		interval_tree_insert(&before->it, &vm->va);
1963 		if (before->flags & AMDGPU_PTE_PRT)
1964 			amdgpu_vm_prt_get(adev);
1965 	} else {
1966 		kfree(before);
1967 	}
1968 
1969 	/* Insert partial mapping after the range */
1970 	if (!list_empty(&after->list)) {
1971 		interval_tree_insert(&after->it, &vm->va);
1972 		if (after->flags & AMDGPU_PTE_PRT)
1973 			amdgpu_vm_prt_get(adev);
1974 	} else {
1975 		kfree(after);
1976 	}
1977 
1978 	return 0;
1979 }
1980 
1981 /**
1982  * amdgpu_vm_bo_rmv - remove a bo to a specific vm
1983  *
1984  * @adev: amdgpu_device pointer
1985  * @bo_va: requested bo_va
1986  *
1987  * Remove @bo_va->bo from the requested vm.
1988  *
1989  * Object have to be reserved!
1990  */
1991 void amdgpu_vm_bo_rmv(struct amdgpu_device *adev,
1992 		      struct amdgpu_bo_va *bo_va)
1993 {
1994 	struct amdgpu_bo_va_mapping *mapping, *next;
1995 	struct amdgpu_vm *vm = bo_va->vm;
1996 
1997 	list_del(&bo_va->bo_list);
1998 
1999 	spin_lock(&vm->status_lock);
2000 	list_del(&bo_va->vm_status);
2001 	spin_unlock(&vm->status_lock);
2002 
2003 	list_for_each_entry_safe(mapping, next, &bo_va->valids, list) {
2004 		list_del(&mapping->list);
2005 		interval_tree_remove(&mapping->it, &vm->va);
2006 		trace_amdgpu_vm_bo_unmap(bo_va, mapping);
2007 		list_add(&mapping->list, &vm->freed);
2008 	}
2009 	list_for_each_entry_safe(mapping, next, &bo_va->invalids, list) {
2010 		list_del(&mapping->list);
2011 		interval_tree_remove(&mapping->it, &vm->va);
2012 		amdgpu_vm_free_mapping(adev, vm, mapping,
2013 				       bo_va->last_pt_update);
2014 	}
2015 
2016 	dma_fence_put(bo_va->last_pt_update);
2017 	kfree(bo_va);
2018 }
2019 
2020 /**
2021  * amdgpu_vm_bo_invalidate - mark the bo as invalid
2022  *
2023  * @adev: amdgpu_device pointer
2024  * @vm: requested vm
2025  * @bo: amdgpu buffer object
2026  *
2027  * Mark @bo as invalid.
2028  */
2029 void amdgpu_vm_bo_invalidate(struct amdgpu_device *adev,
2030 			     struct amdgpu_bo *bo)
2031 {
2032 	struct amdgpu_bo_va *bo_va;
2033 
2034 	list_for_each_entry(bo_va, &bo->va, bo_list) {
2035 		spin_lock(&bo_va->vm->status_lock);
2036 		if (list_empty(&bo_va->vm_status))
2037 			list_add(&bo_va->vm_status, &bo_va->vm->invalidated);
2038 		spin_unlock(&bo_va->vm->status_lock);
2039 	}
2040 }
2041 
2042 /**
2043  * amdgpu_vm_init - initialize a vm instance
2044  *
2045  * @adev: amdgpu_device pointer
2046  * @vm: requested vm
2047  *
2048  * Init @vm fields.
2049  */
2050 int amdgpu_vm_init(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2051 {
2052 	const unsigned align = min(AMDGPU_VM_PTB_ALIGN_SIZE,
2053 		AMDGPU_VM_PTE_COUNT * 8);
2054 	unsigned ring_instance;
2055 	struct amdgpu_ring *ring;
2056 	struct amd_sched_rq *rq;
2057 	int i, r;
2058 
2059 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
2060 		vm->ids[i] = NULL;
2061 	vm->va = RB_ROOT;
2062 	vm->client_id = atomic64_inc_return(&adev->vm_manager.client_counter);
2063 	spin_lock_init(&vm->status_lock);
2064 	INIT_LIST_HEAD(&vm->invalidated);
2065 	INIT_LIST_HEAD(&vm->cleared);
2066 	INIT_LIST_HEAD(&vm->freed);
2067 
2068 	/* create scheduler entity for page table updates */
2069 
2070 	ring_instance = atomic_inc_return(&adev->vm_manager.vm_pte_next_ring);
2071 	ring_instance %= adev->vm_manager.vm_pte_num_rings;
2072 	ring = adev->vm_manager.vm_pte_rings[ring_instance];
2073 	rq = &ring->sched.sched_rq[AMD_SCHED_PRIORITY_KERNEL];
2074 	r = amd_sched_entity_init(&ring->sched, &vm->entity,
2075 				  rq, amdgpu_sched_jobs);
2076 	if (r)
2077 		return r;
2078 
2079 	vm->last_dir_update = NULL;
2080 
2081 	r = amdgpu_bo_create(adev, amdgpu_vm_bo_size(adev, 0), align, true,
2082 			     AMDGPU_GEM_DOMAIN_VRAM,
2083 			     AMDGPU_GEM_CREATE_NO_CPU_ACCESS |
2084 			     AMDGPU_GEM_CREATE_SHADOW |
2085 			     AMDGPU_GEM_CREATE_VRAM_CONTIGUOUS |
2086 			     AMDGPU_GEM_CREATE_VRAM_CLEARED,
2087 			     NULL, NULL, &vm->root.bo);
2088 	if (r)
2089 		goto error_free_sched_entity;
2090 
2091 	r = amdgpu_bo_reserve(vm->root.bo, false);
2092 	if (r)
2093 		goto error_free_root;
2094 
2095 	vm->last_eviction_counter = atomic64_read(&adev->num_evictions);
2096 	amdgpu_bo_unreserve(vm->root.bo);
2097 
2098 	return 0;
2099 
2100 error_free_root:
2101 	amdgpu_bo_unref(&vm->root.bo->shadow);
2102 	amdgpu_bo_unref(&vm->root.bo);
2103 	vm->root.bo = NULL;
2104 
2105 error_free_sched_entity:
2106 	amd_sched_entity_fini(&ring->sched, &vm->entity);
2107 
2108 	return r;
2109 }
2110 
2111 /**
2112  * amdgpu_vm_free_levels - free PD/PT levels
2113  *
2114  * @level: PD/PT starting level to free
2115  *
2116  * Free the page directory or page table level and all sub levels.
2117  */
2118 static void amdgpu_vm_free_levels(struct amdgpu_vm_pt *level)
2119 {
2120 	unsigned i;
2121 
2122 	if (level->bo) {
2123 		amdgpu_bo_unref(&level->bo->shadow);
2124 		amdgpu_bo_unref(&level->bo);
2125 	}
2126 
2127 	if (level->entries)
2128 		for (i = 0; i <= level->last_entry_used; i++)
2129 			amdgpu_vm_free_levels(&level->entries[i]);
2130 
2131 	drm_free_large(level->entries);
2132 }
2133 
2134 /**
2135  * amdgpu_vm_fini - tear down a vm instance
2136  *
2137  * @adev: amdgpu_device pointer
2138  * @vm: requested vm
2139  *
2140  * Tear down @vm.
2141  * Unbind the VM and remove all bos from the vm bo list
2142  */
2143 void amdgpu_vm_fini(struct amdgpu_device *adev, struct amdgpu_vm *vm)
2144 {
2145 	struct amdgpu_bo_va_mapping *mapping, *tmp;
2146 	bool prt_fini_needed = !!adev->gart.gart_funcs->set_prt;
2147 
2148 	amd_sched_entity_fini(vm->entity.sched, &vm->entity);
2149 
2150 	if (!RB_EMPTY_ROOT(&vm->va)) {
2151 		dev_err(adev->dev, "still active bo inside vm\n");
2152 	}
2153 	rbtree_postorder_for_each_entry_safe(mapping, tmp, &vm->va, it.rb) {
2154 		list_del(&mapping->list);
2155 		interval_tree_remove(&mapping->it, &vm->va);
2156 		kfree(mapping);
2157 	}
2158 	list_for_each_entry_safe(mapping, tmp, &vm->freed, list) {
2159 		if (mapping->flags & AMDGPU_PTE_PRT && prt_fini_needed) {
2160 			amdgpu_vm_prt_fini(adev, vm);
2161 			prt_fini_needed = false;
2162 		}
2163 
2164 		list_del(&mapping->list);
2165 		amdgpu_vm_free_mapping(adev, vm, mapping, NULL);
2166 	}
2167 
2168 	amdgpu_vm_free_levels(&vm->root);
2169 	dma_fence_put(vm->last_dir_update);
2170 }
2171 
2172 /**
2173  * amdgpu_vm_manager_init - init the VM manager
2174  *
2175  * @adev: amdgpu_device pointer
2176  *
2177  * Initialize the VM manager structures
2178  */
2179 void amdgpu_vm_manager_init(struct amdgpu_device *adev)
2180 {
2181 	unsigned i;
2182 
2183 	INIT_LIST_HEAD(&adev->vm_manager.ids_lru);
2184 
2185 	/* skip over VMID 0, since it is the system VM */
2186 	for (i = 1; i < adev->vm_manager.num_ids; ++i) {
2187 		amdgpu_vm_reset_id(adev, i);
2188 		amdgpu_sync_create(&adev->vm_manager.ids[i].active);
2189 		list_add_tail(&adev->vm_manager.ids[i].list,
2190 			      &adev->vm_manager.ids_lru);
2191 	}
2192 
2193 	adev->vm_manager.fence_context =
2194 		dma_fence_context_alloc(AMDGPU_MAX_RINGS);
2195 	for (i = 0; i < AMDGPU_MAX_RINGS; ++i)
2196 		adev->vm_manager.seqno[i] = 0;
2197 
2198 	atomic_set(&adev->vm_manager.vm_pte_next_ring, 0);
2199 	atomic64_set(&adev->vm_manager.client_counter, 0);
2200 	spin_lock_init(&adev->vm_manager.prt_lock);
2201 	atomic_set(&adev->vm_manager.num_prt_users, 0);
2202 }
2203 
2204 /**
2205  * amdgpu_vm_manager_fini - cleanup VM manager
2206  *
2207  * @adev: amdgpu_device pointer
2208  *
2209  * Cleanup the VM manager and free resources.
2210  */
2211 void amdgpu_vm_manager_fini(struct amdgpu_device *adev)
2212 {
2213 	unsigned i;
2214 
2215 	for (i = 0; i < AMDGPU_NUM_VM; ++i) {
2216 		struct amdgpu_vm_id *id = &adev->vm_manager.ids[i];
2217 
2218 		dma_fence_put(adev->vm_manager.ids[i].first);
2219 		amdgpu_sync_free(&adev->vm_manager.ids[i].active);
2220 		dma_fence_put(id->flushed_updates);
2221 		dma_fence_put(id->last_flush);
2222 	}
2223 }
2224