1 /*
2  * Copyright 2014-2018 Advanced Micro Devices, Inc.
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included in
12  * all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
18  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
19  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
20  * OTHER DEALINGS IN THE SOFTWARE.
21  */
22 
23 #define pr_fmt(fmt) "kfd2kgd: " fmt
24 
25 #include <linux/list.h>
26 #include <linux/pagemap.h>
27 #include <linux/sched/mm.h>
28 #include <drm/drmP.h>
29 #include "amdgpu_object.h"
30 #include "amdgpu_vm.h"
31 #include "amdgpu_amdkfd.h"
32 
33 /* Special VM and GART address alignment needed for VI pre-Fiji due to
34  * a HW bug.
35  */
36 #define VI_BO_SIZE_ALIGN (0x8000)
37 
38 /* BO flag to indicate a KFD userptr BO */
39 #define AMDGPU_AMDKFD_USERPTR_BO (1ULL << 63)
40 
41 /* Userptr restore delay, just long enough to allow consecutive VM
42  * changes to accumulate
43  */
44 #define AMDGPU_USERPTR_RESTORE_DELAY_MS 1
45 
46 /* Impose limit on how much memory KFD can use */
47 static struct {
48 	uint64_t max_system_mem_limit;
49 	uint64_t max_ttm_mem_limit;
50 	int64_t system_mem_used;
51 	int64_t ttm_mem_used;
52 	spinlock_t mem_limit_lock;
53 } kfd_mem_limit;
54 
55 /* Struct used for amdgpu_amdkfd_bo_validate */
56 struct amdgpu_vm_parser {
57 	uint32_t        domain;
58 	bool            wait;
59 };
60 
61 static const char * const domain_bit_to_string[] = {
62 		"CPU",
63 		"GTT",
64 		"VRAM",
65 		"GDS",
66 		"GWS",
67 		"OA"
68 };
69 
70 #define domain_string(domain) domain_bit_to_string[ffs(domain)-1]
71 
72 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work);
73 
74 
75 static inline struct amdgpu_device *get_amdgpu_device(struct kgd_dev *kgd)
76 {
77 	return (struct amdgpu_device *)kgd;
78 }
79 
80 static bool check_if_add_bo_to_vm(struct amdgpu_vm *avm,
81 		struct kgd_mem *mem)
82 {
83 	struct kfd_bo_va_list *entry;
84 
85 	list_for_each_entry(entry, &mem->bo_va_list, bo_list)
86 		if (entry->bo_va->base.vm == avm)
87 			return false;
88 
89 	return true;
90 }
91 
92 /* Set memory usage limits. Current, limits are
93  *  System (TTM + userptr) memory - 3/4th System RAM
94  *  TTM memory - 3/8th System RAM
95  */
96 void amdgpu_amdkfd_gpuvm_init_mem_limits(void)
97 {
98 	struct sysinfo si;
99 	uint64_t mem;
100 
101 	si_meminfo(&si);
102 	mem = si.totalram - si.totalhigh;
103 	mem *= si.mem_unit;
104 
105 	spin_lock_init(&kfd_mem_limit.mem_limit_lock);
106 	kfd_mem_limit.max_system_mem_limit = (mem >> 1) + (mem >> 2);
107 	kfd_mem_limit.max_ttm_mem_limit = (mem >> 1) - (mem >> 3);
108 	pr_debug("Kernel memory limit %lluM, TTM limit %lluM\n",
109 		(kfd_mem_limit.max_system_mem_limit >> 20),
110 		(kfd_mem_limit.max_ttm_mem_limit >> 20));
111 }
112 
113 static int amdgpu_amdkfd_reserve_system_mem_limit(struct amdgpu_device *adev,
114 		uint64_t size, u32 domain, bool sg)
115 {
116 	size_t acc_size, system_mem_needed, ttm_mem_needed;
117 	int ret = 0;
118 
119 	acc_size = ttm_bo_dma_acc_size(&adev->mman.bdev, size,
120 				       sizeof(struct amdgpu_bo));
121 
122 	spin_lock(&kfd_mem_limit.mem_limit_lock);
123 
124 	if (domain == AMDGPU_GEM_DOMAIN_GTT) {
125 		/* TTM GTT memory */
126 		system_mem_needed = acc_size + size;
127 		ttm_mem_needed = acc_size + size;
128 	} else if (domain == AMDGPU_GEM_DOMAIN_CPU && !sg) {
129 		/* Userptr */
130 		system_mem_needed = acc_size + size;
131 		ttm_mem_needed = acc_size;
132 	} else {
133 		/* VRAM and SG */
134 		system_mem_needed = acc_size;
135 		ttm_mem_needed = acc_size;
136 	}
137 
138 	if ((kfd_mem_limit.system_mem_used + system_mem_needed >
139 		kfd_mem_limit.max_system_mem_limit) ||
140 		(kfd_mem_limit.ttm_mem_used + ttm_mem_needed >
141 		kfd_mem_limit.max_ttm_mem_limit))
142 		ret = -ENOMEM;
143 	else {
144 		kfd_mem_limit.system_mem_used += system_mem_needed;
145 		kfd_mem_limit.ttm_mem_used += ttm_mem_needed;
146 	}
147 
148 	spin_unlock(&kfd_mem_limit.mem_limit_lock);
149 	return ret;
150 }
151 
152 static void unreserve_system_mem_limit(struct amdgpu_device *adev,
153 		uint64_t size, u32 domain, bool sg)
154 {
155 	size_t acc_size;
156 
157 	acc_size = ttm_bo_dma_acc_size(&adev->mman.bdev, size,
158 				       sizeof(struct amdgpu_bo));
159 
160 	spin_lock(&kfd_mem_limit.mem_limit_lock);
161 	if (domain == AMDGPU_GEM_DOMAIN_GTT) {
162 		kfd_mem_limit.system_mem_used -= (acc_size + size);
163 		kfd_mem_limit.ttm_mem_used -= (acc_size + size);
164 	} else if (domain == AMDGPU_GEM_DOMAIN_CPU && !sg) {
165 		kfd_mem_limit.system_mem_used -= (acc_size + size);
166 		kfd_mem_limit.ttm_mem_used -= acc_size;
167 	} else {
168 		kfd_mem_limit.system_mem_used -= acc_size;
169 		kfd_mem_limit.ttm_mem_used -= acc_size;
170 	}
171 	WARN_ONCE(kfd_mem_limit.system_mem_used < 0,
172 		  "kfd system memory accounting unbalanced");
173 	WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0,
174 		  "kfd TTM memory accounting unbalanced");
175 
176 	spin_unlock(&kfd_mem_limit.mem_limit_lock);
177 }
178 
179 void amdgpu_amdkfd_unreserve_system_memory_limit(struct amdgpu_bo *bo)
180 {
181 	spin_lock(&kfd_mem_limit.mem_limit_lock);
182 
183 	if (bo->flags & AMDGPU_AMDKFD_USERPTR_BO) {
184 		kfd_mem_limit.system_mem_used -=
185 			(bo->tbo.acc_size + amdgpu_bo_size(bo));
186 		kfd_mem_limit.ttm_mem_used -= bo->tbo.acc_size;
187 	} else if (bo->preferred_domains == AMDGPU_GEM_DOMAIN_GTT) {
188 		kfd_mem_limit.system_mem_used -=
189 			(bo->tbo.acc_size + amdgpu_bo_size(bo));
190 		kfd_mem_limit.ttm_mem_used -=
191 			(bo->tbo.acc_size + amdgpu_bo_size(bo));
192 	} else {
193 		kfd_mem_limit.system_mem_used -= bo->tbo.acc_size;
194 		kfd_mem_limit.ttm_mem_used -= bo->tbo.acc_size;
195 	}
196 	WARN_ONCE(kfd_mem_limit.system_mem_used < 0,
197 		  "kfd system memory accounting unbalanced");
198 	WARN_ONCE(kfd_mem_limit.ttm_mem_used < 0,
199 		  "kfd TTM memory accounting unbalanced");
200 
201 	spin_unlock(&kfd_mem_limit.mem_limit_lock);
202 }
203 
204 
205 /* amdgpu_amdkfd_remove_eviction_fence - Removes eviction fence(s) from BO's
206  *  reservation object.
207  *
208  * @bo: [IN] Remove eviction fence(s) from this BO
209  * @ef: [IN] If ef is specified, then this eviction fence is removed if it
210  *  is present in the shared list.
211  * @ef_list: [OUT] Returns list of eviction fences. These fences are removed
212  *  from BO's reservation object shared list.
213  * @ef_count: [OUT] Number of fences in ef_list.
214  *
215  * NOTE: If called with ef_list, then amdgpu_amdkfd_add_eviction_fence must be
216  *  called to restore the eviction fences and to avoid memory leak. This is
217  *  useful for shared BOs.
218  * NOTE: Must be called with BO reserved i.e. bo->tbo.resv->lock held.
219  */
220 static int amdgpu_amdkfd_remove_eviction_fence(struct amdgpu_bo *bo,
221 					struct amdgpu_amdkfd_fence *ef,
222 					struct amdgpu_amdkfd_fence ***ef_list,
223 					unsigned int *ef_count)
224 {
225 	struct reservation_object *resv = bo->tbo.resv;
226 	struct reservation_object_list *old, *new;
227 	unsigned int i, j, k;
228 
229 	if (!ef && !ef_list)
230 		return -EINVAL;
231 
232 	if (ef_list) {
233 		*ef_list = NULL;
234 		*ef_count = 0;
235 	}
236 
237 	old = reservation_object_get_list(resv);
238 	if (!old)
239 		return 0;
240 
241 	new = kmalloc(offsetof(typeof(*new), shared[old->shared_max]),
242 		      GFP_KERNEL);
243 	if (!new)
244 		return -ENOMEM;
245 
246 	/* Go through all the shared fences in the resevation object and sort
247 	 * the interesting ones to the end of the list.
248 	 */
249 	for (i = 0, j = old->shared_count, k = 0; i < old->shared_count; ++i) {
250 		struct dma_fence *f;
251 
252 		f = rcu_dereference_protected(old->shared[i],
253 					      reservation_object_held(resv));
254 
255 		if ((ef && f->context == ef->base.context) ||
256 		    (!ef && to_amdgpu_amdkfd_fence(f)))
257 			RCU_INIT_POINTER(new->shared[--j], f);
258 		else
259 			RCU_INIT_POINTER(new->shared[k++], f);
260 	}
261 	new->shared_max = old->shared_max;
262 	new->shared_count = k;
263 
264 	if (!ef) {
265 		unsigned int count = old->shared_count - j;
266 
267 		/* Alloc memory for count number of eviction fence pointers.
268 		 * Fill the ef_list array and ef_count
269 		 */
270 		*ef_list = kcalloc(count, sizeof(**ef_list), GFP_KERNEL);
271 		*ef_count = count;
272 
273 		if (!*ef_list) {
274 			kfree(new);
275 			return -ENOMEM;
276 		}
277 	}
278 
279 	/* Install the new fence list, seqcount provides the barriers */
280 	preempt_disable();
281 	write_seqcount_begin(&resv->seq);
282 	RCU_INIT_POINTER(resv->fence, new);
283 	write_seqcount_end(&resv->seq);
284 	preempt_enable();
285 
286 	/* Drop the references to the removed fences or move them to ef_list */
287 	for (i = j, k = 0; i < old->shared_count; ++i) {
288 		struct dma_fence *f;
289 
290 		f = rcu_dereference_protected(new->shared[i],
291 					      reservation_object_held(resv));
292 		if (!ef)
293 			(*ef_list)[k++] = to_amdgpu_amdkfd_fence(f);
294 		else
295 			dma_fence_put(f);
296 	}
297 	kfree_rcu(old, rcu);
298 
299 	return 0;
300 }
301 
302 /* amdgpu_amdkfd_add_eviction_fence - Adds eviction fence(s) back into BO's
303  *  reservation object.
304  *
305  * @bo: [IN] Add eviction fences to this BO
306  * @ef_list: [IN] List of eviction fences to be added
307  * @ef_count: [IN] Number of fences in ef_list.
308  *
309  * NOTE: Must call amdgpu_amdkfd_remove_eviction_fence before calling this
310  *  function.
311  */
312 static void amdgpu_amdkfd_add_eviction_fence(struct amdgpu_bo *bo,
313 				struct amdgpu_amdkfd_fence **ef_list,
314 				unsigned int ef_count)
315 {
316 	int i;
317 
318 	if (!ef_list || !ef_count)
319 		return;
320 
321 	for (i = 0; i < ef_count; i++) {
322 		amdgpu_bo_fence(bo, &ef_list[i]->base, true);
323 		/* Re-adding the fence takes an additional reference. Drop that
324 		 * reference.
325 		 */
326 		dma_fence_put(&ef_list[i]->base);
327 	}
328 
329 	kfree(ef_list);
330 }
331 
332 static int amdgpu_amdkfd_bo_validate(struct amdgpu_bo *bo, uint32_t domain,
333 				     bool wait)
334 {
335 	struct ttm_operation_ctx ctx = { false, false };
336 	int ret;
337 
338 	if (WARN(amdgpu_ttm_tt_get_usermm(bo->tbo.ttm),
339 		 "Called with userptr BO"))
340 		return -EINVAL;
341 
342 	amdgpu_bo_placement_from_domain(bo, domain);
343 
344 	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
345 	if (ret)
346 		goto validate_fail;
347 	if (wait) {
348 		struct amdgpu_amdkfd_fence **ef_list;
349 		unsigned int ef_count;
350 
351 		ret = amdgpu_amdkfd_remove_eviction_fence(bo, NULL, &ef_list,
352 							  &ef_count);
353 		if (ret)
354 			goto validate_fail;
355 
356 		ttm_bo_wait(&bo->tbo, false, false);
357 		amdgpu_amdkfd_add_eviction_fence(bo, ef_list, ef_count);
358 	}
359 
360 validate_fail:
361 	return ret;
362 }
363 
364 static int amdgpu_amdkfd_validate(void *param, struct amdgpu_bo *bo)
365 {
366 	struct amdgpu_vm_parser *p = param;
367 
368 	return amdgpu_amdkfd_bo_validate(bo, p->domain, p->wait);
369 }
370 
371 /* vm_validate_pt_pd_bos - Validate page table and directory BOs
372  *
373  * Page directories are not updated here because huge page handling
374  * during page table updates can invalidate page directory entries
375  * again. Page directories are only updated after updating page
376  * tables.
377  */
378 static int vm_validate_pt_pd_bos(struct amdgpu_vm *vm)
379 {
380 	struct amdgpu_bo *pd = vm->root.base.bo;
381 	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
382 	struct amdgpu_vm_parser param;
383 	int ret;
384 
385 	param.domain = AMDGPU_GEM_DOMAIN_VRAM;
386 	param.wait = false;
387 
388 	ret = amdgpu_vm_validate_pt_bos(adev, vm, amdgpu_amdkfd_validate,
389 					&param);
390 	if (ret) {
391 		pr_err("amdgpu: failed to validate PT BOs\n");
392 		return ret;
393 	}
394 
395 	ret = amdgpu_amdkfd_validate(&param, pd);
396 	if (ret) {
397 		pr_err("amdgpu: failed to validate PD\n");
398 		return ret;
399 	}
400 
401 	vm->pd_phys_addr = amdgpu_gmc_pd_addr(vm->root.base.bo);
402 
403 	if (vm->use_cpu_for_update) {
404 		ret = amdgpu_bo_kmap(pd, NULL);
405 		if (ret) {
406 			pr_err("amdgpu: failed to kmap PD, ret=%d\n", ret);
407 			return ret;
408 		}
409 	}
410 
411 	return 0;
412 }
413 
414 static int vm_update_pds(struct amdgpu_vm *vm, struct amdgpu_sync *sync)
415 {
416 	struct amdgpu_bo *pd = vm->root.base.bo;
417 	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
418 	int ret;
419 
420 	ret = amdgpu_vm_update_directories(adev, vm);
421 	if (ret)
422 		return ret;
423 
424 	return amdgpu_sync_fence(NULL, sync, vm->last_update, false);
425 }
426 
427 /* add_bo_to_vm - Add a BO to a VM
428  *
429  * Everything that needs to bo done only once when a BO is first added
430  * to a VM. It can later be mapped and unmapped many times without
431  * repeating these steps.
432  *
433  * 1. Allocate and initialize BO VA entry data structure
434  * 2. Add BO to the VM
435  * 3. Determine ASIC-specific PTE flags
436  * 4. Alloc page tables and directories if needed
437  * 4a.  Validate new page tables and directories
438  */
439 static int add_bo_to_vm(struct amdgpu_device *adev, struct kgd_mem *mem,
440 		struct amdgpu_vm *vm, bool is_aql,
441 		struct kfd_bo_va_list **p_bo_va_entry)
442 {
443 	int ret;
444 	struct kfd_bo_va_list *bo_va_entry;
445 	struct amdgpu_bo *pd = vm->root.base.bo;
446 	struct amdgpu_bo *bo = mem->bo;
447 	uint64_t va = mem->va;
448 	struct list_head *list_bo_va = &mem->bo_va_list;
449 	unsigned long bo_size = bo->tbo.mem.size;
450 
451 	if (!va) {
452 		pr_err("Invalid VA when adding BO to VM\n");
453 		return -EINVAL;
454 	}
455 
456 	if (is_aql)
457 		va += bo_size;
458 
459 	bo_va_entry = kzalloc(sizeof(*bo_va_entry), GFP_KERNEL);
460 	if (!bo_va_entry)
461 		return -ENOMEM;
462 
463 	pr_debug("\t add VA 0x%llx - 0x%llx to vm %p\n", va,
464 			va + bo_size, vm);
465 
466 	/* Add BO to VM internal data structures*/
467 	bo_va_entry->bo_va = amdgpu_vm_bo_add(adev, vm, bo);
468 	if (!bo_va_entry->bo_va) {
469 		ret = -EINVAL;
470 		pr_err("Failed to add BO object to VM. ret == %d\n",
471 				ret);
472 		goto err_vmadd;
473 	}
474 
475 	bo_va_entry->va = va;
476 	bo_va_entry->pte_flags = amdgpu_gmc_get_pte_flags(adev,
477 							 mem->mapping_flags);
478 	bo_va_entry->kgd_dev = (void *)adev;
479 	list_add(&bo_va_entry->bo_list, list_bo_va);
480 
481 	if (p_bo_va_entry)
482 		*p_bo_va_entry = bo_va_entry;
483 
484 	/* Allocate new page tables if needed and validate
485 	 * them. Clearing of new page tables and validate need to wait
486 	 * on move fences. We don't want that to trigger the eviction
487 	 * fence, so remove it temporarily.
488 	 */
489 	amdgpu_amdkfd_remove_eviction_fence(pd,
490 					vm->process_info->eviction_fence,
491 					NULL, NULL);
492 
493 	ret = amdgpu_vm_alloc_pts(adev, vm, va, amdgpu_bo_size(bo));
494 	if (ret) {
495 		pr_err("Failed to allocate pts, err=%d\n", ret);
496 		goto err_alloc_pts;
497 	}
498 
499 	ret = vm_validate_pt_pd_bos(vm);
500 	if (ret) {
501 		pr_err("validate_pt_pd_bos() failed\n");
502 		goto err_alloc_pts;
503 	}
504 
505 	/* Add the eviction fence back */
506 	amdgpu_bo_fence(pd, &vm->process_info->eviction_fence->base, true);
507 
508 	return 0;
509 
510 err_alloc_pts:
511 	amdgpu_bo_fence(pd, &vm->process_info->eviction_fence->base, true);
512 	amdgpu_vm_bo_rmv(adev, bo_va_entry->bo_va);
513 	list_del(&bo_va_entry->bo_list);
514 err_vmadd:
515 	kfree(bo_va_entry);
516 	return ret;
517 }
518 
519 static void remove_bo_from_vm(struct amdgpu_device *adev,
520 		struct kfd_bo_va_list *entry, unsigned long size)
521 {
522 	pr_debug("\t remove VA 0x%llx - 0x%llx in entry %p\n",
523 			entry->va,
524 			entry->va + size, entry);
525 	amdgpu_vm_bo_rmv(adev, entry->bo_va);
526 	list_del(&entry->bo_list);
527 	kfree(entry);
528 }
529 
530 static void add_kgd_mem_to_kfd_bo_list(struct kgd_mem *mem,
531 				struct amdkfd_process_info *process_info,
532 				bool userptr)
533 {
534 	struct ttm_validate_buffer *entry = &mem->validate_list;
535 	struct amdgpu_bo *bo = mem->bo;
536 
537 	INIT_LIST_HEAD(&entry->head);
538 	entry->shared = true;
539 	entry->bo = &bo->tbo;
540 	mutex_lock(&process_info->lock);
541 	if (userptr)
542 		list_add_tail(&entry->head, &process_info->userptr_valid_list);
543 	else
544 		list_add_tail(&entry->head, &process_info->kfd_bo_list);
545 	mutex_unlock(&process_info->lock);
546 }
547 
548 /* Initializes user pages. It registers the MMU notifier and validates
549  * the userptr BO in the GTT domain.
550  *
551  * The BO must already be on the userptr_valid_list. Otherwise an
552  * eviction and restore may happen that leaves the new BO unmapped
553  * with the user mode queues running.
554  *
555  * Takes the process_info->lock to protect against concurrent restore
556  * workers.
557  *
558  * Returns 0 for success, negative errno for errors.
559  */
560 static int init_user_pages(struct kgd_mem *mem, struct mm_struct *mm,
561 			   uint64_t user_addr)
562 {
563 	struct amdkfd_process_info *process_info = mem->process_info;
564 	struct amdgpu_bo *bo = mem->bo;
565 	struct ttm_operation_ctx ctx = { true, false };
566 	int ret = 0;
567 
568 	mutex_lock(&process_info->lock);
569 
570 	ret = amdgpu_ttm_tt_set_userptr(bo->tbo.ttm, user_addr, 0);
571 	if (ret) {
572 		pr_err("%s: Failed to set userptr: %d\n", __func__, ret);
573 		goto out;
574 	}
575 
576 	ret = amdgpu_mn_register(bo, user_addr);
577 	if (ret) {
578 		pr_err("%s: Failed to register MMU notifier: %d\n",
579 		       __func__, ret);
580 		goto out;
581 	}
582 
583 	/* If no restore worker is running concurrently, user_pages
584 	 * should not be allocated
585 	 */
586 	WARN(mem->user_pages, "Leaking user_pages array");
587 
588 	mem->user_pages = kvmalloc_array(bo->tbo.ttm->num_pages,
589 					   sizeof(struct page *),
590 					   GFP_KERNEL | __GFP_ZERO);
591 	if (!mem->user_pages) {
592 		pr_err("%s: Failed to allocate pages array\n", __func__);
593 		ret = -ENOMEM;
594 		goto unregister_out;
595 	}
596 
597 	ret = amdgpu_ttm_tt_get_user_pages(bo->tbo.ttm, mem->user_pages);
598 	if (ret) {
599 		pr_err("%s: Failed to get user pages: %d\n", __func__, ret);
600 		goto free_out;
601 	}
602 
603 	amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm, mem->user_pages);
604 
605 	ret = amdgpu_bo_reserve(bo, true);
606 	if (ret) {
607 		pr_err("%s: Failed to reserve BO\n", __func__);
608 		goto release_out;
609 	}
610 	amdgpu_bo_placement_from_domain(bo, mem->domain);
611 	ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
612 	if (ret)
613 		pr_err("%s: failed to validate BO\n", __func__);
614 	amdgpu_bo_unreserve(bo);
615 
616 release_out:
617 	if (ret)
618 		release_pages(mem->user_pages, bo->tbo.ttm->num_pages);
619 free_out:
620 	kvfree(mem->user_pages);
621 	mem->user_pages = NULL;
622 unregister_out:
623 	if (ret)
624 		amdgpu_mn_unregister(bo);
625 out:
626 	mutex_unlock(&process_info->lock);
627 	return ret;
628 }
629 
630 /* Reserving a BO and its page table BOs must happen atomically to
631  * avoid deadlocks. Some operations update multiple VMs at once. Track
632  * all the reservation info in a context structure. Optionally a sync
633  * object can track VM updates.
634  */
635 struct bo_vm_reservation_context {
636 	struct amdgpu_bo_list_entry kfd_bo; /* BO list entry for the KFD BO */
637 	unsigned int n_vms;		    /* Number of VMs reserved	    */
638 	struct amdgpu_bo_list_entry *vm_pd; /* Array of VM BO list entries  */
639 	struct ww_acquire_ctx ticket;	    /* Reservation ticket	    */
640 	struct list_head list, duplicates;  /* BO lists			    */
641 	struct amdgpu_sync *sync;	    /* Pointer to sync object	    */
642 	bool reserved;			    /* Whether BOs are reserved	    */
643 };
644 
645 enum bo_vm_match {
646 	BO_VM_NOT_MAPPED = 0,	/* Match VMs where a BO is not mapped */
647 	BO_VM_MAPPED,		/* Match VMs where a BO is mapped     */
648 	BO_VM_ALL,		/* Match all VMs a BO was added to    */
649 };
650 
651 /**
652  * reserve_bo_and_vm - reserve a BO and a VM unconditionally.
653  * @mem: KFD BO structure.
654  * @vm: the VM to reserve.
655  * @ctx: the struct that will be used in unreserve_bo_and_vms().
656  */
657 static int reserve_bo_and_vm(struct kgd_mem *mem,
658 			      struct amdgpu_vm *vm,
659 			      struct bo_vm_reservation_context *ctx)
660 {
661 	struct amdgpu_bo *bo = mem->bo;
662 	int ret;
663 
664 	WARN_ON(!vm);
665 
666 	ctx->reserved = false;
667 	ctx->n_vms = 1;
668 	ctx->sync = &mem->sync;
669 
670 	INIT_LIST_HEAD(&ctx->list);
671 	INIT_LIST_HEAD(&ctx->duplicates);
672 
673 	ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd), GFP_KERNEL);
674 	if (!ctx->vm_pd)
675 		return -ENOMEM;
676 
677 	ctx->kfd_bo.priority = 0;
678 	ctx->kfd_bo.tv.bo = &bo->tbo;
679 	ctx->kfd_bo.tv.shared = true;
680 	ctx->kfd_bo.user_pages = NULL;
681 	list_add(&ctx->kfd_bo.tv.head, &ctx->list);
682 
683 	amdgpu_vm_get_pd_bo(vm, &ctx->list, &ctx->vm_pd[0]);
684 
685 	ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
686 				     false, &ctx->duplicates);
687 	if (!ret)
688 		ctx->reserved = true;
689 	else {
690 		pr_err("Failed to reserve buffers in ttm\n");
691 		kfree(ctx->vm_pd);
692 		ctx->vm_pd = NULL;
693 	}
694 
695 	return ret;
696 }
697 
698 /**
699  * reserve_bo_and_cond_vms - reserve a BO and some VMs conditionally
700  * @mem: KFD BO structure.
701  * @vm: the VM to reserve. If NULL, then all VMs associated with the BO
702  * is used. Otherwise, a single VM associated with the BO.
703  * @map_type: the mapping status that will be used to filter the VMs.
704  * @ctx: the struct that will be used in unreserve_bo_and_vms().
705  *
706  * Returns 0 for success, negative for failure.
707  */
708 static int reserve_bo_and_cond_vms(struct kgd_mem *mem,
709 				struct amdgpu_vm *vm, enum bo_vm_match map_type,
710 				struct bo_vm_reservation_context *ctx)
711 {
712 	struct amdgpu_bo *bo = mem->bo;
713 	struct kfd_bo_va_list *entry;
714 	unsigned int i;
715 	int ret;
716 
717 	ctx->reserved = false;
718 	ctx->n_vms = 0;
719 	ctx->vm_pd = NULL;
720 	ctx->sync = &mem->sync;
721 
722 	INIT_LIST_HEAD(&ctx->list);
723 	INIT_LIST_HEAD(&ctx->duplicates);
724 
725 	list_for_each_entry(entry, &mem->bo_va_list, bo_list) {
726 		if ((vm && vm != entry->bo_va->base.vm) ||
727 			(entry->is_mapped != map_type
728 			&& map_type != BO_VM_ALL))
729 			continue;
730 
731 		ctx->n_vms++;
732 	}
733 
734 	if (ctx->n_vms != 0) {
735 		ctx->vm_pd = kcalloc(ctx->n_vms, sizeof(*ctx->vm_pd),
736 				     GFP_KERNEL);
737 		if (!ctx->vm_pd)
738 			return -ENOMEM;
739 	}
740 
741 	ctx->kfd_bo.priority = 0;
742 	ctx->kfd_bo.tv.bo = &bo->tbo;
743 	ctx->kfd_bo.tv.shared = true;
744 	ctx->kfd_bo.user_pages = NULL;
745 	list_add(&ctx->kfd_bo.tv.head, &ctx->list);
746 
747 	i = 0;
748 	list_for_each_entry(entry, &mem->bo_va_list, bo_list) {
749 		if ((vm && vm != entry->bo_va->base.vm) ||
750 			(entry->is_mapped != map_type
751 			&& map_type != BO_VM_ALL))
752 			continue;
753 
754 		amdgpu_vm_get_pd_bo(entry->bo_va->base.vm, &ctx->list,
755 				&ctx->vm_pd[i]);
756 		i++;
757 	}
758 
759 	ret = ttm_eu_reserve_buffers(&ctx->ticket, &ctx->list,
760 				     false, &ctx->duplicates);
761 	if (!ret)
762 		ctx->reserved = true;
763 	else
764 		pr_err("Failed to reserve buffers in ttm.\n");
765 
766 	if (ret) {
767 		kfree(ctx->vm_pd);
768 		ctx->vm_pd = NULL;
769 	}
770 
771 	return ret;
772 }
773 
774 /**
775  * unreserve_bo_and_vms - Unreserve BO and VMs from a reservation context
776  * @ctx: Reservation context to unreserve
777  * @wait: Optionally wait for a sync object representing pending VM updates
778  * @intr: Whether the wait is interruptible
779  *
780  * Also frees any resources allocated in
781  * reserve_bo_and_(cond_)vm(s). Returns the status from
782  * amdgpu_sync_wait.
783  */
784 static int unreserve_bo_and_vms(struct bo_vm_reservation_context *ctx,
785 				 bool wait, bool intr)
786 {
787 	int ret = 0;
788 
789 	if (wait)
790 		ret = amdgpu_sync_wait(ctx->sync, intr);
791 
792 	if (ctx->reserved)
793 		ttm_eu_backoff_reservation(&ctx->ticket, &ctx->list);
794 	kfree(ctx->vm_pd);
795 
796 	ctx->sync = NULL;
797 
798 	ctx->reserved = false;
799 	ctx->vm_pd = NULL;
800 
801 	return ret;
802 }
803 
804 static int unmap_bo_from_gpuvm(struct amdgpu_device *adev,
805 				struct kfd_bo_va_list *entry,
806 				struct amdgpu_sync *sync)
807 {
808 	struct amdgpu_bo_va *bo_va = entry->bo_va;
809 	struct amdgpu_vm *vm = bo_va->base.vm;
810 	struct amdgpu_bo *pd = vm->root.base.bo;
811 
812 	/* Remove eviction fence from PD (and thereby from PTs too as
813 	 * they share the resv. object). Otherwise during PT update
814 	 * job (see amdgpu_vm_bo_update_mapping), eviction fence would
815 	 * get added to job->sync object and job execution would
816 	 * trigger the eviction fence.
817 	 */
818 	amdgpu_amdkfd_remove_eviction_fence(pd,
819 					    vm->process_info->eviction_fence,
820 					    NULL, NULL);
821 	amdgpu_vm_bo_unmap(adev, bo_va, entry->va);
822 
823 	amdgpu_vm_clear_freed(adev, vm, &bo_va->last_pt_update);
824 
825 	/* Add the eviction fence back */
826 	amdgpu_bo_fence(pd, &vm->process_info->eviction_fence->base, true);
827 
828 	amdgpu_sync_fence(NULL, sync, bo_va->last_pt_update, false);
829 
830 	return 0;
831 }
832 
833 static int update_gpuvm_pte(struct amdgpu_device *adev,
834 		struct kfd_bo_va_list *entry,
835 		struct amdgpu_sync *sync)
836 {
837 	int ret;
838 	struct amdgpu_vm *vm;
839 	struct amdgpu_bo_va *bo_va;
840 	struct amdgpu_bo *bo;
841 
842 	bo_va = entry->bo_va;
843 	vm = bo_va->base.vm;
844 	bo = bo_va->base.bo;
845 
846 	/* Update the page tables  */
847 	ret = amdgpu_vm_bo_update(adev, bo_va, false);
848 	if (ret) {
849 		pr_err("amdgpu_vm_bo_update failed\n");
850 		return ret;
851 	}
852 
853 	return amdgpu_sync_fence(NULL, sync, bo_va->last_pt_update, false);
854 }
855 
856 static int map_bo_to_gpuvm(struct amdgpu_device *adev,
857 		struct kfd_bo_va_list *entry, struct amdgpu_sync *sync,
858 		bool no_update_pte)
859 {
860 	int ret;
861 
862 	/* Set virtual address for the allocation */
863 	ret = amdgpu_vm_bo_map(adev, entry->bo_va, entry->va, 0,
864 			       amdgpu_bo_size(entry->bo_va->base.bo),
865 			       entry->pte_flags);
866 	if (ret) {
867 		pr_err("Failed to map VA 0x%llx in vm. ret %d\n",
868 				entry->va, ret);
869 		return ret;
870 	}
871 
872 	if (no_update_pte)
873 		return 0;
874 
875 	ret = update_gpuvm_pte(adev, entry, sync);
876 	if (ret) {
877 		pr_err("update_gpuvm_pte() failed\n");
878 		goto update_gpuvm_pte_failed;
879 	}
880 
881 	return 0;
882 
883 update_gpuvm_pte_failed:
884 	unmap_bo_from_gpuvm(adev, entry, sync);
885 	return ret;
886 }
887 
888 static int process_validate_vms(struct amdkfd_process_info *process_info)
889 {
890 	struct amdgpu_vm *peer_vm;
891 	int ret;
892 
893 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
894 			    vm_list_node) {
895 		ret = vm_validate_pt_pd_bos(peer_vm);
896 		if (ret)
897 			return ret;
898 	}
899 
900 	return 0;
901 }
902 
903 static int process_sync_pds_resv(struct amdkfd_process_info *process_info,
904 				 struct amdgpu_sync *sync)
905 {
906 	struct amdgpu_vm *peer_vm;
907 	int ret;
908 
909 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
910 			    vm_list_node) {
911 		struct amdgpu_bo *pd = peer_vm->root.base.bo;
912 
913 		ret = amdgpu_sync_resv(NULL,
914 					sync, pd->tbo.resv,
915 					AMDGPU_FENCE_OWNER_UNDEFINED, false);
916 		if (ret)
917 			return ret;
918 	}
919 
920 	return 0;
921 }
922 
923 static int process_update_pds(struct amdkfd_process_info *process_info,
924 			      struct amdgpu_sync *sync)
925 {
926 	struct amdgpu_vm *peer_vm;
927 	int ret;
928 
929 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
930 			    vm_list_node) {
931 		ret = vm_update_pds(peer_vm, sync);
932 		if (ret)
933 			return ret;
934 	}
935 
936 	return 0;
937 }
938 
939 static int init_kfd_vm(struct amdgpu_vm *vm, void **process_info,
940 		       struct dma_fence **ef)
941 {
942 	struct amdkfd_process_info *info = NULL;
943 	int ret;
944 
945 	if (!*process_info) {
946 		info = kzalloc(sizeof(*info), GFP_KERNEL);
947 		if (!info)
948 			return -ENOMEM;
949 
950 		mutex_init(&info->lock);
951 		INIT_LIST_HEAD(&info->vm_list_head);
952 		INIT_LIST_HEAD(&info->kfd_bo_list);
953 		INIT_LIST_HEAD(&info->userptr_valid_list);
954 		INIT_LIST_HEAD(&info->userptr_inval_list);
955 
956 		info->eviction_fence =
957 			amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),
958 						   current->mm);
959 		if (!info->eviction_fence) {
960 			pr_err("Failed to create eviction fence\n");
961 			ret = -ENOMEM;
962 			goto create_evict_fence_fail;
963 		}
964 
965 		info->pid = get_task_pid(current->group_leader, PIDTYPE_PID);
966 		atomic_set(&info->evicted_bos, 0);
967 		INIT_DELAYED_WORK(&info->restore_userptr_work,
968 				  amdgpu_amdkfd_restore_userptr_worker);
969 
970 		*process_info = info;
971 		*ef = dma_fence_get(&info->eviction_fence->base);
972 	}
973 
974 	vm->process_info = *process_info;
975 
976 	/* Validate page directory and attach eviction fence */
977 	ret = amdgpu_bo_reserve(vm->root.base.bo, true);
978 	if (ret)
979 		goto reserve_pd_fail;
980 	ret = vm_validate_pt_pd_bos(vm);
981 	if (ret) {
982 		pr_err("validate_pt_pd_bos() failed\n");
983 		goto validate_pd_fail;
984 	}
985 	ret = ttm_bo_wait(&vm->root.base.bo->tbo, false, false);
986 	if (ret)
987 		goto wait_pd_fail;
988 	amdgpu_bo_fence(vm->root.base.bo,
989 			&vm->process_info->eviction_fence->base, true);
990 	amdgpu_bo_unreserve(vm->root.base.bo);
991 
992 	/* Update process info */
993 	mutex_lock(&vm->process_info->lock);
994 	list_add_tail(&vm->vm_list_node,
995 			&(vm->process_info->vm_list_head));
996 	vm->process_info->n_vms++;
997 	mutex_unlock(&vm->process_info->lock);
998 
999 	return 0;
1000 
1001 wait_pd_fail:
1002 validate_pd_fail:
1003 	amdgpu_bo_unreserve(vm->root.base.bo);
1004 reserve_pd_fail:
1005 	vm->process_info = NULL;
1006 	if (info) {
1007 		/* Two fence references: one in info and one in *ef */
1008 		dma_fence_put(&info->eviction_fence->base);
1009 		dma_fence_put(*ef);
1010 		*ef = NULL;
1011 		*process_info = NULL;
1012 		put_pid(info->pid);
1013 create_evict_fence_fail:
1014 		mutex_destroy(&info->lock);
1015 		kfree(info);
1016 	}
1017 	return ret;
1018 }
1019 
1020 int amdgpu_amdkfd_gpuvm_create_process_vm(struct kgd_dev *kgd, unsigned int pasid,
1021 					  void **vm, void **process_info,
1022 					  struct dma_fence **ef)
1023 {
1024 	struct amdgpu_device *adev = get_amdgpu_device(kgd);
1025 	struct amdgpu_vm *new_vm;
1026 	int ret;
1027 
1028 	new_vm = kzalloc(sizeof(*new_vm), GFP_KERNEL);
1029 	if (!new_vm)
1030 		return -ENOMEM;
1031 
1032 	/* Initialize AMDGPU part of the VM */
1033 	ret = amdgpu_vm_init(adev, new_vm, AMDGPU_VM_CONTEXT_COMPUTE, pasid);
1034 	if (ret) {
1035 		pr_err("Failed init vm ret %d\n", ret);
1036 		goto amdgpu_vm_init_fail;
1037 	}
1038 
1039 	/* Initialize KFD part of the VM and process info */
1040 	ret = init_kfd_vm(new_vm, process_info, ef);
1041 	if (ret)
1042 		goto init_kfd_vm_fail;
1043 
1044 	*vm = (void *) new_vm;
1045 
1046 	return 0;
1047 
1048 init_kfd_vm_fail:
1049 	amdgpu_vm_fini(adev, new_vm);
1050 amdgpu_vm_init_fail:
1051 	kfree(new_vm);
1052 	return ret;
1053 }
1054 
1055 int amdgpu_amdkfd_gpuvm_acquire_process_vm(struct kgd_dev *kgd,
1056 					   struct file *filp, unsigned int pasid,
1057 					   void **vm, void **process_info,
1058 					   struct dma_fence **ef)
1059 {
1060 	struct amdgpu_device *adev = get_amdgpu_device(kgd);
1061 	struct drm_file *drm_priv = filp->private_data;
1062 	struct amdgpu_fpriv *drv_priv = drm_priv->driver_priv;
1063 	struct amdgpu_vm *avm = &drv_priv->vm;
1064 	int ret;
1065 
1066 	/* Already a compute VM? */
1067 	if (avm->process_info)
1068 		return -EINVAL;
1069 
1070 	/* Convert VM into a compute VM */
1071 	ret = amdgpu_vm_make_compute(adev, avm, pasid);
1072 	if (ret)
1073 		return ret;
1074 
1075 	/* Initialize KFD part of the VM and process info */
1076 	ret = init_kfd_vm(avm, process_info, ef);
1077 	if (ret)
1078 		return ret;
1079 
1080 	*vm = (void *)avm;
1081 
1082 	return 0;
1083 }
1084 
1085 void amdgpu_amdkfd_gpuvm_destroy_cb(struct amdgpu_device *adev,
1086 				    struct amdgpu_vm *vm)
1087 {
1088 	struct amdkfd_process_info *process_info = vm->process_info;
1089 	struct amdgpu_bo *pd = vm->root.base.bo;
1090 
1091 	if (!process_info)
1092 		return;
1093 
1094 	/* Release eviction fence from PD */
1095 	amdgpu_bo_reserve(pd, false);
1096 	amdgpu_bo_fence(pd, NULL, false);
1097 	amdgpu_bo_unreserve(pd);
1098 
1099 	/* Update process info */
1100 	mutex_lock(&process_info->lock);
1101 	process_info->n_vms--;
1102 	list_del(&vm->vm_list_node);
1103 	mutex_unlock(&process_info->lock);
1104 
1105 	/* Release per-process resources when last compute VM is destroyed */
1106 	if (!process_info->n_vms) {
1107 		WARN_ON(!list_empty(&process_info->kfd_bo_list));
1108 		WARN_ON(!list_empty(&process_info->userptr_valid_list));
1109 		WARN_ON(!list_empty(&process_info->userptr_inval_list));
1110 
1111 		dma_fence_put(&process_info->eviction_fence->base);
1112 		cancel_delayed_work_sync(&process_info->restore_userptr_work);
1113 		put_pid(process_info->pid);
1114 		mutex_destroy(&process_info->lock);
1115 		kfree(process_info);
1116 	}
1117 }
1118 
1119 void amdgpu_amdkfd_gpuvm_destroy_process_vm(struct kgd_dev *kgd, void *vm)
1120 {
1121 	struct amdgpu_device *adev = get_amdgpu_device(kgd);
1122 	struct amdgpu_vm *avm = (struct amdgpu_vm *)vm;
1123 
1124 	if (WARN_ON(!kgd || !vm))
1125 		return;
1126 
1127 	pr_debug("Destroying process vm %p\n", vm);
1128 
1129 	/* Release the VM context */
1130 	amdgpu_vm_fini(adev, avm);
1131 	kfree(vm);
1132 }
1133 
1134 void amdgpu_amdkfd_gpuvm_release_process_vm(struct kgd_dev *kgd, void *vm)
1135 {
1136 	struct amdgpu_device *adev = get_amdgpu_device(kgd);
1137         struct amdgpu_vm *avm = (struct amdgpu_vm *)vm;
1138 
1139 	if (WARN_ON(!kgd || !vm))
1140                 return;
1141 
1142         pr_debug("Releasing process vm %p\n", vm);
1143 
1144         /* The original pasid of amdgpu vm has already been
1145          * released during making a amdgpu vm to a compute vm
1146          * The current pasid is managed by kfd and will be
1147          * released on kfd process destroy. Set amdgpu pasid
1148          * to 0 to avoid duplicate release.
1149          */
1150 	amdgpu_vm_release_compute(adev, avm);
1151 }
1152 
1153 uint64_t amdgpu_amdkfd_gpuvm_get_process_page_dir(void *vm)
1154 {
1155 	struct amdgpu_vm *avm = (struct amdgpu_vm *)vm;
1156 	struct amdgpu_bo *pd = avm->root.base.bo;
1157 	struct amdgpu_device *adev = amdgpu_ttm_adev(pd->tbo.bdev);
1158 
1159 	if (adev->asic_type < CHIP_VEGA10)
1160 		return avm->pd_phys_addr >> AMDGPU_GPU_PAGE_SHIFT;
1161 	return avm->pd_phys_addr;
1162 }
1163 
1164 int amdgpu_amdkfd_gpuvm_alloc_memory_of_gpu(
1165 		struct kgd_dev *kgd, uint64_t va, uint64_t size,
1166 		void *vm, struct kgd_mem **mem,
1167 		uint64_t *offset, uint32_t flags)
1168 {
1169 	struct amdgpu_device *adev = get_amdgpu_device(kgd);
1170 	struct amdgpu_vm *avm = (struct amdgpu_vm *)vm;
1171 	uint64_t user_addr = 0;
1172 	struct amdgpu_bo *bo;
1173 	struct amdgpu_bo_param bp;
1174 	int byte_align;
1175 	u32 domain, alloc_domain;
1176 	u64 alloc_flags;
1177 	uint32_t mapping_flags;
1178 	int ret;
1179 
1180 	/*
1181 	 * Check on which domain to allocate BO
1182 	 */
1183 	if (flags & ALLOC_MEM_FLAGS_VRAM) {
1184 		domain = alloc_domain = AMDGPU_GEM_DOMAIN_VRAM;
1185 		alloc_flags = AMDGPU_GEM_CREATE_VRAM_CLEARED;
1186 		alloc_flags |= (flags & ALLOC_MEM_FLAGS_PUBLIC) ?
1187 			AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED :
1188 			AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
1189 	} else if (flags & ALLOC_MEM_FLAGS_GTT) {
1190 		domain = alloc_domain = AMDGPU_GEM_DOMAIN_GTT;
1191 		alloc_flags = 0;
1192 	} else if (flags & ALLOC_MEM_FLAGS_USERPTR) {
1193 		domain = AMDGPU_GEM_DOMAIN_GTT;
1194 		alloc_domain = AMDGPU_GEM_DOMAIN_CPU;
1195 		alloc_flags = 0;
1196 		if (!offset || !*offset)
1197 			return -EINVAL;
1198 		user_addr = *offset;
1199 	} else {
1200 		return -EINVAL;
1201 	}
1202 
1203 	*mem = kzalloc(sizeof(struct kgd_mem), GFP_KERNEL);
1204 	if (!*mem)
1205 		return -ENOMEM;
1206 	INIT_LIST_HEAD(&(*mem)->bo_va_list);
1207 	mutex_init(&(*mem)->lock);
1208 	(*mem)->aql_queue = !!(flags & ALLOC_MEM_FLAGS_AQL_QUEUE_MEM);
1209 
1210 	/* Workaround for AQL queue wraparound bug. Map the same
1211 	 * memory twice. That means we only actually allocate half
1212 	 * the memory.
1213 	 */
1214 	if ((*mem)->aql_queue)
1215 		size = size >> 1;
1216 
1217 	/* Workaround for TLB bug on older VI chips */
1218 	byte_align = (adev->family == AMDGPU_FAMILY_VI &&
1219 			adev->asic_type != CHIP_FIJI &&
1220 			adev->asic_type != CHIP_POLARIS10 &&
1221 			adev->asic_type != CHIP_POLARIS11 &&
1222 			adev->asic_type != CHIP_POLARIS12) ?
1223 			VI_BO_SIZE_ALIGN : 1;
1224 
1225 	mapping_flags = AMDGPU_VM_PAGE_READABLE;
1226 	if (flags & ALLOC_MEM_FLAGS_WRITABLE)
1227 		mapping_flags |= AMDGPU_VM_PAGE_WRITEABLE;
1228 	if (flags & ALLOC_MEM_FLAGS_EXECUTABLE)
1229 		mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE;
1230 	if (flags & ALLOC_MEM_FLAGS_COHERENT)
1231 		mapping_flags |= AMDGPU_VM_MTYPE_UC;
1232 	else
1233 		mapping_flags |= AMDGPU_VM_MTYPE_NC;
1234 	(*mem)->mapping_flags = mapping_flags;
1235 
1236 	amdgpu_sync_create(&(*mem)->sync);
1237 
1238 	ret = amdgpu_amdkfd_reserve_system_mem_limit(adev, size,
1239 						     alloc_domain, false);
1240 	if (ret) {
1241 		pr_debug("Insufficient system memory\n");
1242 		goto err_reserve_limit;
1243 	}
1244 
1245 	pr_debug("\tcreate BO VA 0x%llx size 0x%llx domain %s\n",
1246 			va, size, domain_string(alloc_domain));
1247 
1248 	memset(&bp, 0, sizeof(bp));
1249 	bp.size = size;
1250 	bp.byte_align = byte_align;
1251 	bp.domain = alloc_domain;
1252 	bp.flags = alloc_flags;
1253 	bp.type = ttm_bo_type_device;
1254 	bp.resv = NULL;
1255 	ret = amdgpu_bo_create(adev, &bp, &bo);
1256 	if (ret) {
1257 		pr_debug("Failed to create BO on domain %s. ret %d\n",
1258 				domain_string(alloc_domain), ret);
1259 		goto err_bo_create;
1260 	}
1261 	bo->kfd_bo = *mem;
1262 	(*mem)->bo = bo;
1263 	if (user_addr)
1264 		bo->flags |= AMDGPU_AMDKFD_USERPTR_BO;
1265 
1266 	(*mem)->va = va;
1267 	(*mem)->domain = domain;
1268 	(*mem)->mapped_to_gpu_memory = 0;
1269 	(*mem)->process_info = avm->process_info;
1270 	add_kgd_mem_to_kfd_bo_list(*mem, avm->process_info, user_addr);
1271 
1272 	if (user_addr) {
1273 		ret = init_user_pages(*mem, current->mm, user_addr);
1274 		if (ret) {
1275 			mutex_lock(&avm->process_info->lock);
1276 			list_del(&(*mem)->validate_list.head);
1277 			mutex_unlock(&avm->process_info->lock);
1278 			goto allocate_init_user_pages_failed;
1279 		}
1280 	}
1281 
1282 	if (offset)
1283 		*offset = amdgpu_bo_mmap_offset(bo);
1284 
1285 	return 0;
1286 
1287 allocate_init_user_pages_failed:
1288 	amdgpu_bo_unref(&bo);
1289 	/* Don't unreserve system mem limit twice */
1290 	goto err_reserve_limit;
1291 err_bo_create:
1292 	unreserve_system_mem_limit(adev, size, alloc_domain, false);
1293 err_reserve_limit:
1294 	mutex_destroy(&(*mem)->lock);
1295 	kfree(*mem);
1296 	return ret;
1297 }
1298 
1299 int amdgpu_amdkfd_gpuvm_free_memory_of_gpu(
1300 		struct kgd_dev *kgd, struct kgd_mem *mem)
1301 {
1302 	struct amdkfd_process_info *process_info = mem->process_info;
1303 	unsigned long bo_size = mem->bo->tbo.mem.size;
1304 	struct kfd_bo_va_list *entry, *tmp;
1305 	struct bo_vm_reservation_context ctx;
1306 	struct ttm_validate_buffer *bo_list_entry;
1307 	int ret;
1308 
1309 	mutex_lock(&mem->lock);
1310 
1311 	if (mem->mapped_to_gpu_memory > 0) {
1312 		pr_debug("BO VA 0x%llx size 0x%lx is still mapped.\n",
1313 				mem->va, bo_size);
1314 		mutex_unlock(&mem->lock);
1315 		return -EBUSY;
1316 	}
1317 
1318 	mutex_unlock(&mem->lock);
1319 	/* lock is not needed after this, since mem is unused and will
1320 	 * be freed anyway
1321 	 */
1322 
1323 	/* No more MMU notifiers */
1324 	amdgpu_mn_unregister(mem->bo);
1325 
1326 	/* Make sure restore workers don't access the BO any more */
1327 	bo_list_entry = &mem->validate_list;
1328 	mutex_lock(&process_info->lock);
1329 	list_del(&bo_list_entry->head);
1330 	mutex_unlock(&process_info->lock);
1331 
1332 	/* Free user pages if necessary */
1333 	if (mem->user_pages) {
1334 		pr_debug("%s: Freeing user_pages array\n", __func__);
1335 		if (mem->user_pages[0])
1336 			release_pages(mem->user_pages,
1337 					mem->bo->tbo.ttm->num_pages);
1338 		kvfree(mem->user_pages);
1339 	}
1340 
1341 	ret = reserve_bo_and_cond_vms(mem, NULL, BO_VM_ALL, &ctx);
1342 	if (unlikely(ret))
1343 		return ret;
1344 
1345 	/* The eviction fence should be removed by the last unmap.
1346 	 * TODO: Log an error condition if the bo still has the eviction fence
1347 	 * attached
1348 	 */
1349 	amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1350 					process_info->eviction_fence,
1351 					NULL, NULL);
1352 	pr_debug("Release VA 0x%llx - 0x%llx\n", mem->va,
1353 		mem->va + bo_size * (1 + mem->aql_queue));
1354 
1355 	/* Remove from VM internal data structures */
1356 	list_for_each_entry_safe(entry, tmp, &mem->bo_va_list, bo_list)
1357 		remove_bo_from_vm((struct amdgpu_device *)entry->kgd_dev,
1358 				entry, bo_size);
1359 
1360 	ret = unreserve_bo_and_vms(&ctx, false, false);
1361 
1362 	/* Free the sync object */
1363 	amdgpu_sync_free(&mem->sync);
1364 
1365 	/* Free the BO*/
1366 	amdgpu_bo_unref(&mem->bo);
1367 	mutex_destroy(&mem->lock);
1368 	kfree(mem);
1369 
1370 	return ret;
1371 }
1372 
1373 int amdgpu_amdkfd_gpuvm_map_memory_to_gpu(
1374 		struct kgd_dev *kgd, struct kgd_mem *mem, void *vm)
1375 {
1376 	struct amdgpu_device *adev = get_amdgpu_device(kgd);
1377 	struct amdgpu_vm *avm = (struct amdgpu_vm *)vm;
1378 	int ret;
1379 	struct amdgpu_bo *bo;
1380 	uint32_t domain;
1381 	struct kfd_bo_va_list *entry;
1382 	struct bo_vm_reservation_context ctx;
1383 	struct kfd_bo_va_list *bo_va_entry = NULL;
1384 	struct kfd_bo_va_list *bo_va_entry_aql = NULL;
1385 	unsigned long bo_size;
1386 	bool is_invalid_userptr = false;
1387 
1388 	bo = mem->bo;
1389 	if (!bo) {
1390 		pr_err("Invalid BO when mapping memory to GPU\n");
1391 		return -EINVAL;
1392 	}
1393 
1394 	/* Make sure restore is not running concurrently. Since we
1395 	 * don't map invalid userptr BOs, we rely on the next restore
1396 	 * worker to do the mapping
1397 	 */
1398 	mutex_lock(&mem->process_info->lock);
1399 
1400 	/* Lock mmap-sem. If we find an invalid userptr BO, we can be
1401 	 * sure that the MMU notifier is no longer running
1402 	 * concurrently and the queues are actually stopped
1403 	 */
1404 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1405 		down_write(&current->mm->mmap_sem);
1406 		is_invalid_userptr = atomic_read(&mem->invalid);
1407 		up_write(&current->mm->mmap_sem);
1408 	}
1409 
1410 	mutex_lock(&mem->lock);
1411 
1412 	domain = mem->domain;
1413 	bo_size = bo->tbo.mem.size;
1414 
1415 	pr_debug("Map VA 0x%llx - 0x%llx to vm %p domain %s\n",
1416 			mem->va,
1417 			mem->va + bo_size * (1 + mem->aql_queue),
1418 			vm, domain_string(domain));
1419 
1420 	ret = reserve_bo_and_vm(mem, vm, &ctx);
1421 	if (unlikely(ret))
1422 		goto out;
1423 
1424 	/* Userptr can be marked as "not invalid", but not actually be
1425 	 * validated yet (still in the system domain). In that case
1426 	 * the queues are still stopped and we can leave mapping for
1427 	 * the next restore worker
1428 	 */
1429 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) &&
1430 	    bo->tbo.mem.mem_type == TTM_PL_SYSTEM)
1431 		is_invalid_userptr = true;
1432 
1433 	if (check_if_add_bo_to_vm(avm, mem)) {
1434 		ret = add_bo_to_vm(adev, mem, avm, false,
1435 				&bo_va_entry);
1436 		if (ret)
1437 			goto add_bo_to_vm_failed;
1438 		if (mem->aql_queue) {
1439 			ret = add_bo_to_vm(adev, mem, avm,
1440 					true, &bo_va_entry_aql);
1441 			if (ret)
1442 				goto add_bo_to_vm_failed_aql;
1443 		}
1444 	} else {
1445 		ret = vm_validate_pt_pd_bos(avm);
1446 		if (unlikely(ret))
1447 			goto add_bo_to_vm_failed;
1448 	}
1449 
1450 	if (mem->mapped_to_gpu_memory == 0 &&
1451 	    !amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1452 		/* Validate BO only once. The eviction fence gets added to BO
1453 		 * the first time it is mapped. Validate will wait for all
1454 		 * background evictions to complete.
1455 		 */
1456 		ret = amdgpu_amdkfd_bo_validate(bo, domain, true);
1457 		if (ret) {
1458 			pr_debug("Validate failed\n");
1459 			goto map_bo_to_gpuvm_failed;
1460 		}
1461 	}
1462 
1463 	list_for_each_entry(entry, &mem->bo_va_list, bo_list) {
1464 		if (entry->bo_va->base.vm == vm && !entry->is_mapped) {
1465 			pr_debug("\t map VA 0x%llx - 0x%llx in entry %p\n",
1466 					entry->va, entry->va + bo_size,
1467 					entry);
1468 
1469 			ret = map_bo_to_gpuvm(adev, entry, ctx.sync,
1470 					      is_invalid_userptr);
1471 			if (ret) {
1472 				pr_err("Failed to map radeon bo to gpuvm\n");
1473 				goto map_bo_to_gpuvm_failed;
1474 			}
1475 
1476 			ret = vm_update_pds(vm, ctx.sync);
1477 			if (ret) {
1478 				pr_err("Failed to update page directories\n");
1479 				goto map_bo_to_gpuvm_failed;
1480 			}
1481 
1482 			entry->is_mapped = true;
1483 			mem->mapped_to_gpu_memory++;
1484 			pr_debug("\t INC mapping count %d\n",
1485 					mem->mapped_to_gpu_memory);
1486 		}
1487 	}
1488 
1489 	if (!amdgpu_ttm_tt_get_usermm(bo->tbo.ttm) && !bo->pin_count)
1490 		amdgpu_bo_fence(bo,
1491 				&avm->process_info->eviction_fence->base,
1492 				true);
1493 	ret = unreserve_bo_and_vms(&ctx, false, false);
1494 
1495 	goto out;
1496 
1497 map_bo_to_gpuvm_failed:
1498 	if (bo_va_entry_aql)
1499 		remove_bo_from_vm(adev, bo_va_entry_aql, bo_size);
1500 add_bo_to_vm_failed_aql:
1501 	if (bo_va_entry)
1502 		remove_bo_from_vm(adev, bo_va_entry, bo_size);
1503 add_bo_to_vm_failed:
1504 	unreserve_bo_and_vms(&ctx, false, false);
1505 out:
1506 	mutex_unlock(&mem->process_info->lock);
1507 	mutex_unlock(&mem->lock);
1508 	return ret;
1509 }
1510 
1511 int amdgpu_amdkfd_gpuvm_unmap_memory_from_gpu(
1512 		struct kgd_dev *kgd, struct kgd_mem *mem, void *vm)
1513 {
1514 	struct amdgpu_device *adev = get_amdgpu_device(kgd);
1515 	struct amdkfd_process_info *process_info =
1516 		((struct amdgpu_vm *)vm)->process_info;
1517 	unsigned long bo_size = mem->bo->tbo.mem.size;
1518 	struct kfd_bo_va_list *entry;
1519 	struct bo_vm_reservation_context ctx;
1520 	int ret;
1521 
1522 	mutex_lock(&mem->lock);
1523 
1524 	ret = reserve_bo_and_cond_vms(mem, vm, BO_VM_MAPPED, &ctx);
1525 	if (unlikely(ret))
1526 		goto out;
1527 	/* If no VMs were reserved, it means the BO wasn't actually mapped */
1528 	if (ctx.n_vms == 0) {
1529 		ret = -EINVAL;
1530 		goto unreserve_out;
1531 	}
1532 
1533 	ret = vm_validate_pt_pd_bos((struct amdgpu_vm *)vm);
1534 	if (unlikely(ret))
1535 		goto unreserve_out;
1536 
1537 	pr_debug("Unmap VA 0x%llx - 0x%llx from vm %p\n",
1538 		mem->va,
1539 		mem->va + bo_size * (1 + mem->aql_queue),
1540 		vm);
1541 
1542 	list_for_each_entry(entry, &mem->bo_va_list, bo_list) {
1543 		if (entry->bo_va->base.vm == vm && entry->is_mapped) {
1544 			pr_debug("\t unmap VA 0x%llx - 0x%llx from entry %p\n",
1545 					entry->va,
1546 					entry->va + bo_size,
1547 					entry);
1548 
1549 			ret = unmap_bo_from_gpuvm(adev, entry, ctx.sync);
1550 			if (ret == 0) {
1551 				entry->is_mapped = false;
1552 			} else {
1553 				pr_err("failed to unmap VA 0x%llx\n",
1554 						mem->va);
1555 				goto unreserve_out;
1556 			}
1557 
1558 			mem->mapped_to_gpu_memory--;
1559 			pr_debug("\t DEC mapping count %d\n",
1560 					mem->mapped_to_gpu_memory);
1561 		}
1562 	}
1563 
1564 	/* If BO is unmapped from all VMs, unfence it. It can be evicted if
1565 	 * required.
1566 	 */
1567 	if (mem->mapped_to_gpu_memory == 0 &&
1568 	    !amdgpu_ttm_tt_get_usermm(mem->bo->tbo.ttm) && !mem->bo->pin_count)
1569 		amdgpu_amdkfd_remove_eviction_fence(mem->bo,
1570 						process_info->eviction_fence,
1571 						    NULL, NULL);
1572 
1573 unreserve_out:
1574 	unreserve_bo_and_vms(&ctx, false, false);
1575 out:
1576 	mutex_unlock(&mem->lock);
1577 	return ret;
1578 }
1579 
1580 int amdgpu_amdkfd_gpuvm_sync_memory(
1581 		struct kgd_dev *kgd, struct kgd_mem *mem, bool intr)
1582 {
1583 	struct amdgpu_sync sync;
1584 	int ret;
1585 
1586 	amdgpu_sync_create(&sync);
1587 
1588 	mutex_lock(&mem->lock);
1589 	amdgpu_sync_clone(&mem->sync, &sync);
1590 	mutex_unlock(&mem->lock);
1591 
1592 	ret = amdgpu_sync_wait(&sync, intr);
1593 	amdgpu_sync_free(&sync);
1594 	return ret;
1595 }
1596 
1597 int amdgpu_amdkfd_gpuvm_map_gtt_bo_to_kernel(struct kgd_dev *kgd,
1598 		struct kgd_mem *mem, void **kptr, uint64_t *size)
1599 {
1600 	int ret;
1601 	struct amdgpu_bo *bo = mem->bo;
1602 
1603 	if (amdgpu_ttm_tt_get_usermm(bo->tbo.ttm)) {
1604 		pr_err("userptr can't be mapped to kernel\n");
1605 		return -EINVAL;
1606 	}
1607 
1608 	/* delete kgd_mem from kfd_bo_list to avoid re-validating
1609 	 * this BO in BO's restoring after eviction.
1610 	 */
1611 	mutex_lock(&mem->process_info->lock);
1612 
1613 	ret = amdgpu_bo_reserve(bo, true);
1614 	if (ret) {
1615 		pr_err("Failed to reserve bo. ret %d\n", ret);
1616 		goto bo_reserve_failed;
1617 	}
1618 
1619 	ret = amdgpu_bo_pin(bo, AMDGPU_GEM_DOMAIN_GTT);
1620 	if (ret) {
1621 		pr_err("Failed to pin bo. ret %d\n", ret);
1622 		goto pin_failed;
1623 	}
1624 
1625 	ret = amdgpu_bo_kmap(bo, kptr);
1626 	if (ret) {
1627 		pr_err("Failed to map bo to kernel. ret %d\n", ret);
1628 		goto kmap_failed;
1629 	}
1630 
1631 	amdgpu_amdkfd_remove_eviction_fence(
1632 		bo, mem->process_info->eviction_fence, NULL, NULL);
1633 	list_del_init(&mem->validate_list.head);
1634 
1635 	if (size)
1636 		*size = amdgpu_bo_size(bo);
1637 
1638 	amdgpu_bo_unreserve(bo);
1639 
1640 	mutex_unlock(&mem->process_info->lock);
1641 	return 0;
1642 
1643 kmap_failed:
1644 	amdgpu_bo_unpin(bo);
1645 pin_failed:
1646 	amdgpu_bo_unreserve(bo);
1647 bo_reserve_failed:
1648 	mutex_unlock(&mem->process_info->lock);
1649 
1650 	return ret;
1651 }
1652 
1653 int amdgpu_amdkfd_gpuvm_get_vm_fault_info(struct kgd_dev *kgd,
1654 					      struct kfd_vm_fault_info *mem)
1655 {
1656 	struct amdgpu_device *adev;
1657 
1658 	adev = (struct amdgpu_device *)kgd;
1659 	if (atomic_read(&adev->gmc.vm_fault_info_updated) == 1) {
1660 		*mem = *adev->gmc.vm_fault_info;
1661 		mb();
1662 		atomic_set(&adev->gmc.vm_fault_info_updated, 0);
1663 	}
1664 	return 0;
1665 }
1666 
1667 /* Evict a userptr BO by stopping the queues if necessary
1668  *
1669  * Runs in MMU notifier, may be in RECLAIM_FS context. This means it
1670  * cannot do any memory allocations, and cannot take any locks that
1671  * are held elsewhere while allocating memory. Therefore this is as
1672  * simple as possible, using atomic counters.
1673  *
1674  * It doesn't do anything to the BO itself. The real work happens in
1675  * restore, where we get updated page addresses. This function only
1676  * ensures that GPU access to the BO is stopped.
1677  */
1678 int amdgpu_amdkfd_evict_userptr(struct kgd_mem *mem,
1679 				struct mm_struct *mm)
1680 {
1681 	struct amdkfd_process_info *process_info = mem->process_info;
1682 	int invalid, evicted_bos;
1683 	int r = 0;
1684 
1685 	invalid = atomic_inc_return(&mem->invalid);
1686 	evicted_bos = atomic_inc_return(&process_info->evicted_bos);
1687 	if (evicted_bos == 1) {
1688 		/* First eviction, stop the queues */
1689 		r = kgd2kfd->quiesce_mm(mm);
1690 		if (r)
1691 			pr_err("Failed to quiesce KFD\n");
1692 		schedule_delayed_work(&process_info->restore_userptr_work,
1693 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
1694 	}
1695 
1696 	return r;
1697 }
1698 
1699 /* Update invalid userptr BOs
1700  *
1701  * Moves invalidated (evicted) userptr BOs from userptr_valid_list to
1702  * userptr_inval_list and updates user pages for all BOs that have
1703  * been invalidated since their last update.
1704  */
1705 static int update_invalid_user_pages(struct amdkfd_process_info *process_info,
1706 				     struct mm_struct *mm)
1707 {
1708 	struct kgd_mem *mem, *tmp_mem;
1709 	struct amdgpu_bo *bo;
1710 	struct ttm_operation_ctx ctx = { false, false };
1711 	int invalid, ret;
1712 
1713 	/* Move all invalidated BOs to the userptr_inval_list and
1714 	 * release their user pages by migration to the CPU domain
1715 	 */
1716 	list_for_each_entry_safe(mem, tmp_mem,
1717 				 &process_info->userptr_valid_list,
1718 				 validate_list.head) {
1719 		if (!atomic_read(&mem->invalid))
1720 			continue; /* BO is still valid */
1721 
1722 		bo = mem->bo;
1723 
1724 		if (amdgpu_bo_reserve(bo, true))
1725 			return -EAGAIN;
1726 		amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_CPU);
1727 		ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1728 		amdgpu_bo_unreserve(bo);
1729 		if (ret) {
1730 			pr_err("%s: Failed to invalidate userptr BO\n",
1731 			       __func__);
1732 			return -EAGAIN;
1733 		}
1734 
1735 		list_move_tail(&mem->validate_list.head,
1736 			       &process_info->userptr_inval_list);
1737 	}
1738 
1739 	if (list_empty(&process_info->userptr_inval_list))
1740 		return 0; /* All evicted userptr BOs were freed */
1741 
1742 	/* Go through userptr_inval_list and update any invalid user_pages */
1743 	list_for_each_entry(mem, &process_info->userptr_inval_list,
1744 			    validate_list.head) {
1745 		invalid = atomic_read(&mem->invalid);
1746 		if (!invalid)
1747 			/* BO hasn't been invalidated since the last
1748 			 * revalidation attempt. Keep its BO list.
1749 			 */
1750 			continue;
1751 
1752 		bo = mem->bo;
1753 
1754 		if (!mem->user_pages) {
1755 			mem->user_pages =
1756 				kvmalloc_array(bo->tbo.ttm->num_pages,
1757 						 sizeof(struct page *),
1758 						 GFP_KERNEL | __GFP_ZERO);
1759 			if (!mem->user_pages) {
1760 				pr_err("%s: Failed to allocate pages array\n",
1761 				       __func__);
1762 				return -ENOMEM;
1763 			}
1764 		} else if (mem->user_pages[0]) {
1765 			release_pages(mem->user_pages, bo->tbo.ttm->num_pages);
1766 		}
1767 
1768 		/* Get updated user pages */
1769 		ret = amdgpu_ttm_tt_get_user_pages(bo->tbo.ttm,
1770 						   mem->user_pages);
1771 		if (ret) {
1772 			mem->user_pages[0] = NULL;
1773 			pr_info("%s: Failed to get user pages: %d\n",
1774 				__func__, ret);
1775 			/* Pretend it succeeded. It will fail later
1776 			 * with a VM fault if the GPU tries to access
1777 			 * it. Better than hanging indefinitely with
1778 			 * stalled user mode queues.
1779 			 */
1780 		}
1781 
1782 		/* Mark the BO as valid unless it was invalidated
1783 		 * again concurrently
1784 		 */
1785 		if (atomic_cmpxchg(&mem->invalid, invalid, 0) != invalid)
1786 			return -EAGAIN;
1787 	}
1788 
1789 	return 0;
1790 }
1791 
1792 /* Validate invalid userptr BOs
1793  *
1794  * Validates BOs on the userptr_inval_list, and moves them back to the
1795  * userptr_valid_list. Also updates GPUVM page tables with new page
1796  * addresses and waits for the page table updates to complete.
1797  */
1798 static int validate_invalid_user_pages(struct amdkfd_process_info *process_info)
1799 {
1800 	struct amdgpu_bo_list_entry *pd_bo_list_entries;
1801 	struct list_head resv_list, duplicates;
1802 	struct ww_acquire_ctx ticket;
1803 	struct amdgpu_sync sync;
1804 
1805 	struct amdgpu_vm *peer_vm;
1806 	struct kgd_mem *mem, *tmp_mem;
1807 	struct amdgpu_bo *bo;
1808 	struct ttm_operation_ctx ctx = { false, false };
1809 	int i, ret;
1810 
1811 	pd_bo_list_entries = kcalloc(process_info->n_vms,
1812 				     sizeof(struct amdgpu_bo_list_entry),
1813 				     GFP_KERNEL);
1814 	if (!pd_bo_list_entries) {
1815 		pr_err("%s: Failed to allocate PD BO list entries\n", __func__);
1816 		return -ENOMEM;
1817 	}
1818 
1819 	INIT_LIST_HEAD(&resv_list);
1820 	INIT_LIST_HEAD(&duplicates);
1821 
1822 	/* Get all the page directory BOs that need to be reserved */
1823 	i = 0;
1824 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
1825 			    vm_list_node)
1826 		amdgpu_vm_get_pd_bo(peer_vm, &resv_list,
1827 				    &pd_bo_list_entries[i++]);
1828 	/* Add the userptr_inval_list entries to resv_list */
1829 	list_for_each_entry(mem, &process_info->userptr_inval_list,
1830 			    validate_list.head) {
1831 		list_add_tail(&mem->resv_list.head, &resv_list);
1832 		mem->resv_list.bo = mem->validate_list.bo;
1833 		mem->resv_list.shared = mem->validate_list.shared;
1834 	}
1835 
1836 	/* Reserve all BOs and page tables for validation */
1837 	ret = ttm_eu_reserve_buffers(&ticket, &resv_list, false, &duplicates);
1838 	WARN(!list_empty(&duplicates), "Duplicates should be empty");
1839 	if (ret)
1840 		goto out;
1841 
1842 	amdgpu_sync_create(&sync);
1843 
1844 	/* Avoid triggering eviction fences when unmapping invalid
1845 	 * userptr BOs (waits for all fences, doesn't use
1846 	 * FENCE_OWNER_VM)
1847 	 */
1848 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
1849 			    vm_list_node)
1850 		amdgpu_amdkfd_remove_eviction_fence(peer_vm->root.base.bo,
1851 						process_info->eviction_fence,
1852 						NULL, NULL);
1853 
1854 	ret = process_validate_vms(process_info);
1855 	if (ret)
1856 		goto unreserve_out;
1857 
1858 	/* Validate BOs and update GPUVM page tables */
1859 	list_for_each_entry_safe(mem, tmp_mem,
1860 				 &process_info->userptr_inval_list,
1861 				 validate_list.head) {
1862 		struct kfd_bo_va_list *bo_va_entry;
1863 
1864 		bo = mem->bo;
1865 
1866 		/* Copy pages array and validate the BO if we got user pages */
1867 		if (mem->user_pages[0]) {
1868 			amdgpu_ttm_tt_set_user_pages(bo->tbo.ttm,
1869 						     mem->user_pages);
1870 			amdgpu_bo_placement_from_domain(bo, mem->domain);
1871 			ret = ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
1872 			if (ret) {
1873 				pr_err("%s: failed to validate BO\n", __func__);
1874 				goto unreserve_out;
1875 			}
1876 		}
1877 
1878 		/* Validate succeeded, now the BO owns the pages, free
1879 		 * our copy of the pointer array. Put this BO back on
1880 		 * the userptr_valid_list. If we need to revalidate
1881 		 * it, we need to start from scratch.
1882 		 */
1883 		kvfree(mem->user_pages);
1884 		mem->user_pages = NULL;
1885 		list_move_tail(&mem->validate_list.head,
1886 			       &process_info->userptr_valid_list);
1887 
1888 		/* Update mapping. If the BO was not validated
1889 		 * (because we couldn't get user pages), this will
1890 		 * clear the page table entries, which will result in
1891 		 * VM faults if the GPU tries to access the invalid
1892 		 * memory.
1893 		 */
1894 		list_for_each_entry(bo_va_entry, &mem->bo_va_list, bo_list) {
1895 			if (!bo_va_entry->is_mapped)
1896 				continue;
1897 
1898 			ret = update_gpuvm_pte((struct amdgpu_device *)
1899 					       bo_va_entry->kgd_dev,
1900 					       bo_va_entry, &sync);
1901 			if (ret) {
1902 				pr_err("%s: update PTE failed\n", __func__);
1903 				/* make sure this gets validated again */
1904 				atomic_inc(&mem->invalid);
1905 				goto unreserve_out;
1906 			}
1907 		}
1908 	}
1909 
1910 	/* Update page directories */
1911 	ret = process_update_pds(process_info, &sync);
1912 
1913 unreserve_out:
1914 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
1915 			    vm_list_node)
1916 		amdgpu_bo_fence(peer_vm->root.base.bo,
1917 				&process_info->eviction_fence->base, true);
1918 	ttm_eu_backoff_reservation(&ticket, &resv_list);
1919 	amdgpu_sync_wait(&sync, false);
1920 	amdgpu_sync_free(&sync);
1921 out:
1922 	kfree(pd_bo_list_entries);
1923 
1924 	return ret;
1925 }
1926 
1927 /* Worker callback to restore evicted userptr BOs
1928  *
1929  * Tries to update and validate all userptr BOs. If successful and no
1930  * concurrent evictions happened, the queues are restarted. Otherwise,
1931  * reschedule for another attempt later.
1932  */
1933 static void amdgpu_amdkfd_restore_userptr_worker(struct work_struct *work)
1934 {
1935 	struct delayed_work *dwork = to_delayed_work(work);
1936 	struct amdkfd_process_info *process_info =
1937 		container_of(dwork, struct amdkfd_process_info,
1938 			     restore_userptr_work);
1939 	struct task_struct *usertask;
1940 	struct mm_struct *mm;
1941 	int evicted_bos;
1942 
1943 	evicted_bos = atomic_read(&process_info->evicted_bos);
1944 	if (!evicted_bos)
1945 		return;
1946 
1947 	/* Reference task and mm in case of concurrent process termination */
1948 	usertask = get_pid_task(process_info->pid, PIDTYPE_PID);
1949 	if (!usertask)
1950 		return;
1951 	mm = get_task_mm(usertask);
1952 	if (!mm) {
1953 		put_task_struct(usertask);
1954 		return;
1955 	}
1956 
1957 	mutex_lock(&process_info->lock);
1958 
1959 	if (update_invalid_user_pages(process_info, mm))
1960 		goto unlock_out;
1961 	/* userptr_inval_list can be empty if all evicted userptr BOs
1962 	 * have been freed. In that case there is nothing to validate
1963 	 * and we can just restart the queues.
1964 	 */
1965 	if (!list_empty(&process_info->userptr_inval_list)) {
1966 		if (atomic_read(&process_info->evicted_bos) != evicted_bos)
1967 			goto unlock_out; /* Concurrent eviction, try again */
1968 
1969 		if (validate_invalid_user_pages(process_info))
1970 			goto unlock_out;
1971 	}
1972 	/* Final check for concurrent evicton and atomic update. If
1973 	 * another eviction happens after successful update, it will
1974 	 * be a first eviction that calls quiesce_mm. The eviction
1975 	 * reference counting inside KFD will handle this case.
1976 	 */
1977 	if (atomic_cmpxchg(&process_info->evicted_bos, evicted_bos, 0) !=
1978 	    evicted_bos)
1979 		goto unlock_out;
1980 	evicted_bos = 0;
1981 	if (kgd2kfd->resume_mm(mm)) {
1982 		pr_err("%s: Failed to resume KFD\n", __func__);
1983 		/* No recovery from this failure. Probably the CP is
1984 		 * hanging. No point trying again.
1985 		 */
1986 	}
1987 unlock_out:
1988 	mutex_unlock(&process_info->lock);
1989 	mmput(mm);
1990 	put_task_struct(usertask);
1991 
1992 	/* If validation failed, reschedule another attempt */
1993 	if (evicted_bos)
1994 		schedule_delayed_work(&process_info->restore_userptr_work,
1995 			msecs_to_jiffies(AMDGPU_USERPTR_RESTORE_DELAY_MS));
1996 }
1997 
1998 /** amdgpu_amdkfd_gpuvm_restore_process_bos - Restore all BOs for the given
1999  *   KFD process identified by process_info
2000  *
2001  * @process_info: amdkfd_process_info of the KFD process
2002  *
2003  * After memory eviction, restore thread calls this function. The function
2004  * should be called when the Process is still valid. BO restore involves -
2005  *
2006  * 1.  Release old eviction fence and create new one
2007  * 2.  Get two copies of PD BO list from all the VMs. Keep one copy as pd_list.
2008  * 3   Use the second PD list and kfd_bo_list to create a list (ctx.list) of
2009  *     BOs that need to be reserved.
2010  * 4.  Reserve all the BOs
2011  * 5.  Validate of PD and PT BOs.
2012  * 6.  Validate all KFD BOs using kfd_bo_list and Map them and add new fence
2013  * 7.  Add fence to all PD and PT BOs.
2014  * 8.  Unreserve all BOs
2015  */
2016 int amdgpu_amdkfd_gpuvm_restore_process_bos(void *info, struct dma_fence **ef)
2017 {
2018 	struct amdgpu_bo_list_entry *pd_bo_list;
2019 	struct amdkfd_process_info *process_info = info;
2020 	struct amdgpu_vm *peer_vm;
2021 	struct kgd_mem *mem;
2022 	struct bo_vm_reservation_context ctx;
2023 	struct amdgpu_amdkfd_fence *new_fence;
2024 	int ret = 0, i;
2025 	struct list_head duplicate_save;
2026 	struct amdgpu_sync sync_obj;
2027 
2028 	INIT_LIST_HEAD(&duplicate_save);
2029 	INIT_LIST_HEAD(&ctx.list);
2030 	INIT_LIST_HEAD(&ctx.duplicates);
2031 
2032 	pd_bo_list = kcalloc(process_info->n_vms,
2033 			     sizeof(struct amdgpu_bo_list_entry),
2034 			     GFP_KERNEL);
2035 	if (!pd_bo_list)
2036 		return -ENOMEM;
2037 
2038 	i = 0;
2039 	mutex_lock(&process_info->lock);
2040 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2041 			vm_list_node)
2042 		amdgpu_vm_get_pd_bo(peer_vm, &ctx.list, &pd_bo_list[i++]);
2043 
2044 	/* Reserve all BOs and page tables/directory. Add all BOs from
2045 	 * kfd_bo_list to ctx.list
2046 	 */
2047 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2048 			    validate_list.head) {
2049 
2050 		list_add_tail(&mem->resv_list.head, &ctx.list);
2051 		mem->resv_list.bo = mem->validate_list.bo;
2052 		mem->resv_list.shared = mem->validate_list.shared;
2053 	}
2054 
2055 	ret = ttm_eu_reserve_buffers(&ctx.ticket, &ctx.list,
2056 				     false, &duplicate_save);
2057 	if (ret) {
2058 		pr_debug("Memory eviction: TTM Reserve Failed. Try again\n");
2059 		goto ttm_reserve_fail;
2060 	}
2061 
2062 	amdgpu_sync_create(&sync_obj);
2063 
2064 	/* Validate PDs and PTs */
2065 	ret = process_validate_vms(process_info);
2066 	if (ret)
2067 		goto validate_map_fail;
2068 
2069 	ret = process_sync_pds_resv(process_info, &sync_obj);
2070 	if (ret) {
2071 		pr_debug("Memory eviction: Failed to sync to PD BO moving fence. Try again\n");
2072 		goto validate_map_fail;
2073 	}
2074 
2075 	/* Validate BOs and map them to GPUVM (update VM page tables). */
2076 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2077 			    validate_list.head) {
2078 
2079 		struct amdgpu_bo *bo = mem->bo;
2080 		uint32_t domain = mem->domain;
2081 		struct kfd_bo_va_list *bo_va_entry;
2082 
2083 		ret = amdgpu_amdkfd_bo_validate(bo, domain, false);
2084 		if (ret) {
2085 			pr_debug("Memory eviction: Validate BOs failed. Try again\n");
2086 			goto validate_map_fail;
2087 		}
2088 		ret = amdgpu_sync_fence(NULL, &sync_obj, bo->tbo.moving, false);
2089 		if (ret) {
2090 			pr_debug("Memory eviction: Sync BO fence failed. Try again\n");
2091 			goto validate_map_fail;
2092 		}
2093 		list_for_each_entry(bo_va_entry, &mem->bo_va_list,
2094 				    bo_list) {
2095 			ret = update_gpuvm_pte((struct amdgpu_device *)
2096 					      bo_va_entry->kgd_dev,
2097 					      bo_va_entry,
2098 					      &sync_obj);
2099 			if (ret) {
2100 				pr_debug("Memory eviction: update PTE failed. Try again\n");
2101 				goto validate_map_fail;
2102 			}
2103 		}
2104 	}
2105 
2106 	/* Update page directories */
2107 	ret = process_update_pds(process_info, &sync_obj);
2108 	if (ret) {
2109 		pr_debug("Memory eviction: update PDs failed. Try again\n");
2110 		goto validate_map_fail;
2111 	}
2112 
2113 	/* Wait for validate and PT updates to finish */
2114 	amdgpu_sync_wait(&sync_obj, false);
2115 
2116 	/* Release old eviction fence and create new one, because fence only
2117 	 * goes from unsignaled to signaled, fence cannot be reused.
2118 	 * Use context and mm from the old fence.
2119 	 */
2120 	new_fence = amdgpu_amdkfd_fence_create(
2121 				process_info->eviction_fence->base.context,
2122 				process_info->eviction_fence->mm);
2123 	if (!new_fence) {
2124 		pr_err("Failed to create eviction fence\n");
2125 		ret = -ENOMEM;
2126 		goto validate_map_fail;
2127 	}
2128 	dma_fence_put(&process_info->eviction_fence->base);
2129 	process_info->eviction_fence = new_fence;
2130 	*ef = dma_fence_get(&new_fence->base);
2131 
2132 	/* Attach new eviction fence to all BOs */
2133 	list_for_each_entry(mem, &process_info->kfd_bo_list,
2134 		validate_list.head)
2135 		amdgpu_bo_fence(mem->bo,
2136 			&process_info->eviction_fence->base, true);
2137 
2138 	/* Attach eviction fence to PD / PT BOs */
2139 	list_for_each_entry(peer_vm, &process_info->vm_list_head,
2140 			    vm_list_node) {
2141 		struct amdgpu_bo *bo = peer_vm->root.base.bo;
2142 
2143 		amdgpu_bo_fence(bo, &process_info->eviction_fence->base, true);
2144 	}
2145 
2146 validate_map_fail:
2147 	ttm_eu_backoff_reservation(&ctx.ticket, &ctx.list);
2148 	amdgpu_sync_free(&sync_obj);
2149 ttm_reserve_fail:
2150 	mutex_unlock(&process_info->lock);
2151 	kfree(pd_bo_list);
2152 	return ret;
2153 }
2154