xref: /openbmc/linux/drivers/gpu/drm/amd/amdkfd/kfd_svm.c (revision 3ddc8b84)
1 // SPDX-License-Identifier: GPL-2.0 OR MIT
2 /*
3  * Copyright 2020-2021 Advanced Micro Devices, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in
13  * all copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
19  * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21  * OTHER DEALINGS IN THE SOFTWARE.
22  */
23 
24 #include <linux/types.h>
25 #include <linux/sched/task.h>
26 #include <linux/dynamic_debug.h>
27 #include <drm/ttm/ttm_tt.h>
28 #include <drm/drm_exec.h>
29 
30 #include "amdgpu_sync.h"
31 #include "amdgpu_object.h"
32 #include "amdgpu_vm.h"
33 #include "amdgpu_hmm.h"
34 #include "amdgpu.h"
35 #include "amdgpu_xgmi.h"
36 #include "kfd_priv.h"
37 #include "kfd_svm.h"
38 #include "kfd_migrate.h"
39 #include "kfd_smi_events.h"
40 
41 #ifdef dev_fmt
42 #undef dev_fmt
43 #endif
44 #define dev_fmt(fmt) "kfd_svm: %s: " fmt, __func__
45 
46 #define AMDGPU_SVM_RANGE_RESTORE_DELAY_MS 1
47 
48 /* Long enough to ensure no retry fault comes after svm range is restored and
49  * page table is updated.
50  */
51 #define AMDGPU_SVM_RANGE_RETRY_FAULT_PENDING	(2UL * NSEC_PER_MSEC)
52 #if IS_ENABLED(CONFIG_DYNAMIC_DEBUG)
53 #define dynamic_svm_range_dump(svms) \
54 	_dynamic_func_call_no_desc("svm_range_dump", svm_range_debug_dump, svms)
55 #else
56 #define dynamic_svm_range_dump(svms) \
57 	do { if (0) svm_range_debug_dump(svms); } while (0)
58 #endif
59 
60 /* Giant svm range split into smaller ranges based on this, it is decided using
61  * minimum of all dGPU/APU 1/32 VRAM size, between 2MB to 1GB and alignment to
62  * power of 2MB.
63  */
64 static uint64_t max_svm_range_pages;
65 
66 struct criu_svm_metadata {
67 	struct list_head list;
68 	struct kfd_criu_svm_range_priv_data data;
69 };
70 
71 static void svm_range_evict_svm_bo_worker(struct work_struct *work);
72 static bool
73 svm_range_cpu_invalidate_pagetables(struct mmu_interval_notifier *mni,
74 				    const struct mmu_notifier_range *range,
75 				    unsigned long cur_seq);
76 static int
77 svm_range_check_vm(struct kfd_process *p, uint64_t start, uint64_t last,
78 		   uint64_t *bo_s, uint64_t *bo_l);
79 static const struct mmu_interval_notifier_ops svm_range_mn_ops = {
80 	.invalidate = svm_range_cpu_invalidate_pagetables,
81 };
82 
83 /**
84  * svm_range_unlink - unlink svm_range from lists and interval tree
85  * @prange: svm range structure to be removed
86  *
87  * Remove the svm_range from the svms and svm_bo lists and the svms
88  * interval tree.
89  *
90  * Context: The caller must hold svms->lock
91  */
92 static void svm_range_unlink(struct svm_range *prange)
93 {
94 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx]\n", prange->svms,
95 		 prange, prange->start, prange->last);
96 
97 	if (prange->svm_bo) {
98 		spin_lock(&prange->svm_bo->list_lock);
99 		list_del(&prange->svm_bo_list);
100 		spin_unlock(&prange->svm_bo->list_lock);
101 	}
102 
103 	list_del(&prange->list);
104 	if (prange->it_node.start != 0 && prange->it_node.last != 0)
105 		interval_tree_remove(&prange->it_node, &prange->svms->objects);
106 }
107 
108 static void
109 svm_range_add_notifier_locked(struct mm_struct *mm, struct svm_range *prange)
110 {
111 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx]\n", prange->svms,
112 		 prange, prange->start, prange->last);
113 
114 	mmu_interval_notifier_insert_locked(&prange->notifier, mm,
115 				     prange->start << PAGE_SHIFT,
116 				     prange->npages << PAGE_SHIFT,
117 				     &svm_range_mn_ops);
118 }
119 
120 /**
121  * svm_range_add_to_svms - add svm range to svms
122  * @prange: svm range structure to be added
123  *
124  * Add the svm range to svms interval tree and link list
125  *
126  * Context: The caller must hold svms->lock
127  */
128 static void svm_range_add_to_svms(struct svm_range *prange)
129 {
130 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx]\n", prange->svms,
131 		 prange, prange->start, prange->last);
132 
133 	list_move_tail(&prange->list, &prange->svms->list);
134 	prange->it_node.start = prange->start;
135 	prange->it_node.last = prange->last;
136 	interval_tree_insert(&prange->it_node, &prange->svms->objects);
137 }
138 
139 static void svm_range_remove_notifier(struct svm_range *prange)
140 {
141 	pr_debug("remove notifier svms 0x%p prange 0x%p [0x%lx 0x%lx]\n",
142 		 prange->svms, prange,
143 		 prange->notifier.interval_tree.start >> PAGE_SHIFT,
144 		 prange->notifier.interval_tree.last >> PAGE_SHIFT);
145 
146 	if (prange->notifier.interval_tree.start != 0 &&
147 	    prange->notifier.interval_tree.last != 0)
148 		mmu_interval_notifier_remove(&prange->notifier);
149 }
150 
151 static bool
152 svm_is_valid_dma_mapping_addr(struct device *dev, dma_addr_t dma_addr)
153 {
154 	return dma_addr && !dma_mapping_error(dev, dma_addr) &&
155 	       !(dma_addr & SVM_RANGE_VRAM_DOMAIN);
156 }
157 
158 static int
159 svm_range_dma_map_dev(struct amdgpu_device *adev, struct svm_range *prange,
160 		      unsigned long offset, unsigned long npages,
161 		      unsigned long *hmm_pfns, uint32_t gpuidx)
162 {
163 	enum dma_data_direction dir = DMA_BIDIRECTIONAL;
164 	dma_addr_t *addr = prange->dma_addr[gpuidx];
165 	struct device *dev = adev->dev;
166 	struct page *page;
167 	int i, r;
168 
169 	if (!addr) {
170 		addr = kvcalloc(prange->npages, sizeof(*addr), GFP_KERNEL);
171 		if (!addr)
172 			return -ENOMEM;
173 		prange->dma_addr[gpuidx] = addr;
174 	}
175 
176 	addr += offset;
177 	for (i = 0; i < npages; i++) {
178 		if (svm_is_valid_dma_mapping_addr(dev, addr[i]))
179 			dma_unmap_page(dev, addr[i], PAGE_SIZE, dir);
180 
181 		page = hmm_pfn_to_page(hmm_pfns[i]);
182 		if (is_zone_device_page(page)) {
183 			struct amdgpu_device *bo_adev = prange->svm_bo->node->adev;
184 
185 			addr[i] = (hmm_pfns[i] << PAGE_SHIFT) +
186 				   bo_adev->vm_manager.vram_base_offset -
187 				   bo_adev->kfd.pgmap.range.start;
188 			addr[i] |= SVM_RANGE_VRAM_DOMAIN;
189 			pr_debug_ratelimited("vram address: 0x%llx\n", addr[i]);
190 			continue;
191 		}
192 		addr[i] = dma_map_page(dev, page, 0, PAGE_SIZE, dir);
193 		r = dma_mapping_error(dev, addr[i]);
194 		if (r) {
195 			dev_err(dev, "failed %d dma_map_page\n", r);
196 			return r;
197 		}
198 		pr_debug_ratelimited("dma mapping 0x%llx for page addr 0x%lx\n",
199 				     addr[i] >> PAGE_SHIFT, page_to_pfn(page));
200 	}
201 	return 0;
202 }
203 
204 static int
205 svm_range_dma_map(struct svm_range *prange, unsigned long *bitmap,
206 		  unsigned long offset, unsigned long npages,
207 		  unsigned long *hmm_pfns)
208 {
209 	struct kfd_process *p;
210 	uint32_t gpuidx;
211 	int r;
212 
213 	p = container_of(prange->svms, struct kfd_process, svms);
214 
215 	for_each_set_bit(gpuidx, bitmap, MAX_GPU_INSTANCE) {
216 		struct kfd_process_device *pdd;
217 
218 		pr_debug("mapping to gpu idx 0x%x\n", gpuidx);
219 		pdd = kfd_process_device_from_gpuidx(p, gpuidx);
220 		if (!pdd) {
221 			pr_debug("failed to find device idx %d\n", gpuidx);
222 			return -EINVAL;
223 		}
224 
225 		r = svm_range_dma_map_dev(pdd->dev->adev, prange, offset, npages,
226 					  hmm_pfns, gpuidx);
227 		if (r)
228 			break;
229 	}
230 
231 	return r;
232 }
233 
234 void svm_range_dma_unmap(struct device *dev, dma_addr_t *dma_addr,
235 			 unsigned long offset, unsigned long npages)
236 {
237 	enum dma_data_direction dir = DMA_BIDIRECTIONAL;
238 	int i;
239 
240 	if (!dma_addr)
241 		return;
242 
243 	for (i = offset; i < offset + npages; i++) {
244 		if (!svm_is_valid_dma_mapping_addr(dev, dma_addr[i]))
245 			continue;
246 		pr_debug_ratelimited("unmap 0x%llx\n", dma_addr[i] >> PAGE_SHIFT);
247 		dma_unmap_page(dev, dma_addr[i], PAGE_SIZE, dir);
248 		dma_addr[i] = 0;
249 	}
250 }
251 
252 void svm_range_free_dma_mappings(struct svm_range *prange, bool unmap_dma)
253 {
254 	struct kfd_process_device *pdd;
255 	dma_addr_t *dma_addr;
256 	struct device *dev;
257 	struct kfd_process *p;
258 	uint32_t gpuidx;
259 
260 	p = container_of(prange->svms, struct kfd_process, svms);
261 
262 	for (gpuidx = 0; gpuidx < MAX_GPU_INSTANCE; gpuidx++) {
263 		dma_addr = prange->dma_addr[gpuidx];
264 		if (!dma_addr)
265 			continue;
266 
267 		pdd = kfd_process_device_from_gpuidx(p, gpuidx);
268 		if (!pdd) {
269 			pr_debug("failed to find device idx %d\n", gpuidx);
270 			continue;
271 		}
272 		dev = &pdd->dev->adev->pdev->dev;
273 		if (unmap_dma)
274 			svm_range_dma_unmap(dev, dma_addr, 0, prange->npages);
275 		kvfree(dma_addr);
276 		prange->dma_addr[gpuidx] = NULL;
277 	}
278 }
279 
280 static void svm_range_free(struct svm_range *prange, bool do_unmap)
281 {
282 	uint64_t size = (prange->last - prange->start + 1) << PAGE_SHIFT;
283 	struct kfd_process *p = container_of(prange->svms, struct kfd_process, svms);
284 
285 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx]\n", prange->svms, prange,
286 		 prange->start, prange->last);
287 
288 	svm_range_vram_node_free(prange);
289 	svm_range_free_dma_mappings(prange, do_unmap);
290 
291 	if (do_unmap && !p->xnack_enabled) {
292 		pr_debug("unreserve prange 0x%p size: 0x%llx\n", prange, size);
293 		amdgpu_amdkfd_unreserve_mem_limit(NULL, size,
294 					KFD_IOC_ALLOC_MEM_FLAGS_USERPTR, 0);
295 	}
296 	mutex_destroy(&prange->lock);
297 	mutex_destroy(&prange->migrate_mutex);
298 	kfree(prange);
299 }
300 
301 static void
302 svm_range_set_default_attributes(int32_t *location, int32_t *prefetch_loc,
303 				 uint8_t *granularity, uint32_t *flags)
304 {
305 	*location = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
306 	*prefetch_loc = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
307 	*granularity = 9;
308 	*flags =
309 		KFD_IOCTL_SVM_FLAG_HOST_ACCESS | KFD_IOCTL_SVM_FLAG_COHERENT;
310 }
311 
312 static struct
313 svm_range *svm_range_new(struct svm_range_list *svms, uint64_t start,
314 			 uint64_t last, bool update_mem_usage)
315 {
316 	uint64_t size = last - start + 1;
317 	struct svm_range *prange;
318 	struct kfd_process *p;
319 
320 	prange = kzalloc(sizeof(*prange), GFP_KERNEL);
321 	if (!prange)
322 		return NULL;
323 
324 	p = container_of(svms, struct kfd_process, svms);
325 	if (!p->xnack_enabled && update_mem_usage &&
326 	    amdgpu_amdkfd_reserve_mem_limit(NULL, size << PAGE_SHIFT,
327 				    KFD_IOC_ALLOC_MEM_FLAGS_USERPTR, 0)) {
328 		pr_info("SVM mapping failed, exceeds resident system memory limit\n");
329 		kfree(prange);
330 		return NULL;
331 	}
332 	prange->npages = size;
333 	prange->svms = svms;
334 	prange->start = start;
335 	prange->last = last;
336 	INIT_LIST_HEAD(&prange->list);
337 	INIT_LIST_HEAD(&prange->update_list);
338 	INIT_LIST_HEAD(&prange->svm_bo_list);
339 	INIT_LIST_HEAD(&prange->deferred_list);
340 	INIT_LIST_HEAD(&prange->child_list);
341 	atomic_set(&prange->invalid, 0);
342 	prange->validate_timestamp = 0;
343 	mutex_init(&prange->migrate_mutex);
344 	mutex_init(&prange->lock);
345 
346 	if (p->xnack_enabled)
347 		bitmap_copy(prange->bitmap_access, svms->bitmap_supported,
348 			    MAX_GPU_INSTANCE);
349 
350 	svm_range_set_default_attributes(&prange->preferred_loc,
351 					 &prange->prefetch_loc,
352 					 &prange->granularity, &prange->flags);
353 
354 	pr_debug("svms 0x%p [0x%llx 0x%llx]\n", svms, start, last);
355 
356 	return prange;
357 }
358 
359 static bool svm_bo_ref_unless_zero(struct svm_range_bo *svm_bo)
360 {
361 	if (!svm_bo || !kref_get_unless_zero(&svm_bo->kref))
362 		return false;
363 
364 	return true;
365 }
366 
367 static void svm_range_bo_release(struct kref *kref)
368 {
369 	struct svm_range_bo *svm_bo;
370 
371 	svm_bo = container_of(kref, struct svm_range_bo, kref);
372 	pr_debug("svm_bo 0x%p\n", svm_bo);
373 
374 	spin_lock(&svm_bo->list_lock);
375 	while (!list_empty(&svm_bo->range_list)) {
376 		struct svm_range *prange =
377 				list_first_entry(&svm_bo->range_list,
378 						struct svm_range, svm_bo_list);
379 		/* list_del_init tells a concurrent svm_range_vram_node_new when
380 		 * it's safe to reuse the svm_bo pointer and svm_bo_list head.
381 		 */
382 		list_del_init(&prange->svm_bo_list);
383 		spin_unlock(&svm_bo->list_lock);
384 
385 		pr_debug("svms 0x%p [0x%lx 0x%lx]\n", prange->svms,
386 			 prange->start, prange->last);
387 		mutex_lock(&prange->lock);
388 		prange->svm_bo = NULL;
389 		mutex_unlock(&prange->lock);
390 
391 		spin_lock(&svm_bo->list_lock);
392 	}
393 	spin_unlock(&svm_bo->list_lock);
394 	if (!dma_fence_is_signaled(&svm_bo->eviction_fence->base)) {
395 		/* We're not in the eviction worker.
396 		 * Signal the fence and synchronize with any
397 		 * pending eviction work.
398 		 */
399 		dma_fence_signal(&svm_bo->eviction_fence->base);
400 		cancel_work_sync(&svm_bo->eviction_work);
401 	}
402 	dma_fence_put(&svm_bo->eviction_fence->base);
403 	amdgpu_bo_unref(&svm_bo->bo);
404 	kfree(svm_bo);
405 }
406 
407 static void svm_range_bo_wq_release(struct work_struct *work)
408 {
409 	struct svm_range_bo *svm_bo;
410 
411 	svm_bo = container_of(work, struct svm_range_bo, release_work);
412 	svm_range_bo_release(&svm_bo->kref);
413 }
414 
415 static void svm_range_bo_release_async(struct kref *kref)
416 {
417 	struct svm_range_bo *svm_bo;
418 
419 	svm_bo = container_of(kref, struct svm_range_bo, kref);
420 	pr_debug("svm_bo 0x%p\n", svm_bo);
421 	INIT_WORK(&svm_bo->release_work, svm_range_bo_wq_release);
422 	schedule_work(&svm_bo->release_work);
423 }
424 
425 void svm_range_bo_unref_async(struct svm_range_bo *svm_bo)
426 {
427 	kref_put(&svm_bo->kref, svm_range_bo_release_async);
428 }
429 
430 static void svm_range_bo_unref(struct svm_range_bo *svm_bo)
431 {
432 	if (svm_bo)
433 		kref_put(&svm_bo->kref, svm_range_bo_release);
434 }
435 
436 static bool
437 svm_range_validate_svm_bo(struct kfd_node *node, struct svm_range *prange)
438 {
439 	mutex_lock(&prange->lock);
440 	if (!prange->svm_bo) {
441 		mutex_unlock(&prange->lock);
442 		return false;
443 	}
444 	if (prange->ttm_res) {
445 		/* We still have a reference, all is well */
446 		mutex_unlock(&prange->lock);
447 		return true;
448 	}
449 	if (svm_bo_ref_unless_zero(prange->svm_bo)) {
450 		/*
451 		 * Migrate from GPU to GPU, remove range from source svm_bo->node
452 		 * range list, and return false to allocate svm_bo from destination
453 		 * node.
454 		 */
455 		if (prange->svm_bo->node != node) {
456 			mutex_unlock(&prange->lock);
457 
458 			spin_lock(&prange->svm_bo->list_lock);
459 			list_del_init(&prange->svm_bo_list);
460 			spin_unlock(&prange->svm_bo->list_lock);
461 
462 			svm_range_bo_unref(prange->svm_bo);
463 			return false;
464 		}
465 		if (READ_ONCE(prange->svm_bo->evicting)) {
466 			struct dma_fence *f;
467 			struct svm_range_bo *svm_bo;
468 			/* The BO is getting evicted,
469 			 * we need to get a new one
470 			 */
471 			mutex_unlock(&prange->lock);
472 			svm_bo = prange->svm_bo;
473 			f = dma_fence_get(&svm_bo->eviction_fence->base);
474 			svm_range_bo_unref(prange->svm_bo);
475 			/* wait for the fence to avoid long spin-loop
476 			 * at list_empty_careful
477 			 */
478 			dma_fence_wait(f, false);
479 			dma_fence_put(f);
480 		} else {
481 			/* The BO was still around and we got
482 			 * a new reference to it
483 			 */
484 			mutex_unlock(&prange->lock);
485 			pr_debug("reuse old bo svms 0x%p [0x%lx 0x%lx]\n",
486 				 prange->svms, prange->start, prange->last);
487 
488 			prange->ttm_res = prange->svm_bo->bo->tbo.resource;
489 			return true;
490 		}
491 
492 	} else {
493 		mutex_unlock(&prange->lock);
494 	}
495 
496 	/* We need a new svm_bo. Spin-loop to wait for concurrent
497 	 * svm_range_bo_release to finish removing this range from
498 	 * its range list and set prange->svm_bo to null. After this,
499 	 * it is safe to reuse the svm_bo pointer and svm_bo_list head.
500 	 */
501 	while (!list_empty_careful(&prange->svm_bo_list) || prange->svm_bo)
502 		cond_resched();
503 
504 	return false;
505 }
506 
507 static struct svm_range_bo *svm_range_bo_new(void)
508 {
509 	struct svm_range_bo *svm_bo;
510 
511 	svm_bo = kzalloc(sizeof(*svm_bo), GFP_KERNEL);
512 	if (!svm_bo)
513 		return NULL;
514 
515 	kref_init(&svm_bo->kref);
516 	INIT_LIST_HEAD(&svm_bo->range_list);
517 	spin_lock_init(&svm_bo->list_lock);
518 
519 	return svm_bo;
520 }
521 
522 int
523 svm_range_vram_node_new(struct kfd_node *node, struct svm_range *prange,
524 			bool clear)
525 {
526 	struct amdgpu_bo_param bp;
527 	struct svm_range_bo *svm_bo;
528 	struct amdgpu_bo_user *ubo;
529 	struct amdgpu_bo *bo;
530 	struct kfd_process *p;
531 	struct mm_struct *mm;
532 	int r;
533 
534 	p = container_of(prange->svms, struct kfd_process, svms);
535 	pr_debug("pasid: %x svms 0x%p [0x%lx 0x%lx]\n", p->pasid, prange->svms,
536 		 prange->start, prange->last);
537 
538 	if (svm_range_validate_svm_bo(node, prange))
539 		return 0;
540 
541 	svm_bo = svm_range_bo_new();
542 	if (!svm_bo) {
543 		pr_debug("failed to alloc svm bo\n");
544 		return -ENOMEM;
545 	}
546 	mm = get_task_mm(p->lead_thread);
547 	if (!mm) {
548 		pr_debug("failed to get mm\n");
549 		kfree(svm_bo);
550 		return -ESRCH;
551 	}
552 	svm_bo->node = node;
553 	svm_bo->eviction_fence =
554 		amdgpu_amdkfd_fence_create(dma_fence_context_alloc(1),
555 					   mm,
556 					   svm_bo);
557 	mmput(mm);
558 	INIT_WORK(&svm_bo->eviction_work, svm_range_evict_svm_bo_worker);
559 	svm_bo->evicting = 0;
560 	memset(&bp, 0, sizeof(bp));
561 	bp.size = prange->npages * PAGE_SIZE;
562 	bp.byte_align = PAGE_SIZE;
563 	bp.domain = AMDGPU_GEM_DOMAIN_VRAM;
564 	bp.flags = AMDGPU_GEM_CREATE_NO_CPU_ACCESS;
565 	bp.flags |= clear ? AMDGPU_GEM_CREATE_VRAM_CLEARED : 0;
566 	bp.flags |= AMDGPU_GEM_CREATE_DISCARDABLE;
567 	bp.type = ttm_bo_type_device;
568 	bp.resv = NULL;
569 	if (node->xcp)
570 		bp.xcp_id_plus1 = node->xcp->id + 1;
571 
572 	r = amdgpu_bo_create_user(node->adev, &bp, &ubo);
573 	if (r) {
574 		pr_debug("failed %d to create bo\n", r);
575 		goto create_bo_failed;
576 	}
577 	bo = &ubo->bo;
578 
579 	pr_debug("alloc bo at offset 0x%lx size 0x%lx on partition %d\n",
580 		 bo->tbo.resource->start << PAGE_SHIFT, bp.size,
581 		 bp.xcp_id_plus1 - 1);
582 
583 	r = amdgpu_bo_reserve(bo, true);
584 	if (r) {
585 		pr_debug("failed %d to reserve bo\n", r);
586 		goto reserve_bo_failed;
587 	}
588 
589 	if (clear) {
590 		r = amdgpu_bo_sync_wait(bo, AMDGPU_FENCE_OWNER_KFD, false);
591 		if (r) {
592 			pr_debug("failed %d to sync bo\n", r);
593 			amdgpu_bo_unreserve(bo);
594 			goto reserve_bo_failed;
595 		}
596 	}
597 
598 	r = dma_resv_reserve_fences(bo->tbo.base.resv, 1);
599 	if (r) {
600 		pr_debug("failed %d to reserve bo\n", r);
601 		amdgpu_bo_unreserve(bo);
602 		goto reserve_bo_failed;
603 	}
604 	amdgpu_bo_fence(bo, &svm_bo->eviction_fence->base, true);
605 
606 	amdgpu_bo_unreserve(bo);
607 
608 	svm_bo->bo = bo;
609 	prange->svm_bo = svm_bo;
610 	prange->ttm_res = bo->tbo.resource;
611 	prange->offset = 0;
612 
613 	spin_lock(&svm_bo->list_lock);
614 	list_add(&prange->svm_bo_list, &svm_bo->range_list);
615 	spin_unlock(&svm_bo->list_lock);
616 
617 	return 0;
618 
619 reserve_bo_failed:
620 	amdgpu_bo_unref(&bo);
621 create_bo_failed:
622 	dma_fence_put(&svm_bo->eviction_fence->base);
623 	kfree(svm_bo);
624 	prange->ttm_res = NULL;
625 
626 	return r;
627 }
628 
629 void svm_range_vram_node_free(struct svm_range *prange)
630 {
631 	/* serialize prange->svm_bo unref */
632 	mutex_lock(&prange->lock);
633 	/* prange->svm_bo has not been unref */
634 	if (prange->ttm_res) {
635 		prange->ttm_res = NULL;
636 		mutex_unlock(&prange->lock);
637 		svm_range_bo_unref(prange->svm_bo);
638 	} else
639 		mutex_unlock(&prange->lock);
640 }
641 
642 struct kfd_node *
643 svm_range_get_node_by_id(struct svm_range *prange, uint32_t gpu_id)
644 {
645 	struct kfd_process *p;
646 	struct kfd_process_device *pdd;
647 
648 	p = container_of(prange->svms, struct kfd_process, svms);
649 	pdd = kfd_process_device_data_by_id(p, gpu_id);
650 	if (!pdd) {
651 		pr_debug("failed to get kfd process device by id 0x%x\n", gpu_id);
652 		return NULL;
653 	}
654 
655 	return pdd->dev;
656 }
657 
658 struct kfd_process_device *
659 svm_range_get_pdd_by_node(struct svm_range *prange, struct kfd_node *node)
660 {
661 	struct kfd_process *p;
662 
663 	p = container_of(prange->svms, struct kfd_process, svms);
664 
665 	return kfd_get_process_device_data(node, p);
666 }
667 
668 static int svm_range_bo_validate(void *param, struct amdgpu_bo *bo)
669 {
670 	struct ttm_operation_ctx ctx = { false, false };
671 
672 	amdgpu_bo_placement_from_domain(bo, AMDGPU_GEM_DOMAIN_VRAM);
673 
674 	return ttm_bo_validate(&bo->tbo, &bo->placement, &ctx);
675 }
676 
677 static int
678 svm_range_check_attr(struct kfd_process *p,
679 		     uint32_t nattr, struct kfd_ioctl_svm_attribute *attrs)
680 {
681 	uint32_t i;
682 
683 	for (i = 0; i < nattr; i++) {
684 		uint32_t val = attrs[i].value;
685 		int gpuidx = MAX_GPU_INSTANCE;
686 
687 		switch (attrs[i].type) {
688 		case KFD_IOCTL_SVM_ATTR_PREFERRED_LOC:
689 			if (val != KFD_IOCTL_SVM_LOCATION_SYSMEM &&
690 			    val != KFD_IOCTL_SVM_LOCATION_UNDEFINED)
691 				gpuidx = kfd_process_gpuidx_from_gpuid(p, val);
692 			break;
693 		case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
694 			if (val != KFD_IOCTL_SVM_LOCATION_SYSMEM)
695 				gpuidx = kfd_process_gpuidx_from_gpuid(p, val);
696 			break;
697 		case KFD_IOCTL_SVM_ATTR_ACCESS:
698 		case KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE:
699 		case KFD_IOCTL_SVM_ATTR_NO_ACCESS:
700 			gpuidx = kfd_process_gpuidx_from_gpuid(p, val);
701 			break;
702 		case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
703 			break;
704 		case KFD_IOCTL_SVM_ATTR_CLR_FLAGS:
705 			break;
706 		case KFD_IOCTL_SVM_ATTR_GRANULARITY:
707 			break;
708 		default:
709 			pr_debug("unknown attr type 0x%x\n", attrs[i].type);
710 			return -EINVAL;
711 		}
712 
713 		if (gpuidx < 0) {
714 			pr_debug("no GPU 0x%x found\n", val);
715 			return -EINVAL;
716 		} else if (gpuidx < MAX_GPU_INSTANCE &&
717 			   !test_bit(gpuidx, p->svms.bitmap_supported)) {
718 			pr_debug("GPU 0x%x not supported\n", val);
719 			return -EINVAL;
720 		}
721 	}
722 
723 	return 0;
724 }
725 
726 static void
727 svm_range_apply_attrs(struct kfd_process *p, struct svm_range *prange,
728 		      uint32_t nattr, struct kfd_ioctl_svm_attribute *attrs,
729 		      bool *update_mapping)
730 {
731 	uint32_t i;
732 	int gpuidx;
733 
734 	for (i = 0; i < nattr; i++) {
735 		switch (attrs[i].type) {
736 		case KFD_IOCTL_SVM_ATTR_PREFERRED_LOC:
737 			prange->preferred_loc = attrs[i].value;
738 			break;
739 		case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
740 			prange->prefetch_loc = attrs[i].value;
741 			break;
742 		case KFD_IOCTL_SVM_ATTR_ACCESS:
743 		case KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE:
744 		case KFD_IOCTL_SVM_ATTR_NO_ACCESS:
745 			if (!p->xnack_enabled)
746 				*update_mapping = true;
747 
748 			gpuidx = kfd_process_gpuidx_from_gpuid(p,
749 							       attrs[i].value);
750 			if (attrs[i].type == KFD_IOCTL_SVM_ATTR_NO_ACCESS) {
751 				bitmap_clear(prange->bitmap_access, gpuidx, 1);
752 				bitmap_clear(prange->bitmap_aip, gpuidx, 1);
753 			} else if (attrs[i].type == KFD_IOCTL_SVM_ATTR_ACCESS) {
754 				bitmap_set(prange->bitmap_access, gpuidx, 1);
755 				bitmap_clear(prange->bitmap_aip, gpuidx, 1);
756 			} else {
757 				bitmap_clear(prange->bitmap_access, gpuidx, 1);
758 				bitmap_set(prange->bitmap_aip, gpuidx, 1);
759 			}
760 			break;
761 		case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
762 			*update_mapping = true;
763 			prange->flags |= attrs[i].value;
764 			break;
765 		case KFD_IOCTL_SVM_ATTR_CLR_FLAGS:
766 			*update_mapping = true;
767 			prange->flags &= ~attrs[i].value;
768 			break;
769 		case KFD_IOCTL_SVM_ATTR_GRANULARITY:
770 			prange->granularity = min_t(uint32_t, attrs[i].value, 0x3F);
771 			break;
772 		default:
773 			WARN_ONCE(1, "svm_range_check_attrs wasn't called?");
774 		}
775 	}
776 }
777 
778 static bool
779 svm_range_is_same_attrs(struct kfd_process *p, struct svm_range *prange,
780 			uint32_t nattr, struct kfd_ioctl_svm_attribute *attrs)
781 {
782 	uint32_t i;
783 	int gpuidx;
784 
785 	for (i = 0; i < nattr; i++) {
786 		switch (attrs[i].type) {
787 		case KFD_IOCTL_SVM_ATTR_PREFERRED_LOC:
788 			if (prange->preferred_loc != attrs[i].value)
789 				return false;
790 			break;
791 		case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
792 			/* Prefetch should always trigger a migration even
793 			 * if the value of the attribute didn't change.
794 			 */
795 			return false;
796 		case KFD_IOCTL_SVM_ATTR_ACCESS:
797 		case KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE:
798 		case KFD_IOCTL_SVM_ATTR_NO_ACCESS:
799 			gpuidx = kfd_process_gpuidx_from_gpuid(p,
800 							       attrs[i].value);
801 			if (attrs[i].type == KFD_IOCTL_SVM_ATTR_NO_ACCESS) {
802 				if (test_bit(gpuidx, prange->bitmap_access) ||
803 				    test_bit(gpuidx, prange->bitmap_aip))
804 					return false;
805 			} else if (attrs[i].type == KFD_IOCTL_SVM_ATTR_ACCESS) {
806 				if (!test_bit(gpuidx, prange->bitmap_access))
807 					return false;
808 			} else {
809 				if (!test_bit(gpuidx, prange->bitmap_aip))
810 					return false;
811 			}
812 			break;
813 		case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
814 			if ((prange->flags & attrs[i].value) != attrs[i].value)
815 				return false;
816 			break;
817 		case KFD_IOCTL_SVM_ATTR_CLR_FLAGS:
818 			if ((prange->flags & attrs[i].value) != 0)
819 				return false;
820 			break;
821 		case KFD_IOCTL_SVM_ATTR_GRANULARITY:
822 			if (prange->granularity != attrs[i].value)
823 				return false;
824 			break;
825 		default:
826 			WARN_ONCE(1, "svm_range_check_attrs wasn't called?");
827 		}
828 	}
829 
830 	return true;
831 }
832 
833 /**
834  * svm_range_debug_dump - print all range information from svms
835  * @svms: svm range list header
836  *
837  * debug output svm range start, end, prefetch location from svms
838  * interval tree and link list
839  *
840  * Context: The caller must hold svms->lock
841  */
842 static void svm_range_debug_dump(struct svm_range_list *svms)
843 {
844 	struct interval_tree_node *node;
845 	struct svm_range *prange;
846 
847 	pr_debug("dump svms 0x%p list\n", svms);
848 	pr_debug("range\tstart\tpage\tend\t\tlocation\n");
849 
850 	list_for_each_entry(prange, &svms->list, list) {
851 		pr_debug("0x%p 0x%lx\t0x%llx\t0x%llx\t0x%x\n",
852 			 prange, prange->start, prange->npages,
853 			 prange->start + prange->npages - 1,
854 			 prange->actual_loc);
855 	}
856 
857 	pr_debug("dump svms 0x%p interval tree\n", svms);
858 	pr_debug("range\tstart\tpage\tend\t\tlocation\n");
859 	node = interval_tree_iter_first(&svms->objects, 0, ~0ULL);
860 	while (node) {
861 		prange = container_of(node, struct svm_range, it_node);
862 		pr_debug("0x%p 0x%lx\t0x%llx\t0x%llx\t0x%x\n",
863 			 prange, prange->start, prange->npages,
864 			 prange->start + prange->npages - 1,
865 			 prange->actual_loc);
866 		node = interval_tree_iter_next(node, 0, ~0ULL);
867 	}
868 }
869 
870 static void *
871 svm_range_copy_array(void *psrc, size_t size, uint64_t num_elements,
872 		     uint64_t offset)
873 {
874 	unsigned char *dst;
875 
876 	dst = kvmalloc_array(num_elements, size, GFP_KERNEL);
877 	if (!dst)
878 		return NULL;
879 	memcpy(dst, (unsigned char *)psrc + offset, num_elements * size);
880 
881 	return (void *)dst;
882 }
883 
884 static int
885 svm_range_copy_dma_addrs(struct svm_range *dst, struct svm_range *src)
886 {
887 	int i;
888 
889 	for (i = 0; i < MAX_GPU_INSTANCE; i++) {
890 		if (!src->dma_addr[i])
891 			continue;
892 		dst->dma_addr[i] = svm_range_copy_array(src->dma_addr[i],
893 					sizeof(*src->dma_addr[i]), src->npages, 0);
894 		if (!dst->dma_addr[i])
895 			return -ENOMEM;
896 	}
897 
898 	return 0;
899 }
900 
901 static int
902 svm_range_split_array(void *ppnew, void *ppold, size_t size,
903 		      uint64_t old_start, uint64_t old_n,
904 		      uint64_t new_start, uint64_t new_n)
905 {
906 	unsigned char *new, *old, *pold;
907 	uint64_t d;
908 
909 	if (!ppold)
910 		return 0;
911 	pold = *(unsigned char **)ppold;
912 	if (!pold)
913 		return 0;
914 
915 	d = (new_start - old_start) * size;
916 	new = svm_range_copy_array(pold, size, new_n, d);
917 	if (!new)
918 		return -ENOMEM;
919 	d = (new_start == old_start) ? new_n * size : 0;
920 	old = svm_range_copy_array(pold, size, old_n, d);
921 	if (!old) {
922 		kvfree(new);
923 		return -ENOMEM;
924 	}
925 	kvfree(pold);
926 	*(void **)ppold = old;
927 	*(void **)ppnew = new;
928 
929 	return 0;
930 }
931 
932 static int
933 svm_range_split_pages(struct svm_range *new, struct svm_range *old,
934 		      uint64_t start, uint64_t last)
935 {
936 	uint64_t npages = last - start + 1;
937 	int i, r;
938 
939 	for (i = 0; i < MAX_GPU_INSTANCE; i++) {
940 		r = svm_range_split_array(&new->dma_addr[i], &old->dma_addr[i],
941 					  sizeof(*old->dma_addr[i]), old->start,
942 					  npages, new->start, new->npages);
943 		if (r)
944 			return r;
945 	}
946 
947 	return 0;
948 }
949 
950 static int
951 svm_range_split_nodes(struct svm_range *new, struct svm_range *old,
952 		      uint64_t start, uint64_t last)
953 {
954 	uint64_t npages = last - start + 1;
955 
956 	pr_debug("svms 0x%p new prange 0x%p start 0x%lx [0x%llx 0x%llx]\n",
957 		 new->svms, new, new->start, start, last);
958 
959 	if (new->start == old->start) {
960 		new->offset = old->offset;
961 		old->offset += new->npages;
962 	} else {
963 		new->offset = old->offset + npages;
964 	}
965 
966 	new->svm_bo = svm_range_bo_ref(old->svm_bo);
967 	new->ttm_res = old->ttm_res;
968 
969 	spin_lock(&new->svm_bo->list_lock);
970 	list_add(&new->svm_bo_list, &new->svm_bo->range_list);
971 	spin_unlock(&new->svm_bo->list_lock);
972 
973 	return 0;
974 }
975 
976 /**
977  * svm_range_split_adjust - split range and adjust
978  *
979  * @new: new range
980  * @old: the old range
981  * @start: the old range adjust to start address in pages
982  * @last: the old range adjust to last address in pages
983  *
984  * Copy system memory dma_addr or vram ttm_res in old range to new
985  * range from new_start up to size new->npages, the remaining old range is from
986  * start to last
987  *
988  * Return:
989  * 0 - OK, -ENOMEM - out of memory
990  */
991 static int
992 svm_range_split_adjust(struct svm_range *new, struct svm_range *old,
993 		      uint64_t start, uint64_t last)
994 {
995 	int r;
996 
997 	pr_debug("svms 0x%p new 0x%lx old [0x%lx 0x%lx] => [0x%llx 0x%llx]\n",
998 		 new->svms, new->start, old->start, old->last, start, last);
999 
1000 	if (new->start < old->start ||
1001 	    new->last > old->last) {
1002 		WARN_ONCE(1, "invalid new range start or last\n");
1003 		return -EINVAL;
1004 	}
1005 
1006 	r = svm_range_split_pages(new, old, start, last);
1007 	if (r)
1008 		return r;
1009 
1010 	if (old->actual_loc && old->ttm_res) {
1011 		r = svm_range_split_nodes(new, old, start, last);
1012 		if (r)
1013 			return r;
1014 	}
1015 
1016 	old->npages = last - start + 1;
1017 	old->start = start;
1018 	old->last = last;
1019 	new->flags = old->flags;
1020 	new->preferred_loc = old->preferred_loc;
1021 	new->prefetch_loc = old->prefetch_loc;
1022 	new->actual_loc = old->actual_loc;
1023 	new->granularity = old->granularity;
1024 	new->mapped_to_gpu = old->mapped_to_gpu;
1025 	bitmap_copy(new->bitmap_access, old->bitmap_access, MAX_GPU_INSTANCE);
1026 	bitmap_copy(new->bitmap_aip, old->bitmap_aip, MAX_GPU_INSTANCE);
1027 
1028 	return 0;
1029 }
1030 
1031 /**
1032  * svm_range_split - split a range in 2 ranges
1033  *
1034  * @prange: the svm range to split
1035  * @start: the remaining range start address in pages
1036  * @last: the remaining range last address in pages
1037  * @new: the result new range generated
1038  *
1039  * Two cases only:
1040  * case 1: if start == prange->start
1041  *         prange ==> prange[start, last]
1042  *         new range [last + 1, prange->last]
1043  *
1044  * case 2: if last == prange->last
1045  *         prange ==> prange[start, last]
1046  *         new range [prange->start, start - 1]
1047  *
1048  * Return:
1049  * 0 - OK, -ENOMEM - out of memory, -EINVAL - invalid start, last
1050  */
1051 static int
1052 svm_range_split(struct svm_range *prange, uint64_t start, uint64_t last,
1053 		struct svm_range **new)
1054 {
1055 	uint64_t old_start = prange->start;
1056 	uint64_t old_last = prange->last;
1057 	struct svm_range_list *svms;
1058 	int r = 0;
1059 
1060 	pr_debug("svms 0x%p [0x%llx 0x%llx] to [0x%llx 0x%llx]\n", prange->svms,
1061 		 old_start, old_last, start, last);
1062 
1063 	if (old_start != start && old_last != last)
1064 		return -EINVAL;
1065 	if (start < old_start || last > old_last)
1066 		return -EINVAL;
1067 
1068 	svms = prange->svms;
1069 	if (old_start == start)
1070 		*new = svm_range_new(svms, last + 1, old_last, false);
1071 	else
1072 		*new = svm_range_new(svms, old_start, start - 1, false);
1073 	if (!*new)
1074 		return -ENOMEM;
1075 
1076 	r = svm_range_split_adjust(*new, prange, start, last);
1077 	if (r) {
1078 		pr_debug("failed %d split [0x%llx 0x%llx] to [0x%llx 0x%llx]\n",
1079 			 r, old_start, old_last, start, last);
1080 		svm_range_free(*new, false);
1081 		*new = NULL;
1082 	}
1083 
1084 	return r;
1085 }
1086 
1087 static int
1088 svm_range_split_tail(struct svm_range *prange,
1089 		     uint64_t new_last, struct list_head *insert_list)
1090 {
1091 	struct svm_range *tail;
1092 	int r = svm_range_split(prange, prange->start, new_last, &tail);
1093 
1094 	if (!r)
1095 		list_add(&tail->list, insert_list);
1096 	return r;
1097 }
1098 
1099 static int
1100 svm_range_split_head(struct svm_range *prange,
1101 		     uint64_t new_start, struct list_head *insert_list)
1102 {
1103 	struct svm_range *head;
1104 	int r = svm_range_split(prange, new_start, prange->last, &head);
1105 
1106 	if (!r)
1107 		list_add(&head->list, insert_list);
1108 	return r;
1109 }
1110 
1111 static void
1112 svm_range_add_child(struct svm_range *prange, struct mm_struct *mm,
1113 		    struct svm_range *pchild, enum svm_work_list_ops op)
1114 {
1115 	pr_debug("add child 0x%p [0x%lx 0x%lx] to prange 0x%p child list %d\n",
1116 		 pchild, pchild->start, pchild->last, prange, op);
1117 
1118 	pchild->work_item.mm = mm;
1119 	pchild->work_item.op = op;
1120 	list_add_tail(&pchild->child_list, &prange->child_list);
1121 }
1122 
1123 /**
1124  * svm_range_split_by_granularity - collect ranges within granularity boundary
1125  *
1126  * @p: the process with svms list
1127  * @mm: mm structure
1128  * @addr: the vm fault address in pages, to split the prange
1129  * @parent: parent range if prange is from child list
1130  * @prange: prange to split
1131  *
1132  * Trims @prange to be a single aligned block of prange->granularity if
1133  * possible. The head and tail are added to the child_list in @parent.
1134  *
1135  * Context: caller must hold mmap_read_lock and prange->lock
1136  *
1137  * Return:
1138  * 0 - OK, otherwise error code
1139  */
1140 int
1141 svm_range_split_by_granularity(struct kfd_process *p, struct mm_struct *mm,
1142 			       unsigned long addr, struct svm_range *parent,
1143 			       struct svm_range *prange)
1144 {
1145 	struct svm_range *head, *tail;
1146 	unsigned long start, last, size;
1147 	int r;
1148 
1149 	/* Align splited range start and size to granularity size, then a single
1150 	 * PTE will be used for whole range, this reduces the number of PTE
1151 	 * updated and the L1 TLB space used for translation.
1152 	 */
1153 	size = 1UL << prange->granularity;
1154 	start = ALIGN_DOWN(addr, size);
1155 	last = ALIGN(addr + 1, size) - 1;
1156 
1157 	pr_debug("svms 0x%p split [0x%lx 0x%lx] to [0x%lx 0x%lx] size 0x%lx\n",
1158 		 prange->svms, prange->start, prange->last, start, last, size);
1159 
1160 	if (start > prange->start) {
1161 		r = svm_range_split(prange, start, prange->last, &head);
1162 		if (r)
1163 			return r;
1164 		svm_range_add_child(parent, mm, head, SVM_OP_ADD_RANGE);
1165 	}
1166 
1167 	if (last < prange->last) {
1168 		r = svm_range_split(prange, prange->start, last, &tail);
1169 		if (r)
1170 			return r;
1171 		svm_range_add_child(parent, mm, tail, SVM_OP_ADD_RANGE);
1172 	}
1173 
1174 	/* xnack on, update mapping on GPUs with ACCESS_IN_PLACE */
1175 	if (p->xnack_enabled && prange->work_item.op == SVM_OP_ADD_RANGE) {
1176 		prange->work_item.op = SVM_OP_ADD_RANGE_AND_MAP;
1177 		pr_debug("change prange 0x%p [0x%lx 0x%lx] op %d\n",
1178 			 prange, prange->start, prange->last,
1179 			 SVM_OP_ADD_RANGE_AND_MAP);
1180 	}
1181 	return 0;
1182 }
1183 static bool
1184 svm_nodes_in_same_hive(struct kfd_node *node_a, struct kfd_node *node_b)
1185 {
1186 	return (node_a->adev == node_b->adev ||
1187 		amdgpu_xgmi_same_hive(node_a->adev, node_b->adev));
1188 }
1189 
1190 static uint64_t
1191 svm_range_get_pte_flags(struct kfd_node *node,
1192 			struct svm_range *prange, int domain)
1193 {
1194 	struct kfd_node *bo_node;
1195 	uint32_t flags = prange->flags;
1196 	uint32_t mapping_flags = 0;
1197 	uint64_t pte_flags;
1198 	bool snoop = (domain != SVM_RANGE_VRAM_DOMAIN);
1199 	bool coherent = flags & KFD_IOCTL_SVM_FLAG_COHERENT;
1200 	bool uncached = false; /*flags & KFD_IOCTL_SVM_FLAG_UNCACHED;*/
1201 	unsigned int mtype_local;
1202 
1203 	if (domain == SVM_RANGE_VRAM_DOMAIN)
1204 		bo_node = prange->svm_bo->node;
1205 
1206 	switch (node->adev->ip_versions[GC_HWIP][0]) {
1207 	case IP_VERSION(9, 4, 1):
1208 		if (domain == SVM_RANGE_VRAM_DOMAIN) {
1209 			if (bo_node == node) {
1210 				mapping_flags |= coherent ?
1211 					AMDGPU_VM_MTYPE_CC : AMDGPU_VM_MTYPE_RW;
1212 			} else {
1213 				mapping_flags |= coherent ?
1214 					AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
1215 				if (svm_nodes_in_same_hive(node, bo_node))
1216 					snoop = true;
1217 			}
1218 		} else {
1219 			mapping_flags |= coherent ?
1220 				AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
1221 		}
1222 		break;
1223 	case IP_VERSION(9, 4, 2):
1224 		if (domain == SVM_RANGE_VRAM_DOMAIN) {
1225 			if (bo_node == node) {
1226 				mapping_flags |= coherent ?
1227 					AMDGPU_VM_MTYPE_CC : AMDGPU_VM_MTYPE_RW;
1228 				if (node->adev->gmc.xgmi.connected_to_cpu)
1229 					snoop = true;
1230 			} else {
1231 				mapping_flags |= coherent ?
1232 					AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
1233 				if (svm_nodes_in_same_hive(node, bo_node))
1234 					snoop = true;
1235 			}
1236 		} else {
1237 			mapping_flags |= coherent ?
1238 				AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
1239 		}
1240 		break;
1241 	case IP_VERSION(9, 4, 3):
1242 		mtype_local = amdgpu_mtype_local == 1 ? AMDGPU_VM_MTYPE_NC :
1243 			     (amdgpu_mtype_local == 2 ? AMDGPU_VM_MTYPE_CC : AMDGPU_VM_MTYPE_RW);
1244 		snoop = true;
1245 		if (uncached) {
1246 			mapping_flags |= AMDGPU_VM_MTYPE_UC;
1247 		} else if (domain == SVM_RANGE_VRAM_DOMAIN) {
1248 			/* local HBM region close to partition */
1249 			if (bo_node->adev == node->adev &&
1250 			    (!bo_node->xcp || !node->xcp || bo_node->xcp->mem_id == node->xcp->mem_id))
1251 				mapping_flags |= mtype_local;
1252 			/* local HBM region far from partition or remote XGMI GPU */
1253 			else if (svm_nodes_in_same_hive(bo_node, node))
1254 				mapping_flags |= AMDGPU_VM_MTYPE_NC;
1255 			/* PCIe P2P */
1256 			else
1257 				mapping_flags |= AMDGPU_VM_MTYPE_UC;
1258 		/* system memory accessed by the APU */
1259 		} else if (node->adev->flags & AMD_IS_APU) {
1260 			/* On NUMA systems, locality is determined per-page
1261 			 * in amdgpu_gmc_override_vm_pte_flags
1262 			 */
1263 			if (num_possible_nodes() <= 1)
1264 				mapping_flags |= mtype_local;
1265 			else
1266 				mapping_flags |= AMDGPU_VM_MTYPE_NC;
1267 		/* system memory accessed by the dGPU */
1268 		} else {
1269 			mapping_flags |= AMDGPU_VM_MTYPE_UC;
1270 		}
1271 		break;
1272 	default:
1273 		mapping_flags |= coherent ?
1274 			AMDGPU_VM_MTYPE_UC : AMDGPU_VM_MTYPE_NC;
1275 	}
1276 
1277 	mapping_flags |= AMDGPU_VM_PAGE_READABLE | AMDGPU_VM_PAGE_WRITEABLE;
1278 
1279 	if (flags & KFD_IOCTL_SVM_FLAG_GPU_RO)
1280 		mapping_flags &= ~AMDGPU_VM_PAGE_WRITEABLE;
1281 	if (flags & KFD_IOCTL_SVM_FLAG_GPU_EXEC)
1282 		mapping_flags |= AMDGPU_VM_PAGE_EXECUTABLE;
1283 
1284 	pte_flags = AMDGPU_PTE_VALID;
1285 	pte_flags |= (domain == SVM_RANGE_VRAM_DOMAIN) ? 0 : AMDGPU_PTE_SYSTEM;
1286 	pte_flags |= snoop ? AMDGPU_PTE_SNOOPED : 0;
1287 
1288 	pte_flags |= amdgpu_gem_va_map_flags(node->adev, mapping_flags);
1289 	return pte_flags;
1290 }
1291 
1292 static int
1293 svm_range_unmap_from_gpu(struct amdgpu_device *adev, struct amdgpu_vm *vm,
1294 			 uint64_t start, uint64_t last,
1295 			 struct dma_fence **fence)
1296 {
1297 	uint64_t init_pte_value = 0;
1298 
1299 	pr_debug("[0x%llx 0x%llx]\n", start, last);
1300 
1301 	return amdgpu_vm_update_range(adev, vm, false, true, true, NULL, start,
1302 				      last, init_pte_value, 0, 0, NULL, NULL,
1303 				      fence);
1304 }
1305 
1306 static int
1307 svm_range_unmap_from_gpus(struct svm_range *prange, unsigned long start,
1308 			  unsigned long last, uint32_t trigger)
1309 {
1310 	DECLARE_BITMAP(bitmap, MAX_GPU_INSTANCE);
1311 	struct kfd_process_device *pdd;
1312 	struct dma_fence *fence = NULL;
1313 	struct kfd_process *p;
1314 	uint32_t gpuidx;
1315 	int r = 0;
1316 
1317 	if (!prange->mapped_to_gpu) {
1318 		pr_debug("prange 0x%p [0x%lx 0x%lx] not mapped to GPU\n",
1319 			 prange, prange->start, prange->last);
1320 		return 0;
1321 	}
1322 
1323 	if (prange->start == start && prange->last == last) {
1324 		pr_debug("unmap svms 0x%p prange 0x%p\n", prange->svms, prange);
1325 		prange->mapped_to_gpu = false;
1326 	}
1327 
1328 	bitmap_or(bitmap, prange->bitmap_access, prange->bitmap_aip,
1329 		  MAX_GPU_INSTANCE);
1330 	p = container_of(prange->svms, struct kfd_process, svms);
1331 
1332 	for_each_set_bit(gpuidx, bitmap, MAX_GPU_INSTANCE) {
1333 		pr_debug("unmap from gpu idx 0x%x\n", gpuidx);
1334 		pdd = kfd_process_device_from_gpuidx(p, gpuidx);
1335 		if (!pdd) {
1336 			pr_debug("failed to find device idx %d\n", gpuidx);
1337 			return -EINVAL;
1338 		}
1339 
1340 		kfd_smi_event_unmap_from_gpu(pdd->dev, p->lead_thread->pid,
1341 					     start, last, trigger);
1342 
1343 		r = svm_range_unmap_from_gpu(pdd->dev->adev,
1344 					     drm_priv_to_vm(pdd->drm_priv),
1345 					     start, last, &fence);
1346 		if (r)
1347 			break;
1348 
1349 		if (fence) {
1350 			r = dma_fence_wait(fence, false);
1351 			dma_fence_put(fence);
1352 			fence = NULL;
1353 			if (r)
1354 				break;
1355 		}
1356 		kfd_flush_tlb(pdd, TLB_FLUSH_HEAVYWEIGHT);
1357 	}
1358 
1359 	return r;
1360 }
1361 
1362 static int
1363 svm_range_map_to_gpu(struct kfd_process_device *pdd, struct svm_range *prange,
1364 		     unsigned long offset, unsigned long npages, bool readonly,
1365 		     dma_addr_t *dma_addr, struct amdgpu_device *bo_adev,
1366 		     struct dma_fence **fence, bool flush_tlb)
1367 {
1368 	struct amdgpu_device *adev = pdd->dev->adev;
1369 	struct amdgpu_vm *vm = drm_priv_to_vm(pdd->drm_priv);
1370 	uint64_t pte_flags;
1371 	unsigned long last_start;
1372 	int last_domain;
1373 	int r = 0;
1374 	int64_t i, j;
1375 
1376 	last_start = prange->start + offset;
1377 
1378 	pr_debug("svms 0x%p [0x%lx 0x%lx] readonly %d\n", prange->svms,
1379 		 last_start, last_start + npages - 1, readonly);
1380 
1381 	for (i = offset; i < offset + npages; i++) {
1382 		last_domain = dma_addr[i] & SVM_RANGE_VRAM_DOMAIN;
1383 		dma_addr[i] &= ~SVM_RANGE_VRAM_DOMAIN;
1384 
1385 		/* Collect all pages in the same address range and memory domain
1386 		 * that can be mapped with a single call to update mapping.
1387 		 */
1388 		if (i < offset + npages - 1 &&
1389 		    last_domain == (dma_addr[i + 1] & SVM_RANGE_VRAM_DOMAIN))
1390 			continue;
1391 
1392 		pr_debug("Mapping range [0x%lx 0x%llx] on domain: %s\n",
1393 			 last_start, prange->start + i, last_domain ? "GPU" : "CPU");
1394 
1395 		pte_flags = svm_range_get_pte_flags(pdd->dev, prange, last_domain);
1396 		if (readonly)
1397 			pte_flags &= ~AMDGPU_PTE_WRITEABLE;
1398 
1399 		pr_debug("svms 0x%p map [0x%lx 0x%llx] vram %d PTE 0x%llx\n",
1400 			 prange->svms, last_start, prange->start + i,
1401 			 (last_domain == SVM_RANGE_VRAM_DOMAIN) ? 1 : 0,
1402 			 pte_flags);
1403 
1404 		/* For dGPU mode, we use same vm_manager to allocate VRAM for
1405 		 * different memory partition based on fpfn/lpfn, we should use
1406 		 * same vm_manager.vram_base_offset regardless memory partition.
1407 		 */
1408 		r = amdgpu_vm_update_range(adev, vm, false, false, flush_tlb, NULL,
1409 					   last_start, prange->start + i,
1410 					   pte_flags,
1411 					   (last_start - prange->start) << PAGE_SHIFT,
1412 					   bo_adev ? bo_adev->vm_manager.vram_base_offset : 0,
1413 					   NULL, dma_addr, &vm->last_update);
1414 
1415 		for (j = last_start - prange->start; j <= i; j++)
1416 			dma_addr[j] |= last_domain;
1417 
1418 		if (r) {
1419 			pr_debug("failed %d to map to gpu 0x%lx\n", r, prange->start);
1420 			goto out;
1421 		}
1422 		last_start = prange->start + i + 1;
1423 	}
1424 
1425 	r = amdgpu_vm_update_pdes(adev, vm, false);
1426 	if (r) {
1427 		pr_debug("failed %d to update directories 0x%lx\n", r,
1428 			 prange->start);
1429 		goto out;
1430 	}
1431 
1432 	if (fence)
1433 		*fence = dma_fence_get(vm->last_update);
1434 
1435 out:
1436 	return r;
1437 }
1438 
1439 static int
1440 svm_range_map_to_gpus(struct svm_range *prange, unsigned long offset,
1441 		      unsigned long npages, bool readonly,
1442 		      unsigned long *bitmap, bool wait, bool flush_tlb)
1443 {
1444 	struct kfd_process_device *pdd;
1445 	struct amdgpu_device *bo_adev = NULL;
1446 	struct kfd_process *p;
1447 	struct dma_fence *fence = NULL;
1448 	uint32_t gpuidx;
1449 	int r = 0;
1450 
1451 	if (prange->svm_bo && prange->ttm_res)
1452 		bo_adev = prange->svm_bo->node->adev;
1453 
1454 	p = container_of(prange->svms, struct kfd_process, svms);
1455 	for_each_set_bit(gpuidx, bitmap, MAX_GPU_INSTANCE) {
1456 		pr_debug("mapping to gpu idx 0x%x\n", gpuidx);
1457 		pdd = kfd_process_device_from_gpuidx(p, gpuidx);
1458 		if (!pdd) {
1459 			pr_debug("failed to find device idx %d\n", gpuidx);
1460 			return -EINVAL;
1461 		}
1462 
1463 		pdd = kfd_bind_process_to_device(pdd->dev, p);
1464 		if (IS_ERR(pdd))
1465 			return -EINVAL;
1466 
1467 		if (bo_adev && pdd->dev->adev != bo_adev &&
1468 		    !amdgpu_xgmi_same_hive(pdd->dev->adev, bo_adev)) {
1469 			pr_debug("cannot map to device idx %d\n", gpuidx);
1470 			continue;
1471 		}
1472 
1473 		r = svm_range_map_to_gpu(pdd, prange, offset, npages, readonly,
1474 					 prange->dma_addr[gpuidx],
1475 					 bo_adev, wait ? &fence : NULL,
1476 					 flush_tlb);
1477 		if (r)
1478 			break;
1479 
1480 		if (fence) {
1481 			r = dma_fence_wait(fence, false);
1482 			dma_fence_put(fence);
1483 			fence = NULL;
1484 			if (r) {
1485 				pr_debug("failed %d to dma fence wait\n", r);
1486 				break;
1487 			}
1488 		}
1489 
1490 		kfd_flush_tlb(pdd, TLB_FLUSH_LEGACY);
1491 	}
1492 
1493 	return r;
1494 }
1495 
1496 struct svm_validate_context {
1497 	struct kfd_process *process;
1498 	struct svm_range *prange;
1499 	bool intr;
1500 	DECLARE_BITMAP(bitmap, MAX_GPU_INSTANCE);
1501 	struct drm_exec exec;
1502 };
1503 
1504 static int svm_range_reserve_bos(struct svm_validate_context *ctx, bool intr)
1505 {
1506 	struct kfd_process_device *pdd;
1507 	struct amdgpu_vm *vm;
1508 	uint32_t gpuidx;
1509 	int r;
1510 
1511 	drm_exec_init(&ctx->exec, intr ? DRM_EXEC_INTERRUPTIBLE_WAIT: 0);
1512 	drm_exec_until_all_locked(&ctx->exec) {
1513 		for_each_set_bit(gpuidx, ctx->bitmap, MAX_GPU_INSTANCE) {
1514 			pdd = kfd_process_device_from_gpuidx(ctx->process, gpuidx);
1515 			if (!pdd) {
1516 				pr_debug("failed to find device idx %d\n", gpuidx);
1517 				r = -EINVAL;
1518 				goto unreserve_out;
1519 			}
1520 			vm = drm_priv_to_vm(pdd->drm_priv);
1521 
1522 			r = amdgpu_vm_lock_pd(vm, &ctx->exec, 2);
1523 			drm_exec_retry_on_contention(&ctx->exec);
1524 			if (unlikely(r)) {
1525 				pr_debug("failed %d to reserve bo\n", r);
1526 				goto unreserve_out;
1527 			}
1528 		}
1529 	}
1530 
1531 	for_each_set_bit(gpuidx, ctx->bitmap, MAX_GPU_INSTANCE) {
1532 		pdd = kfd_process_device_from_gpuidx(ctx->process, gpuidx);
1533 		if (!pdd) {
1534 			pr_debug("failed to find device idx %d\n", gpuidx);
1535 			r = -EINVAL;
1536 			goto unreserve_out;
1537 		}
1538 
1539 		r = amdgpu_vm_validate_pt_bos(pdd->dev->adev,
1540 					      drm_priv_to_vm(pdd->drm_priv),
1541 					      svm_range_bo_validate, NULL);
1542 		if (r) {
1543 			pr_debug("failed %d validate pt bos\n", r);
1544 			goto unreserve_out;
1545 		}
1546 	}
1547 
1548 	return 0;
1549 
1550 unreserve_out:
1551 	drm_exec_fini(&ctx->exec);
1552 	return r;
1553 }
1554 
1555 static void svm_range_unreserve_bos(struct svm_validate_context *ctx)
1556 {
1557 	drm_exec_fini(&ctx->exec);
1558 }
1559 
1560 static void *kfd_svm_page_owner(struct kfd_process *p, int32_t gpuidx)
1561 {
1562 	struct kfd_process_device *pdd;
1563 
1564 	pdd = kfd_process_device_from_gpuidx(p, gpuidx);
1565 	if (!pdd)
1566 		return NULL;
1567 
1568 	return SVM_ADEV_PGMAP_OWNER(pdd->dev->adev);
1569 }
1570 
1571 /*
1572  * Validation+GPU mapping with concurrent invalidation (MMU notifiers)
1573  *
1574  * To prevent concurrent destruction or change of range attributes, the
1575  * svm_read_lock must be held. The caller must not hold the svm_write_lock
1576  * because that would block concurrent evictions and lead to deadlocks. To
1577  * serialize concurrent migrations or validations of the same range, the
1578  * prange->migrate_mutex must be held.
1579  *
1580  * For VRAM ranges, the SVM BO must be allocated and valid (protected by its
1581  * eviction fence.
1582  *
1583  * The following sequence ensures race-free validation and GPU mapping:
1584  *
1585  * 1. Reserve page table (and SVM BO if range is in VRAM)
1586  * 2. hmm_range_fault to get page addresses (if system memory)
1587  * 3. DMA-map pages (if system memory)
1588  * 4-a. Take notifier lock
1589  * 4-b. Check that pages still valid (mmu_interval_read_retry)
1590  * 4-c. Check that the range was not split or otherwise invalidated
1591  * 4-d. Update GPU page table
1592  * 4.e. Release notifier lock
1593  * 5. Release page table (and SVM BO) reservation
1594  */
1595 static int svm_range_validate_and_map(struct mm_struct *mm,
1596 				      struct svm_range *prange, int32_t gpuidx,
1597 				      bool intr, bool wait, bool flush_tlb)
1598 {
1599 	struct svm_validate_context *ctx;
1600 	unsigned long start, end, addr;
1601 	struct kfd_process *p;
1602 	void *owner;
1603 	int32_t idx;
1604 	int r = 0;
1605 
1606 	ctx = kzalloc(sizeof(struct svm_validate_context), GFP_KERNEL);
1607 	if (!ctx)
1608 		return -ENOMEM;
1609 	ctx->process = container_of(prange->svms, struct kfd_process, svms);
1610 	ctx->prange = prange;
1611 	ctx->intr = intr;
1612 
1613 	if (gpuidx < MAX_GPU_INSTANCE) {
1614 		bitmap_zero(ctx->bitmap, MAX_GPU_INSTANCE);
1615 		bitmap_set(ctx->bitmap, gpuidx, 1);
1616 	} else if (ctx->process->xnack_enabled) {
1617 		bitmap_copy(ctx->bitmap, prange->bitmap_aip, MAX_GPU_INSTANCE);
1618 
1619 		/* If prefetch range to GPU, or GPU retry fault migrate range to
1620 		 * GPU, which has ACCESS attribute to the range, create mapping
1621 		 * on that GPU.
1622 		 */
1623 		if (prange->actual_loc) {
1624 			gpuidx = kfd_process_gpuidx_from_gpuid(ctx->process,
1625 							prange->actual_loc);
1626 			if (gpuidx < 0) {
1627 				WARN_ONCE(1, "failed get device by id 0x%x\n",
1628 					 prange->actual_loc);
1629 				r = -EINVAL;
1630 				goto free_ctx;
1631 			}
1632 			if (test_bit(gpuidx, prange->bitmap_access))
1633 				bitmap_set(ctx->bitmap, gpuidx, 1);
1634 		}
1635 
1636 		/*
1637 		 * If prange is already mapped or with always mapped flag,
1638 		 * update mapping on GPUs with ACCESS attribute
1639 		 */
1640 		if (bitmap_empty(ctx->bitmap, MAX_GPU_INSTANCE)) {
1641 			if (prange->mapped_to_gpu ||
1642 			    prange->flags & KFD_IOCTL_SVM_FLAG_GPU_ALWAYS_MAPPED)
1643 				bitmap_copy(ctx->bitmap, prange->bitmap_access, MAX_GPU_INSTANCE);
1644 		}
1645 	} else {
1646 		bitmap_or(ctx->bitmap, prange->bitmap_access,
1647 			  prange->bitmap_aip, MAX_GPU_INSTANCE);
1648 	}
1649 
1650 	if (bitmap_empty(ctx->bitmap, MAX_GPU_INSTANCE)) {
1651 		r = 0;
1652 		goto free_ctx;
1653 	}
1654 
1655 	if (prange->actual_loc && !prange->ttm_res) {
1656 		/* This should never happen. actual_loc gets set by
1657 		 * svm_migrate_ram_to_vram after allocating a BO.
1658 		 */
1659 		WARN_ONCE(1, "VRAM BO missing during validation\n");
1660 		r = -EINVAL;
1661 		goto free_ctx;
1662 	}
1663 
1664 	svm_range_reserve_bos(ctx, intr);
1665 
1666 	p = container_of(prange->svms, struct kfd_process, svms);
1667 	owner = kfd_svm_page_owner(p, find_first_bit(ctx->bitmap,
1668 						MAX_GPU_INSTANCE));
1669 	for_each_set_bit(idx, ctx->bitmap, MAX_GPU_INSTANCE) {
1670 		if (kfd_svm_page_owner(p, idx) != owner) {
1671 			owner = NULL;
1672 			break;
1673 		}
1674 	}
1675 
1676 	start = prange->start << PAGE_SHIFT;
1677 	end = (prange->last + 1) << PAGE_SHIFT;
1678 	for (addr = start; !r && addr < end; ) {
1679 		struct hmm_range *hmm_range;
1680 		struct vm_area_struct *vma;
1681 		unsigned long next = 0;
1682 		unsigned long offset;
1683 		unsigned long npages;
1684 		bool readonly;
1685 
1686 		vma = vma_lookup(mm, addr);
1687 		if (vma) {
1688 			readonly = !(vma->vm_flags & VM_WRITE);
1689 
1690 			next = min(vma->vm_end, end);
1691 			npages = (next - addr) >> PAGE_SHIFT;
1692 			WRITE_ONCE(p->svms.faulting_task, current);
1693 			r = amdgpu_hmm_range_get_pages(&prange->notifier, addr, npages,
1694 						       readonly, owner, NULL,
1695 						       &hmm_range);
1696 			WRITE_ONCE(p->svms.faulting_task, NULL);
1697 			if (r) {
1698 				pr_debug("failed %d to get svm range pages\n", r);
1699 				if (r == -EBUSY)
1700 					r = -EAGAIN;
1701 			}
1702 		} else {
1703 			r = -EFAULT;
1704 		}
1705 
1706 		if (!r) {
1707 			offset = (addr - start) >> PAGE_SHIFT;
1708 			r = svm_range_dma_map(prange, ctx->bitmap, offset, npages,
1709 					      hmm_range->hmm_pfns);
1710 			if (r)
1711 				pr_debug("failed %d to dma map range\n", r);
1712 		}
1713 
1714 		svm_range_lock(prange);
1715 		if (!r && amdgpu_hmm_range_get_pages_done(hmm_range)) {
1716 			pr_debug("hmm update the range, need validate again\n");
1717 			r = -EAGAIN;
1718 		}
1719 
1720 		if (!r && !list_empty(&prange->child_list)) {
1721 			pr_debug("range split by unmap in parallel, validate again\n");
1722 			r = -EAGAIN;
1723 		}
1724 
1725 		if (!r)
1726 			r = svm_range_map_to_gpus(prange, offset, npages, readonly,
1727 						  ctx->bitmap, wait, flush_tlb);
1728 
1729 		if (!r && next == end)
1730 			prange->mapped_to_gpu = true;
1731 
1732 		svm_range_unlock(prange);
1733 
1734 		addr = next;
1735 	}
1736 
1737 	svm_range_unreserve_bos(ctx);
1738 	if (!r)
1739 		prange->validate_timestamp = ktime_get_boottime();
1740 
1741 free_ctx:
1742 	kfree(ctx);
1743 
1744 	return r;
1745 }
1746 
1747 /**
1748  * svm_range_list_lock_and_flush_work - flush pending deferred work
1749  *
1750  * @svms: the svm range list
1751  * @mm: the mm structure
1752  *
1753  * Context: Returns with mmap write lock held, pending deferred work flushed
1754  *
1755  */
1756 void
1757 svm_range_list_lock_and_flush_work(struct svm_range_list *svms,
1758 				   struct mm_struct *mm)
1759 {
1760 retry_flush_work:
1761 	flush_work(&svms->deferred_list_work);
1762 	mmap_write_lock(mm);
1763 
1764 	if (list_empty(&svms->deferred_range_list))
1765 		return;
1766 	mmap_write_unlock(mm);
1767 	pr_debug("retry flush\n");
1768 	goto retry_flush_work;
1769 }
1770 
1771 static void svm_range_restore_work(struct work_struct *work)
1772 {
1773 	struct delayed_work *dwork = to_delayed_work(work);
1774 	struct amdkfd_process_info *process_info;
1775 	struct svm_range_list *svms;
1776 	struct svm_range *prange;
1777 	struct kfd_process *p;
1778 	struct mm_struct *mm;
1779 	int evicted_ranges;
1780 	int invalid;
1781 	int r;
1782 
1783 	svms = container_of(dwork, struct svm_range_list, restore_work);
1784 	evicted_ranges = atomic_read(&svms->evicted_ranges);
1785 	if (!evicted_ranges)
1786 		return;
1787 
1788 	pr_debug("restore svm ranges\n");
1789 
1790 	p = container_of(svms, struct kfd_process, svms);
1791 	process_info = p->kgd_process_info;
1792 
1793 	/* Keep mm reference when svm_range_validate_and_map ranges */
1794 	mm = get_task_mm(p->lead_thread);
1795 	if (!mm) {
1796 		pr_debug("svms 0x%p process mm gone\n", svms);
1797 		return;
1798 	}
1799 
1800 	mutex_lock(&process_info->lock);
1801 	svm_range_list_lock_and_flush_work(svms, mm);
1802 	mutex_lock(&svms->lock);
1803 
1804 	evicted_ranges = atomic_read(&svms->evicted_ranges);
1805 
1806 	list_for_each_entry(prange, &svms->list, list) {
1807 		invalid = atomic_read(&prange->invalid);
1808 		if (!invalid)
1809 			continue;
1810 
1811 		pr_debug("restoring svms 0x%p prange 0x%p [0x%lx %lx] inv %d\n",
1812 			 prange->svms, prange, prange->start, prange->last,
1813 			 invalid);
1814 
1815 		/*
1816 		 * If range is migrating, wait for migration is done.
1817 		 */
1818 		mutex_lock(&prange->migrate_mutex);
1819 
1820 		r = svm_range_validate_and_map(mm, prange, MAX_GPU_INSTANCE,
1821 					       false, true, false);
1822 		if (r)
1823 			pr_debug("failed %d to map 0x%lx to gpus\n", r,
1824 				 prange->start);
1825 
1826 		mutex_unlock(&prange->migrate_mutex);
1827 		if (r)
1828 			goto out_reschedule;
1829 
1830 		if (atomic_cmpxchg(&prange->invalid, invalid, 0) != invalid)
1831 			goto out_reschedule;
1832 	}
1833 
1834 	if (atomic_cmpxchg(&svms->evicted_ranges, evicted_ranges, 0) !=
1835 	    evicted_ranges)
1836 		goto out_reschedule;
1837 
1838 	evicted_ranges = 0;
1839 
1840 	r = kgd2kfd_resume_mm(mm);
1841 	if (r) {
1842 		/* No recovery from this failure. Probably the CP is
1843 		 * hanging. No point trying again.
1844 		 */
1845 		pr_debug("failed %d to resume KFD\n", r);
1846 	}
1847 
1848 	pr_debug("restore svm ranges successfully\n");
1849 
1850 out_reschedule:
1851 	mutex_unlock(&svms->lock);
1852 	mmap_write_unlock(mm);
1853 	mutex_unlock(&process_info->lock);
1854 
1855 	/* If validation failed, reschedule another attempt */
1856 	if (evicted_ranges) {
1857 		pr_debug("reschedule to restore svm range\n");
1858 		schedule_delayed_work(&svms->restore_work,
1859 			msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
1860 
1861 		kfd_smi_event_queue_restore_rescheduled(mm);
1862 	}
1863 	mmput(mm);
1864 }
1865 
1866 /**
1867  * svm_range_evict - evict svm range
1868  * @prange: svm range structure
1869  * @mm: current process mm_struct
1870  * @start: starting process queue number
1871  * @last: last process queue number
1872  * @event: mmu notifier event when range is evicted or migrated
1873  *
1874  * Stop all queues of the process to ensure GPU doesn't access the memory, then
1875  * return to let CPU evict the buffer and proceed CPU pagetable update.
1876  *
1877  * Don't need use lock to sync cpu pagetable invalidation with GPU execution.
1878  * If invalidation happens while restore work is running, restore work will
1879  * restart to ensure to get the latest CPU pages mapping to GPU, then start
1880  * the queues.
1881  */
1882 static int
1883 svm_range_evict(struct svm_range *prange, struct mm_struct *mm,
1884 		unsigned long start, unsigned long last,
1885 		enum mmu_notifier_event event)
1886 {
1887 	struct svm_range_list *svms = prange->svms;
1888 	struct svm_range *pchild;
1889 	struct kfd_process *p;
1890 	int r = 0;
1891 
1892 	p = container_of(svms, struct kfd_process, svms);
1893 
1894 	pr_debug("invalidate svms 0x%p prange [0x%lx 0x%lx] [0x%lx 0x%lx]\n",
1895 		 svms, prange->start, prange->last, start, last);
1896 
1897 	if (!p->xnack_enabled ||
1898 	    (prange->flags & KFD_IOCTL_SVM_FLAG_GPU_ALWAYS_MAPPED)) {
1899 		int evicted_ranges;
1900 		bool mapped = prange->mapped_to_gpu;
1901 
1902 		list_for_each_entry(pchild, &prange->child_list, child_list) {
1903 			if (!pchild->mapped_to_gpu)
1904 				continue;
1905 			mapped = true;
1906 			mutex_lock_nested(&pchild->lock, 1);
1907 			if (pchild->start <= last && pchild->last >= start) {
1908 				pr_debug("increment pchild invalid [0x%lx 0x%lx]\n",
1909 					 pchild->start, pchild->last);
1910 				atomic_inc(&pchild->invalid);
1911 			}
1912 			mutex_unlock(&pchild->lock);
1913 		}
1914 
1915 		if (!mapped)
1916 			return r;
1917 
1918 		if (prange->start <= last && prange->last >= start)
1919 			atomic_inc(&prange->invalid);
1920 
1921 		evicted_ranges = atomic_inc_return(&svms->evicted_ranges);
1922 		if (evicted_ranges != 1)
1923 			return r;
1924 
1925 		pr_debug("evicting svms 0x%p range [0x%lx 0x%lx]\n",
1926 			 prange->svms, prange->start, prange->last);
1927 
1928 		/* First eviction, stop the queues */
1929 		r = kgd2kfd_quiesce_mm(mm, KFD_QUEUE_EVICTION_TRIGGER_SVM);
1930 		if (r)
1931 			pr_debug("failed to quiesce KFD\n");
1932 
1933 		pr_debug("schedule to restore svm %p ranges\n", svms);
1934 		schedule_delayed_work(&svms->restore_work,
1935 			msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
1936 	} else {
1937 		unsigned long s, l;
1938 		uint32_t trigger;
1939 
1940 		if (event == MMU_NOTIFY_MIGRATE)
1941 			trigger = KFD_SVM_UNMAP_TRIGGER_MMU_NOTIFY_MIGRATE;
1942 		else
1943 			trigger = KFD_SVM_UNMAP_TRIGGER_MMU_NOTIFY;
1944 
1945 		pr_debug("invalidate unmap svms 0x%p [0x%lx 0x%lx] from GPUs\n",
1946 			 prange->svms, start, last);
1947 		list_for_each_entry(pchild, &prange->child_list, child_list) {
1948 			mutex_lock_nested(&pchild->lock, 1);
1949 			s = max(start, pchild->start);
1950 			l = min(last, pchild->last);
1951 			if (l >= s)
1952 				svm_range_unmap_from_gpus(pchild, s, l, trigger);
1953 			mutex_unlock(&pchild->lock);
1954 		}
1955 		s = max(start, prange->start);
1956 		l = min(last, prange->last);
1957 		if (l >= s)
1958 			svm_range_unmap_from_gpus(prange, s, l, trigger);
1959 	}
1960 
1961 	return r;
1962 }
1963 
1964 static struct svm_range *svm_range_clone(struct svm_range *old)
1965 {
1966 	struct svm_range *new;
1967 
1968 	new = svm_range_new(old->svms, old->start, old->last, false);
1969 	if (!new)
1970 		return NULL;
1971 	if (svm_range_copy_dma_addrs(new, old)) {
1972 		svm_range_free(new, false);
1973 		return NULL;
1974 	}
1975 	if (old->svm_bo) {
1976 		new->ttm_res = old->ttm_res;
1977 		new->offset = old->offset;
1978 		new->svm_bo = svm_range_bo_ref(old->svm_bo);
1979 		spin_lock(&new->svm_bo->list_lock);
1980 		list_add(&new->svm_bo_list, &new->svm_bo->range_list);
1981 		spin_unlock(&new->svm_bo->list_lock);
1982 	}
1983 	new->flags = old->flags;
1984 	new->preferred_loc = old->preferred_loc;
1985 	new->prefetch_loc = old->prefetch_loc;
1986 	new->actual_loc = old->actual_loc;
1987 	new->granularity = old->granularity;
1988 	new->mapped_to_gpu = old->mapped_to_gpu;
1989 	bitmap_copy(new->bitmap_access, old->bitmap_access, MAX_GPU_INSTANCE);
1990 	bitmap_copy(new->bitmap_aip, old->bitmap_aip, MAX_GPU_INSTANCE);
1991 
1992 	return new;
1993 }
1994 
1995 void svm_range_set_max_pages(struct amdgpu_device *adev)
1996 {
1997 	uint64_t max_pages;
1998 	uint64_t pages, _pages;
1999 	uint64_t min_pages = 0;
2000 	int i, id;
2001 
2002 	for (i = 0; i < adev->kfd.dev->num_nodes; i++) {
2003 		if (adev->kfd.dev->nodes[i]->xcp)
2004 			id = adev->kfd.dev->nodes[i]->xcp->id;
2005 		else
2006 			id = -1;
2007 		pages = KFD_XCP_MEMORY_SIZE(adev, id) >> 17;
2008 		pages = clamp(pages, 1ULL << 9, 1ULL << 18);
2009 		pages = rounddown_pow_of_two(pages);
2010 		min_pages = min_not_zero(min_pages, pages);
2011 	}
2012 
2013 	do {
2014 		max_pages = READ_ONCE(max_svm_range_pages);
2015 		_pages = min_not_zero(max_pages, min_pages);
2016 	} while (cmpxchg(&max_svm_range_pages, max_pages, _pages) != max_pages);
2017 }
2018 
2019 static int
2020 svm_range_split_new(struct svm_range_list *svms, uint64_t start, uint64_t last,
2021 		    uint64_t max_pages, struct list_head *insert_list,
2022 		    struct list_head *update_list)
2023 {
2024 	struct svm_range *prange;
2025 	uint64_t l;
2026 
2027 	pr_debug("max_svm_range_pages 0x%llx adding [0x%llx 0x%llx]\n",
2028 		 max_pages, start, last);
2029 
2030 	while (last >= start) {
2031 		l = min(last, ALIGN_DOWN(start + max_pages, max_pages) - 1);
2032 
2033 		prange = svm_range_new(svms, start, l, true);
2034 		if (!prange)
2035 			return -ENOMEM;
2036 		list_add(&prange->list, insert_list);
2037 		list_add(&prange->update_list, update_list);
2038 
2039 		start = l + 1;
2040 	}
2041 	return 0;
2042 }
2043 
2044 /**
2045  * svm_range_add - add svm range and handle overlap
2046  * @p: the range add to this process svms
2047  * @start: page size aligned
2048  * @size: page size aligned
2049  * @nattr: number of attributes
2050  * @attrs: array of attributes
2051  * @update_list: output, the ranges need validate and update GPU mapping
2052  * @insert_list: output, the ranges need insert to svms
2053  * @remove_list: output, the ranges are replaced and need remove from svms
2054  *
2055  * Check if the virtual address range has overlap with any existing ranges,
2056  * split partly overlapping ranges and add new ranges in the gaps. All changes
2057  * should be applied to the range_list and interval tree transactionally. If
2058  * any range split or allocation fails, the entire update fails. Therefore any
2059  * existing overlapping svm_ranges are cloned and the original svm_ranges left
2060  * unchanged.
2061  *
2062  * If the transaction succeeds, the caller can update and insert clones and
2063  * new ranges, then free the originals.
2064  *
2065  * Otherwise the caller can free the clones and new ranges, while the old
2066  * svm_ranges remain unchanged.
2067  *
2068  * Context: Process context, caller must hold svms->lock
2069  *
2070  * Return:
2071  * 0 - OK, otherwise error code
2072  */
2073 static int
2074 svm_range_add(struct kfd_process *p, uint64_t start, uint64_t size,
2075 	      uint32_t nattr, struct kfd_ioctl_svm_attribute *attrs,
2076 	      struct list_head *update_list, struct list_head *insert_list,
2077 	      struct list_head *remove_list)
2078 {
2079 	unsigned long last = start + size - 1UL;
2080 	struct svm_range_list *svms = &p->svms;
2081 	struct interval_tree_node *node;
2082 	struct svm_range *prange;
2083 	struct svm_range *tmp;
2084 	struct list_head new_list;
2085 	int r = 0;
2086 
2087 	pr_debug("svms 0x%p [0x%llx 0x%lx]\n", &p->svms, start, last);
2088 
2089 	INIT_LIST_HEAD(update_list);
2090 	INIT_LIST_HEAD(insert_list);
2091 	INIT_LIST_HEAD(remove_list);
2092 	INIT_LIST_HEAD(&new_list);
2093 
2094 	node = interval_tree_iter_first(&svms->objects, start, last);
2095 	while (node) {
2096 		struct interval_tree_node *next;
2097 		unsigned long next_start;
2098 
2099 		pr_debug("found overlap node [0x%lx 0x%lx]\n", node->start,
2100 			 node->last);
2101 
2102 		prange = container_of(node, struct svm_range, it_node);
2103 		next = interval_tree_iter_next(node, start, last);
2104 		next_start = min(node->last, last) + 1;
2105 
2106 		if (svm_range_is_same_attrs(p, prange, nattr, attrs) &&
2107 		    prange->mapped_to_gpu) {
2108 			/* nothing to do */
2109 		} else if (node->start < start || node->last > last) {
2110 			/* node intersects the update range and its attributes
2111 			 * will change. Clone and split it, apply updates only
2112 			 * to the overlapping part
2113 			 */
2114 			struct svm_range *old = prange;
2115 
2116 			prange = svm_range_clone(old);
2117 			if (!prange) {
2118 				r = -ENOMEM;
2119 				goto out;
2120 			}
2121 
2122 			list_add(&old->update_list, remove_list);
2123 			list_add(&prange->list, insert_list);
2124 			list_add(&prange->update_list, update_list);
2125 
2126 			if (node->start < start) {
2127 				pr_debug("change old range start\n");
2128 				r = svm_range_split_head(prange, start,
2129 							 insert_list);
2130 				if (r)
2131 					goto out;
2132 			}
2133 			if (node->last > last) {
2134 				pr_debug("change old range last\n");
2135 				r = svm_range_split_tail(prange, last,
2136 							 insert_list);
2137 				if (r)
2138 					goto out;
2139 			}
2140 		} else {
2141 			/* The node is contained within start..last,
2142 			 * just update it
2143 			 */
2144 			list_add(&prange->update_list, update_list);
2145 		}
2146 
2147 		/* insert a new node if needed */
2148 		if (node->start > start) {
2149 			r = svm_range_split_new(svms, start, node->start - 1,
2150 						READ_ONCE(max_svm_range_pages),
2151 						&new_list, update_list);
2152 			if (r)
2153 				goto out;
2154 		}
2155 
2156 		node = next;
2157 		start = next_start;
2158 	}
2159 
2160 	/* add a final range at the end if needed */
2161 	if (start <= last)
2162 		r = svm_range_split_new(svms, start, last,
2163 					READ_ONCE(max_svm_range_pages),
2164 					&new_list, update_list);
2165 
2166 out:
2167 	if (r) {
2168 		list_for_each_entry_safe(prange, tmp, insert_list, list)
2169 			svm_range_free(prange, false);
2170 		list_for_each_entry_safe(prange, tmp, &new_list, list)
2171 			svm_range_free(prange, true);
2172 	} else {
2173 		list_splice(&new_list, insert_list);
2174 	}
2175 
2176 	return r;
2177 }
2178 
2179 static void
2180 svm_range_update_notifier_and_interval_tree(struct mm_struct *mm,
2181 					    struct svm_range *prange)
2182 {
2183 	unsigned long start;
2184 	unsigned long last;
2185 
2186 	start = prange->notifier.interval_tree.start >> PAGE_SHIFT;
2187 	last = prange->notifier.interval_tree.last >> PAGE_SHIFT;
2188 
2189 	if (prange->start == start && prange->last == last)
2190 		return;
2191 
2192 	pr_debug("up notifier 0x%p prange 0x%p [0x%lx 0x%lx] [0x%lx 0x%lx]\n",
2193 		  prange->svms, prange, start, last, prange->start,
2194 		  prange->last);
2195 
2196 	if (start != 0 && last != 0) {
2197 		interval_tree_remove(&prange->it_node, &prange->svms->objects);
2198 		svm_range_remove_notifier(prange);
2199 	}
2200 	prange->it_node.start = prange->start;
2201 	prange->it_node.last = prange->last;
2202 
2203 	interval_tree_insert(&prange->it_node, &prange->svms->objects);
2204 	svm_range_add_notifier_locked(mm, prange);
2205 }
2206 
2207 static void
2208 svm_range_handle_list_op(struct svm_range_list *svms, struct svm_range *prange,
2209 			 struct mm_struct *mm)
2210 {
2211 	switch (prange->work_item.op) {
2212 	case SVM_OP_NULL:
2213 		pr_debug("NULL OP 0x%p prange 0x%p [0x%lx 0x%lx]\n",
2214 			 svms, prange, prange->start, prange->last);
2215 		break;
2216 	case SVM_OP_UNMAP_RANGE:
2217 		pr_debug("remove 0x%p prange 0x%p [0x%lx 0x%lx]\n",
2218 			 svms, prange, prange->start, prange->last);
2219 		svm_range_unlink(prange);
2220 		svm_range_remove_notifier(prange);
2221 		svm_range_free(prange, true);
2222 		break;
2223 	case SVM_OP_UPDATE_RANGE_NOTIFIER:
2224 		pr_debug("update notifier 0x%p prange 0x%p [0x%lx 0x%lx]\n",
2225 			 svms, prange, prange->start, prange->last);
2226 		svm_range_update_notifier_and_interval_tree(mm, prange);
2227 		break;
2228 	case SVM_OP_UPDATE_RANGE_NOTIFIER_AND_MAP:
2229 		pr_debug("update and map 0x%p prange 0x%p [0x%lx 0x%lx]\n",
2230 			 svms, prange, prange->start, prange->last);
2231 		svm_range_update_notifier_and_interval_tree(mm, prange);
2232 		/* TODO: implement deferred validation and mapping */
2233 		break;
2234 	case SVM_OP_ADD_RANGE:
2235 		pr_debug("add 0x%p prange 0x%p [0x%lx 0x%lx]\n", svms, prange,
2236 			 prange->start, prange->last);
2237 		svm_range_add_to_svms(prange);
2238 		svm_range_add_notifier_locked(mm, prange);
2239 		break;
2240 	case SVM_OP_ADD_RANGE_AND_MAP:
2241 		pr_debug("add and map 0x%p prange 0x%p [0x%lx 0x%lx]\n", svms,
2242 			 prange, prange->start, prange->last);
2243 		svm_range_add_to_svms(prange);
2244 		svm_range_add_notifier_locked(mm, prange);
2245 		/* TODO: implement deferred validation and mapping */
2246 		break;
2247 	default:
2248 		WARN_ONCE(1, "Unknown prange 0x%p work op %d\n", prange,
2249 			 prange->work_item.op);
2250 	}
2251 }
2252 
2253 static void svm_range_drain_retry_fault(struct svm_range_list *svms)
2254 {
2255 	struct kfd_process_device *pdd;
2256 	struct kfd_process *p;
2257 	int drain;
2258 	uint32_t i;
2259 
2260 	p = container_of(svms, struct kfd_process, svms);
2261 
2262 restart:
2263 	drain = atomic_read(&svms->drain_pagefaults);
2264 	if (!drain)
2265 		return;
2266 
2267 	for_each_set_bit(i, svms->bitmap_supported, p->n_pdds) {
2268 		pdd = p->pdds[i];
2269 		if (!pdd)
2270 			continue;
2271 
2272 		pr_debug("drain retry fault gpu %d svms %p\n", i, svms);
2273 
2274 		amdgpu_ih_wait_on_checkpoint_process_ts(pdd->dev->adev,
2275 				pdd->dev->adev->irq.retry_cam_enabled ?
2276 				&pdd->dev->adev->irq.ih :
2277 				&pdd->dev->adev->irq.ih1);
2278 
2279 		if (pdd->dev->adev->irq.retry_cam_enabled)
2280 			amdgpu_ih_wait_on_checkpoint_process_ts(pdd->dev->adev,
2281 				&pdd->dev->adev->irq.ih_soft);
2282 
2283 
2284 		pr_debug("drain retry fault gpu %d svms 0x%p done\n", i, svms);
2285 	}
2286 	if (atomic_cmpxchg(&svms->drain_pagefaults, drain, 0) != drain)
2287 		goto restart;
2288 }
2289 
2290 static void svm_range_deferred_list_work(struct work_struct *work)
2291 {
2292 	struct svm_range_list *svms;
2293 	struct svm_range *prange;
2294 	struct mm_struct *mm;
2295 
2296 	svms = container_of(work, struct svm_range_list, deferred_list_work);
2297 	pr_debug("enter svms 0x%p\n", svms);
2298 
2299 	spin_lock(&svms->deferred_list_lock);
2300 	while (!list_empty(&svms->deferred_range_list)) {
2301 		prange = list_first_entry(&svms->deferred_range_list,
2302 					  struct svm_range, deferred_list);
2303 		spin_unlock(&svms->deferred_list_lock);
2304 
2305 		pr_debug("prange 0x%p [0x%lx 0x%lx] op %d\n", prange,
2306 			 prange->start, prange->last, prange->work_item.op);
2307 
2308 		mm = prange->work_item.mm;
2309 retry:
2310 		mmap_write_lock(mm);
2311 
2312 		/* Checking for the need to drain retry faults must be inside
2313 		 * mmap write lock to serialize with munmap notifiers.
2314 		 */
2315 		if (unlikely(atomic_read(&svms->drain_pagefaults))) {
2316 			mmap_write_unlock(mm);
2317 			svm_range_drain_retry_fault(svms);
2318 			goto retry;
2319 		}
2320 
2321 		/* Remove from deferred_list must be inside mmap write lock, for
2322 		 * two race cases:
2323 		 * 1. unmap_from_cpu may change work_item.op and add the range
2324 		 *    to deferred_list again, cause use after free bug.
2325 		 * 2. svm_range_list_lock_and_flush_work may hold mmap write
2326 		 *    lock and continue because deferred_list is empty, but
2327 		 *    deferred_list work is actually waiting for mmap lock.
2328 		 */
2329 		spin_lock(&svms->deferred_list_lock);
2330 		list_del_init(&prange->deferred_list);
2331 		spin_unlock(&svms->deferred_list_lock);
2332 
2333 		mutex_lock(&svms->lock);
2334 		mutex_lock(&prange->migrate_mutex);
2335 		while (!list_empty(&prange->child_list)) {
2336 			struct svm_range *pchild;
2337 
2338 			pchild = list_first_entry(&prange->child_list,
2339 						struct svm_range, child_list);
2340 			pr_debug("child prange 0x%p op %d\n", pchild,
2341 				 pchild->work_item.op);
2342 			list_del_init(&pchild->child_list);
2343 			svm_range_handle_list_op(svms, pchild, mm);
2344 		}
2345 		mutex_unlock(&prange->migrate_mutex);
2346 
2347 		svm_range_handle_list_op(svms, prange, mm);
2348 		mutex_unlock(&svms->lock);
2349 		mmap_write_unlock(mm);
2350 
2351 		/* Pairs with mmget in svm_range_add_list_work */
2352 		mmput(mm);
2353 
2354 		spin_lock(&svms->deferred_list_lock);
2355 	}
2356 	spin_unlock(&svms->deferred_list_lock);
2357 	pr_debug("exit svms 0x%p\n", svms);
2358 }
2359 
2360 void
2361 svm_range_add_list_work(struct svm_range_list *svms, struct svm_range *prange,
2362 			struct mm_struct *mm, enum svm_work_list_ops op)
2363 {
2364 	spin_lock(&svms->deferred_list_lock);
2365 	/* if prange is on the deferred list */
2366 	if (!list_empty(&prange->deferred_list)) {
2367 		pr_debug("update exist prange 0x%p work op %d\n", prange, op);
2368 		WARN_ONCE(prange->work_item.mm != mm, "unmatch mm\n");
2369 		if (op != SVM_OP_NULL &&
2370 		    prange->work_item.op != SVM_OP_UNMAP_RANGE)
2371 			prange->work_item.op = op;
2372 	} else {
2373 		prange->work_item.op = op;
2374 
2375 		/* Pairs with mmput in deferred_list_work */
2376 		mmget(mm);
2377 		prange->work_item.mm = mm;
2378 		list_add_tail(&prange->deferred_list,
2379 			      &prange->svms->deferred_range_list);
2380 		pr_debug("add prange 0x%p [0x%lx 0x%lx] to work list op %d\n",
2381 			 prange, prange->start, prange->last, op);
2382 	}
2383 	spin_unlock(&svms->deferred_list_lock);
2384 }
2385 
2386 void schedule_deferred_list_work(struct svm_range_list *svms)
2387 {
2388 	spin_lock(&svms->deferred_list_lock);
2389 	if (!list_empty(&svms->deferred_range_list))
2390 		schedule_work(&svms->deferred_list_work);
2391 	spin_unlock(&svms->deferred_list_lock);
2392 }
2393 
2394 static void
2395 svm_range_unmap_split(struct mm_struct *mm, struct svm_range *parent,
2396 		      struct svm_range *prange, unsigned long start,
2397 		      unsigned long last)
2398 {
2399 	struct svm_range *head;
2400 	struct svm_range *tail;
2401 
2402 	if (prange->work_item.op == SVM_OP_UNMAP_RANGE) {
2403 		pr_debug("prange 0x%p [0x%lx 0x%lx] is already freed\n", prange,
2404 			 prange->start, prange->last);
2405 		return;
2406 	}
2407 	if (start > prange->last || last < prange->start)
2408 		return;
2409 
2410 	head = tail = prange;
2411 	if (start > prange->start)
2412 		svm_range_split(prange, prange->start, start - 1, &tail);
2413 	if (last < tail->last)
2414 		svm_range_split(tail, last + 1, tail->last, &head);
2415 
2416 	if (head != prange && tail != prange) {
2417 		svm_range_add_child(parent, mm, head, SVM_OP_UNMAP_RANGE);
2418 		svm_range_add_child(parent, mm, tail, SVM_OP_ADD_RANGE);
2419 	} else if (tail != prange) {
2420 		svm_range_add_child(parent, mm, tail, SVM_OP_UNMAP_RANGE);
2421 	} else if (head != prange) {
2422 		svm_range_add_child(parent, mm, head, SVM_OP_UNMAP_RANGE);
2423 	} else if (parent != prange) {
2424 		prange->work_item.op = SVM_OP_UNMAP_RANGE;
2425 	}
2426 }
2427 
2428 static void
2429 svm_range_unmap_from_cpu(struct mm_struct *mm, struct svm_range *prange,
2430 			 unsigned long start, unsigned long last)
2431 {
2432 	uint32_t trigger = KFD_SVM_UNMAP_TRIGGER_UNMAP_FROM_CPU;
2433 	struct svm_range_list *svms;
2434 	struct svm_range *pchild;
2435 	struct kfd_process *p;
2436 	unsigned long s, l;
2437 	bool unmap_parent;
2438 
2439 	p = kfd_lookup_process_by_mm(mm);
2440 	if (!p)
2441 		return;
2442 	svms = &p->svms;
2443 
2444 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] [0x%lx 0x%lx]\n", svms,
2445 		 prange, prange->start, prange->last, start, last);
2446 
2447 	/* Make sure pending page faults are drained in the deferred worker
2448 	 * before the range is freed to avoid straggler interrupts on
2449 	 * unmapped memory causing "phantom faults".
2450 	 */
2451 	atomic_inc(&svms->drain_pagefaults);
2452 
2453 	unmap_parent = start <= prange->start && last >= prange->last;
2454 
2455 	list_for_each_entry(pchild, &prange->child_list, child_list) {
2456 		mutex_lock_nested(&pchild->lock, 1);
2457 		s = max(start, pchild->start);
2458 		l = min(last, pchild->last);
2459 		if (l >= s)
2460 			svm_range_unmap_from_gpus(pchild, s, l, trigger);
2461 		svm_range_unmap_split(mm, prange, pchild, start, last);
2462 		mutex_unlock(&pchild->lock);
2463 	}
2464 	s = max(start, prange->start);
2465 	l = min(last, prange->last);
2466 	if (l >= s)
2467 		svm_range_unmap_from_gpus(prange, s, l, trigger);
2468 	svm_range_unmap_split(mm, prange, prange, start, last);
2469 
2470 	if (unmap_parent)
2471 		svm_range_add_list_work(svms, prange, mm, SVM_OP_UNMAP_RANGE);
2472 	else
2473 		svm_range_add_list_work(svms, prange, mm,
2474 					SVM_OP_UPDATE_RANGE_NOTIFIER);
2475 	schedule_deferred_list_work(svms);
2476 
2477 	kfd_unref_process(p);
2478 }
2479 
2480 /**
2481  * svm_range_cpu_invalidate_pagetables - interval notifier callback
2482  * @mni: mmu_interval_notifier struct
2483  * @range: mmu_notifier_range struct
2484  * @cur_seq: value to pass to mmu_interval_set_seq()
2485  *
2486  * If event is MMU_NOTIFY_UNMAP, this is from CPU unmap range, otherwise, it
2487  * is from migration, or CPU page invalidation callback.
2488  *
2489  * For unmap event, unmap range from GPUs, remove prange from svms in a delayed
2490  * work thread, and split prange if only part of prange is unmapped.
2491  *
2492  * For invalidation event, if GPU retry fault is not enabled, evict the queues,
2493  * then schedule svm_range_restore_work to update GPU mapping and resume queues.
2494  * If GPU retry fault is enabled, unmap the svm range from GPU, retry fault will
2495  * update GPU mapping to recover.
2496  *
2497  * Context: mmap lock, notifier_invalidate_start lock are held
2498  *          for invalidate event, prange lock is held if this is from migration
2499  */
2500 static bool
2501 svm_range_cpu_invalidate_pagetables(struct mmu_interval_notifier *mni,
2502 				    const struct mmu_notifier_range *range,
2503 				    unsigned long cur_seq)
2504 {
2505 	struct svm_range *prange;
2506 	unsigned long start;
2507 	unsigned long last;
2508 
2509 	if (range->event == MMU_NOTIFY_RELEASE)
2510 		return true;
2511 	if (!mmget_not_zero(mni->mm))
2512 		return true;
2513 
2514 	start = mni->interval_tree.start;
2515 	last = mni->interval_tree.last;
2516 	start = max(start, range->start) >> PAGE_SHIFT;
2517 	last = min(last, range->end - 1) >> PAGE_SHIFT;
2518 	pr_debug("[0x%lx 0x%lx] range[0x%lx 0x%lx] notifier[0x%lx 0x%lx] %d\n",
2519 		 start, last, range->start >> PAGE_SHIFT,
2520 		 (range->end - 1) >> PAGE_SHIFT,
2521 		 mni->interval_tree.start >> PAGE_SHIFT,
2522 		 mni->interval_tree.last >> PAGE_SHIFT, range->event);
2523 
2524 	prange = container_of(mni, struct svm_range, notifier);
2525 
2526 	svm_range_lock(prange);
2527 	mmu_interval_set_seq(mni, cur_seq);
2528 
2529 	switch (range->event) {
2530 	case MMU_NOTIFY_UNMAP:
2531 		svm_range_unmap_from_cpu(mni->mm, prange, start, last);
2532 		break;
2533 	default:
2534 		svm_range_evict(prange, mni->mm, start, last, range->event);
2535 		break;
2536 	}
2537 
2538 	svm_range_unlock(prange);
2539 	mmput(mni->mm);
2540 
2541 	return true;
2542 }
2543 
2544 /**
2545  * svm_range_from_addr - find svm range from fault address
2546  * @svms: svm range list header
2547  * @addr: address to search range interval tree, in pages
2548  * @parent: parent range if range is on child list
2549  *
2550  * Context: The caller must hold svms->lock
2551  *
2552  * Return: the svm_range found or NULL
2553  */
2554 struct svm_range *
2555 svm_range_from_addr(struct svm_range_list *svms, unsigned long addr,
2556 		    struct svm_range **parent)
2557 {
2558 	struct interval_tree_node *node;
2559 	struct svm_range *prange;
2560 	struct svm_range *pchild;
2561 
2562 	node = interval_tree_iter_first(&svms->objects, addr, addr);
2563 	if (!node)
2564 		return NULL;
2565 
2566 	prange = container_of(node, struct svm_range, it_node);
2567 	pr_debug("address 0x%lx prange [0x%lx 0x%lx] node [0x%lx 0x%lx]\n",
2568 		 addr, prange->start, prange->last, node->start, node->last);
2569 
2570 	if (addr >= prange->start && addr <= prange->last) {
2571 		if (parent)
2572 			*parent = prange;
2573 		return prange;
2574 	}
2575 	list_for_each_entry(pchild, &prange->child_list, child_list)
2576 		if (addr >= pchild->start && addr <= pchild->last) {
2577 			pr_debug("found address 0x%lx pchild [0x%lx 0x%lx]\n",
2578 				 addr, pchild->start, pchild->last);
2579 			if (parent)
2580 				*parent = prange;
2581 			return pchild;
2582 		}
2583 
2584 	return NULL;
2585 }
2586 
2587 /* svm_range_best_restore_location - decide the best fault restore location
2588  * @prange: svm range structure
2589  * @adev: the GPU on which vm fault happened
2590  *
2591  * This is only called when xnack is on, to decide the best location to restore
2592  * the range mapping after GPU vm fault. Caller uses the best location to do
2593  * migration if actual loc is not best location, then update GPU page table
2594  * mapping to the best location.
2595  *
2596  * If the preferred loc is accessible by faulting GPU, use preferred loc.
2597  * If vm fault gpu idx is on range ACCESSIBLE bitmap, best_loc is vm fault gpu
2598  * If vm fault gpu idx is on range ACCESSIBLE_IN_PLACE bitmap, then
2599  *    if range actual loc is cpu, best_loc is cpu
2600  *    if vm fault gpu is on xgmi same hive of range actual loc gpu, best_loc is
2601  *    range actual loc.
2602  * Otherwise, GPU no access, best_loc is -1.
2603  *
2604  * Return:
2605  * -1 means vm fault GPU no access
2606  * 0 for CPU or GPU id
2607  */
2608 static int32_t
2609 svm_range_best_restore_location(struct svm_range *prange,
2610 				struct kfd_node *node,
2611 				int32_t *gpuidx)
2612 {
2613 	struct kfd_node *bo_node, *preferred_node;
2614 	struct kfd_process *p;
2615 	uint32_t gpuid;
2616 	int r;
2617 
2618 	p = container_of(prange->svms, struct kfd_process, svms);
2619 
2620 	r = kfd_process_gpuid_from_node(p, node, &gpuid, gpuidx);
2621 	if (r < 0) {
2622 		pr_debug("failed to get gpuid from kgd\n");
2623 		return -1;
2624 	}
2625 
2626 	if (node->adev->gmc.is_app_apu)
2627 		return 0;
2628 
2629 	if (prange->preferred_loc == gpuid ||
2630 	    prange->preferred_loc == KFD_IOCTL_SVM_LOCATION_SYSMEM) {
2631 		return prange->preferred_loc;
2632 	} else if (prange->preferred_loc != KFD_IOCTL_SVM_LOCATION_UNDEFINED) {
2633 		preferred_node = svm_range_get_node_by_id(prange, prange->preferred_loc);
2634 		if (preferred_node && svm_nodes_in_same_hive(node, preferred_node))
2635 			return prange->preferred_loc;
2636 		/* fall through */
2637 	}
2638 
2639 	if (test_bit(*gpuidx, prange->bitmap_access))
2640 		return gpuid;
2641 
2642 	if (test_bit(*gpuidx, prange->bitmap_aip)) {
2643 		if (!prange->actual_loc)
2644 			return 0;
2645 
2646 		bo_node = svm_range_get_node_by_id(prange, prange->actual_loc);
2647 		if (bo_node && svm_nodes_in_same_hive(node, bo_node))
2648 			return prange->actual_loc;
2649 		else
2650 			return 0;
2651 	}
2652 
2653 	return -1;
2654 }
2655 
2656 static int
2657 svm_range_get_range_boundaries(struct kfd_process *p, int64_t addr,
2658 			       unsigned long *start, unsigned long *last,
2659 			       bool *is_heap_stack)
2660 {
2661 	struct vm_area_struct *vma;
2662 	struct interval_tree_node *node;
2663 	unsigned long start_limit, end_limit;
2664 
2665 	vma = vma_lookup(p->mm, addr << PAGE_SHIFT);
2666 	if (!vma) {
2667 		pr_debug("VMA does not exist in address [0x%llx]\n", addr);
2668 		return -EFAULT;
2669 	}
2670 
2671 	*is_heap_stack = vma_is_initial_heap(vma) || vma_is_initial_stack(vma);
2672 
2673 	start_limit = max(vma->vm_start >> PAGE_SHIFT,
2674 		      (unsigned long)ALIGN_DOWN(addr, 2UL << 8));
2675 	end_limit = min(vma->vm_end >> PAGE_SHIFT,
2676 		    (unsigned long)ALIGN(addr + 1, 2UL << 8));
2677 	/* First range that starts after the fault address */
2678 	node = interval_tree_iter_first(&p->svms.objects, addr + 1, ULONG_MAX);
2679 	if (node) {
2680 		end_limit = min(end_limit, node->start);
2681 		/* Last range that ends before the fault address */
2682 		node = container_of(rb_prev(&node->rb),
2683 				    struct interval_tree_node, rb);
2684 	} else {
2685 		/* Last range must end before addr because
2686 		 * there was no range after addr
2687 		 */
2688 		node = container_of(rb_last(&p->svms.objects.rb_root),
2689 				    struct interval_tree_node, rb);
2690 	}
2691 	if (node) {
2692 		if (node->last >= addr) {
2693 			WARN(1, "Overlap with prev node and page fault addr\n");
2694 			return -EFAULT;
2695 		}
2696 		start_limit = max(start_limit, node->last + 1);
2697 	}
2698 
2699 	*start = start_limit;
2700 	*last = end_limit - 1;
2701 
2702 	pr_debug("vma [0x%lx 0x%lx] range [0x%lx 0x%lx] is_heap_stack %d\n",
2703 		 vma->vm_start >> PAGE_SHIFT, vma->vm_end >> PAGE_SHIFT,
2704 		 *start, *last, *is_heap_stack);
2705 
2706 	return 0;
2707 }
2708 
2709 static int
2710 svm_range_check_vm_userptr(struct kfd_process *p, uint64_t start, uint64_t last,
2711 			   uint64_t *bo_s, uint64_t *bo_l)
2712 {
2713 	struct amdgpu_bo_va_mapping *mapping;
2714 	struct interval_tree_node *node;
2715 	struct amdgpu_bo *bo = NULL;
2716 	unsigned long userptr;
2717 	uint32_t i;
2718 	int r;
2719 
2720 	for (i = 0; i < p->n_pdds; i++) {
2721 		struct amdgpu_vm *vm;
2722 
2723 		if (!p->pdds[i]->drm_priv)
2724 			continue;
2725 
2726 		vm = drm_priv_to_vm(p->pdds[i]->drm_priv);
2727 		r = amdgpu_bo_reserve(vm->root.bo, false);
2728 		if (r)
2729 			return r;
2730 
2731 		/* Check userptr by searching entire vm->va interval tree */
2732 		node = interval_tree_iter_first(&vm->va, 0, ~0ULL);
2733 		while (node) {
2734 			mapping = container_of((struct rb_node *)node,
2735 					       struct amdgpu_bo_va_mapping, rb);
2736 			bo = mapping->bo_va->base.bo;
2737 
2738 			if (!amdgpu_ttm_tt_affect_userptr(bo->tbo.ttm,
2739 							 start << PAGE_SHIFT,
2740 							 last << PAGE_SHIFT,
2741 							 &userptr)) {
2742 				node = interval_tree_iter_next(node, 0, ~0ULL);
2743 				continue;
2744 			}
2745 
2746 			pr_debug("[0x%llx 0x%llx] already userptr mapped\n",
2747 				 start, last);
2748 			if (bo_s && bo_l) {
2749 				*bo_s = userptr >> PAGE_SHIFT;
2750 				*bo_l = *bo_s + bo->tbo.ttm->num_pages - 1;
2751 			}
2752 			amdgpu_bo_unreserve(vm->root.bo);
2753 			return -EADDRINUSE;
2754 		}
2755 		amdgpu_bo_unreserve(vm->root.bo);
2756 	}
2757 	return 0;
2758 }
2759 
2760 static struct
2761 svm_range *svm_range_create_unregistered_range(struct kfd_node *node,
2762 						struct kfd_process *p,
2763 						struct mm_struct *mm,
2764 						int64_t addr)
2765 {
2766 	struct svm_range *prange = NULL;
2767 	unsigned long start, last;
2768 	uint32_t gpuid, gpuidx;
2769 	bool is_heap_stack;
2770 	uint64_t bo_s = 0;
2771 	uint64_t bo_l = 0;
2772 	int r;
2773 
2774 	if (svm_range_get_range_boundaries(p, addr, &start, &last,
2775 					   &is_heap_stack))
2776 		return NULL;
2777 
2778 	r = svm_range_check_vm(p, start, last, &bo_s, &bo_l);
2779 	if (r != -EADDRINUSE)
2780 		r = svm_range_check_vm_userptr(p, start, last, &bo_s, &bo_l);
2781 
2782 	if (r == -EADDRINUSE) {
2783 		if (addr >= bo_s && addr <= bo_l)
2784 			return NULL;
2785 
2786 		/* Create one page svm range if 2MB range overlapping */
2787 		start = addr;
2788 		last = addr;
2789 	}
2790 
2791 	prange = svm_range_new(&p->svms, start, last, true);
2792 	if (!prange) {
2793 		pr_debug("Failed to create prange in address [0x%llx]\n", addr);
2794 		return NULL;
2795 	}
2796 	if (kfd_process_gpuid_from_node(p, node, &gpuid, &gpuidx)) {
2797 		pr_debug("failed to get gpuid from kgd\n");
2798 		svm_range_free(prange, true);
2799 		return NULL;
2800 	}
2801 
2802 	if (is_heap_stack)
2803 		prange->preferred_loc = KFD_IOCTL_SVM_LOCATION_SYSMEM;
2804 
2805 	svm_range_add_to_svms(prange);
2806 	svm_range_add_notifier_locked(mm, prange);
2807 
2808 	return prange;
2809 }
2810 
2811 /* svm_range_skip_recover - decide if prange can be recovered
2812  * @prange: svm range structure
2813  *
2814  * GPU vm retry fault handle skip recover the range for cases:
2815  * 1. prange is on deferred list to be removed after unmap, it is stale fault,
2816  *    deferred list work will drain the stale fault before free the prange.
2817  * 2. prange is on deferred list to add interval notifier after split, or
2818  * 3. prange is child range, it is split from parent prange, recover later
2819  *    after interval notifier is added.
2820  *
2821  * Return: true to skip recover, false to recover
2822  */
2823 static bool svm_range_skip_recover(struct svm_range *prange)
2824 {
2825 	struct svm_range_list *svms = prange->svms;
2826 
2827 	spin_lock(&svms->deferred_list_lock);
2828 	if (list_empty(&prange->deferred_list) &&
2829 	    list_empty(&prange->child_list)) {
2830 		spin_unlock(&svms->deferred_list_lock);
2831 		return false;
2832 	}
2833 	spin_unlock(&svms->deferred_list_lock);
2834 
2835 	if (prange->work_item.op == SVM_OP_UNMAP_RANGE) {
2836 		pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] unmapped\n",
2837 			 svms, prange, prange->start, prange->last);
2838 		return true;
2839 	}
2840 	if (prange->work_item.op == SVM_OP_ADD_RANGE_AND_MAP ||
2841 	    prange->work_item.op == SVM_OP_ADD_RANGE) {
2842 		pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] not added yet\n",
2843 			 svms, prange, prange->start, prange->last);
2844 		return true;
2845 	}
2846 	return false;
2847 }
2848 
2849 static void
2850 svm_range_count_fault(struct kfd_node *node, struct kfd_process *p,
2851 		      int32_t gpuidx)
2852 {
2853 	struct kfd_process_device *pdd;
2854 
2855 	/* fault is on different page of same range
2856 	 * or fault is skipped to recover later
2857 	 * or fault is on invalid virtual address
2858 	 */
2859 	if (gpuidx == MAX_GPU_INSTANCE) {
2860 		uint32_t gpuid;
2861 		int r;
2862 
2863 		r = kfd_process_gpuid_from_node(p, node, &gpuid, &gpuidx);
2864 		if (r < 0)
2865 			return;
2866 	}
2867 
2868 	/* fault is recovered
2869 	 * or fault cannot recover because GPU no access on the range
2870 	 */
2871 	pdd = kfd_process_device_from_gpuidx(p, gpuidx);
2872 	if (pdd)
2873 		WRITE_ONCE(pdd->faults, pdd->faults + 1);
2874 }
2875 
2876 static bool
2877 svm_fault_allowed(struct vm_area_struct *vma, bool write_fault)
2878 {
2879 	unsigned long requested = VM_READ;
2880 
2881 	if (write_fault)
2882 		requested |= VM_WRITE;
2883 
2884 	pr_debug("requested 0x%lx, vma permission flags 0x%lx\n", requested,
2885 		vma->vm_flags);
2886 	return (vma->vm_flags & requested) == requested;
2887 }
2888 
2889 int
2890 svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid,
2891 			uint32_t vmid, uint32_t node_id,
2892 			uint64_t addr, bool write_fault)
2893 {
2894 	struct mm_struct *mm = NULL;
2895 	struct svm_range_list *svms;
2896 	struct svm_range *prange;
2897 	struct kfd_process *p;
2898 	ktime_t timestamp = ktime_get_boottime();
2899 	struct kfd_node *node;
2900 	int32_t best_loc;
2901 	int32_t gpuidx = MAX_GPU_INSTANCE;
2902 	bool write_locked = false;
2903 	struct vm_area_struct *vma;
2904 	bool migration = false;
2905 	int r = 0;
2906 
2907 	if (!KFD_IS_SVM_API_SUPPORTED(adev)) {
2908 		pr_debug("device does not support SVM\n");
2909 		return -EFAULT;
2910 	}
2911 
2912 	p = kfd_lookup_process_by_pasid(pasid);
2913 	if (!p) {
2914 		pr_debug("kfd process not founded pasid 0x%x\n", pasid);
2915 		return 0;
2916 	}
2917 	svms = &p->svms;
2918 
2919 	pr_debug("restoring svms 0x%p fault address 0x%llx\n", svms, addr);
2920 
2921 	if (atomic_read(&svms->drain_pagefaults)) {
2922 		pr_debug("draining retry fault, drop fault 0x%llx\n", addr);
2923 		r = 0;
2924 		goto out;
2925 	}
2926 
2927 	if (!p->xnack_enabled) {
2928 		pr_debug("XNACK not enabled for pasid 0x%x\n", pasid);
2929 		r = -EFAULT;
2930 		goto out;
2931 	}
2932 
2933 	/* p->lead_thread is available as kfd_process_wq_release flush the work
2934 	 * before releasing task ref.
2935 	 */
2936 	mm = get_task_mm(p->lead_thread);
2937 	if (!mm) {
2938 		pr_debug("svms 0x%p failed to get mm\n", svms);
2939 		r = 0;
2940 		goto out;
2941 	}
2942 
2943 	node = kfd_node_by_irq_ids(adev, node_id, vmid);
2944 	if (!node) {
2945 		pr_debug("kfd node does not exist node_id: %d, vmid: %d\n", node_id,
2946 			 vmid);
2947 		r = -EFAULT;
2948 		goto out;
2949 	}
2950 	mmap_read_lock(mm);
2951 retry_write_locked:
2952 	mutex_lock(&svms->lock);
2953 	prange = svm_range_from_addr(svms, addr, NULL);
2954 	if (!prange) {
2955 		pr_debug("failed to find prange svms 0x%p address [0x%llx]\n",
2956 			 svms, addr);
2957 		if (!write_locked) {
2958 			/* Need the write lock to create new range with MMU notifier.
2959 			 * Also flush pending deferred work to make sure the interval
2960 			 * tree is up to date before we add a new range
2961 			 */
2962 			mutex_unlock(&svms->lock);
2963 			mmap_read_unlock(mm);
2964 			mmap_write_lock(mm);
2965 			write_locked = true;
2966 			goto retry_write_locked;
2967 		}
2968 		prange = svm_range_create_unregistered_range(node, p, mm, addr);
2969 		if (!prange) {
2970 			pr_debug("failed to create unregistered range svms 0x%p address [0x%llx]\n",
2971 				 svms, addr);
2972 			mmap_write_downgrade(mm);
2973 			r = -EFAULT;
2974 			goto out_unlock_svms;
2975 		}
2976 	}
2977 	if (write_locked)
2978 		mmap_write_downgrade(mm);
2979 
2980 	mutex_lock(&prange->migrate_mutex);
2981 
2982 	if (svm_range_skip_recover(prange)) {
2983 		amdgpu_gmc_filter_faults_remove(node->adev, addr, pasid);
2984 		r = 0;
2985 		goto out_unlock_range;
2986 	}
2987 
2988 	/* skip duplicate vm fault on different pages of same range */
2989 	if (ktime_before(timestamp, ktime_add_ns(prange->validate_timestamp,
2990 				AMDGPU_SVM_RANGE_RETRY_FAULT_PENDING))) {
2991 		pr_debug("svms 0x%p [0x%lx %lx] already restored\n",
2992 			 svms, prange->start, prange->last);
2993 		r = 0;
2994 		goto out_unlock_range;
2995 	}
2996 
2997 	/* __do_munmap removed VMA, return success as we are handling stale
2998 	 * retry fault.
2999 	 */
3000 	vma = vma_lookup(mm, addr << PAGE_SHIFT);
3001 	if (!vma) {
3002 		pr_debug("address 0x%llx VMA is removed\n", addr);
3003 		r = 0;
3004 		goto out_unlock_range;
3005 	}
3006 
3007 	if (!svm_fault_allowed(vma, write_fault)) {
3008 		pr_debug("fault addr 0x%llx no %s permission\n", addr,
3009 			write_fault ? "write" : "read");
3010 		r = -EPERM;
3011 		goto out_unlock_range;
3012 	}
3013 
3014 	best_loc = svm_range_best_restore_location(prange, node, &gpuidx);
3015 	if (best_loc == -1) {
3016 		pr_debug("svms %p failed get best restore loc [0x%lx 0x%lx]\n",
3017 			 svms, prange->start, prange->last);
3018 		r = -EACCES;
3019 		goto out_unlock_range;
3020 	}
3021 
3022 	pr_debug("svms %p [0x%lx 0x%lx] best restore 0x%x, actual loc 0x%x\n",
3023 		 svms, prange->start, prange->last, best_loc,
3024 		 prange->actual_loc);
3025 
3026 	kfd_smi_event_page_fault_start(node, p->lead_thread->pid, addr,
3027 				       write_fault, timestamp);
3028 
3029 	if (prange->actual_loc != best_loc) {
3030 		migration = true;
3031 		if (best_loc) {
3032 			r = svm_migrate_to_vram(prange, best_loc, mm,
3033 					KFD_MIGRATE_TRIGGER_PAGEFAULT_GPU);
3034 			if (r) {
3035 				pr_debug("svm_migrate_to_vram failed (%d) at %llx, falling back to system memory\n",
3036 					 r, addr);
3037 				/* Fallback to system memory if migration to
3038 				 * VRAM failed
3039 				 */
3040 				if (prange->actual_loc)
3041 					r = svm_migrate_vram_to_ram(prange, mm,
3042 					   KFD_MIGRATE_TRIGGER_PAGEFAULT_GPU,
3043 					   NULL);
3044 				else
3045 					r = 0;
3046 			}
3047 		} else {
3048 			r = svm_migrate_vram_to_ram(prange, mm,
3049 					KFD_MIGRATE_TRIGGER_PAGEFAULT_GPU,
3050 					NULL);
3051 		}
3052 		if (r) {
3053 			pr_debug("failed %d to migrate svms %p [0x%lx 0x%lx]\n",
3054 				 r, svms, prange->start, prange->last);
3055 			goto out_unlock_range;
3056 		}
3057 	}
3058 
3059 	r = svm_range_validate_and_map(mm, prange, gpuidx, false, false, false);
3060 	if (r)
3061 		pr_debug("failed %d to map svms 0x%p [0x%lx 0x%lx] to gpus\n",
3062 			 r, svms, prange->start, prange->last);
3063 
3064 	kfd_smi_event_page_fault_end(node, p->lead_thread->pid, addr,
3065 				     migration);
3066 
3067 out_unlock_range:
3068 	mutex_unlock(&prange->migrate_mutex);
3069 out_unlock_svms:
3070 	mutex_unlock(&svms->lock);
3071 	mmap_read_unlock(mm);
3072 
3073 	svm_range_count_fault(node, p, gpuidx);
3074 
3075 	mmput(mm);
3076 out:
3077 	kfd_unref_process(p);
3078 
3079 	if (r == -EAGAIN) {
3080 		pr_debug("recover vm fault later\n");
3081 		amdgpu_gmc_filter_faults_remove(node->adev, addr, pasid);
3082 		r = 0;
3083 	}
3084 	return r;
3085 }
3086 
3087 int
3088 svm_range_switch_xnack_reserve_mem(struct kfd_process *p, bool xnack_enabled)
3089 {
3090 	struct svm_range *prange, *pchild;
3091 	uint64_t reserved_size = 0;
3092 	uint64_t size;
3093 	int r = 0;
3094 
3095 	pr_debug("switching xnack from %d to %d\n", p->xnack_enabled, xnack_enabled);
3096 
3097 	mutex_lock(&p->svms.lock);
3098 
3099 	list_for_each_entry(prange, &p->svms.list, list) {
3100 		svm_range_lock(prange);
3101 		list_for_each_entry(pchild, &prange->child_list, child_list) {
3102 			size = (pchild->last - pchild->start + 1) << PAGE_SHIFT;
3103 			if (xnack_enabled) {
3104 				amdgpu_amdkfd_unreserve_mem_limit(NULL, size,
3105 					KFD_IOC_ALLOC_MEM_FLAGS_USERPTR, 0);
3106 			} else {
3107 				r = amdgpu_amdkfd_reserve_mem_limit(NULL, size,
3108 					KFD_IOC_ALLOC_MEM_FLAGS_USERPTR, 0);
3109 				if (r)
3110 					goto out_unlock;
3111 				reserved_size += size;
3112 			}
3113 		}
3114 
3115 		size = (prange->last - prange->start + 1) << PAGE_SHIFT;
3116 		if (xnack_enabled) {
3117 			amdgpu_amdkfd_unreserve_mem_limit(NULL, size,
3118 					KFD_IOC_ALLOC_MEM_FLAGS_USERPTR, 0);
3119 		} else {
3120 			r = amdgpu_amdkfd_reserve_mem_limit(NULL, size,
3121 					KFD_IOC_ALLOC_MEM_FLAGS_USERPTR, 0);
3122 			if (r)
3123 				goto out_unlock;
3124 			reserved_size += size;
3125 		}
3126 out_unlock:
3127 		svm_range_unlock(prange);
3128 		if (r)
3129 			break;
3130 	}
3131 
3132 	if (r)
3133 		amdgpu_amdkfd_unreserve_mem_limit(NULL, reserved_size,
3134 					KFD_IOC_ALLOC_MEM_FLAGS_USERPTR, 0);
3135 	else
3136 		/* Change xnack mode must be inside svms lock, to avoid race with
3137 		 * svm_range_deferred_list_work unreserve memory in parallel.
3138 		 */
3139 		p->xnack_enabled = xnack_enabled;
3140 
3141 	mutex_unlock(&p->svms.lock);
3142 	return r;
3143 }
3144 
3145 void svm_range_list_fini(struct kfd_process *p)
3146 {
3147 	struct svm_range *prange;
3148 	struct svm_range *next;
3149 
3150 	pr_debug("pasid 0x%x svms 0x%p\n", p->pasid, &p->svms);
3151 
3152 	cancel_delayed_work_sync(&p->svms.restore_work);
3153 
3154 	/* Ensure list work is finished before process is destroyed */
3155 	flush_work(&p->svms.deferred_list_work);
3156 
3157 	/*
3158 	 * Ensure no retry fault comes in afterwards, as page fault handler will
3159 	 * not find kfd process and take mm lock to recover fault.
3160 	 */
3161 	atomic_inc(&p->svms.drain_pagefaults);
3162 	svm_range_drain_retry_fault(&p->svms);
3163 
3164 	list_for_each_entry_safe(prange, next, &p->svms.list, list) {
3165 		svm_range_unlink(prange);
3166 		svm_range_remove_notifier(prange);
3167 		svm_range_free(prange, true);
3168 	}
3169 
3170 	mutex_destroy(&p->svms.lock);
3171 
3172 	pr_debug("pasid 0x%x svms 0x%p done\n", p->pasid, &p->svms);
3173 }
3174 
3175 int svm_range_list_init(struct kfd_process *p)
3176 {
3177 	struct svm_range_list *svms = &p->svms;
3178 	int i;
3179 
3180 	svms->objects = RB_ROOT_CACHED;
3181 	mutex_init(&svms->lock);
3182 	INIT_LIST_HEAD(&svms->list);
3183 	atomic_set(&svms->evicted_ranges, 0);
3184 	atomic_set(&svms->drain_pagefaults, 0);
3185 	INIT_DELAYED_WORK(&svms->restore_work, svm_range_restore_work);
3186 	INIT_WORK(&svms->deferred_list_work, svm_range_deferred_list_work);
3187 	INIT_LIST_HEAD(&svms->deferred_range_list);
3188 	INIT_LIST_HEAD(&svms->criu_svm_metadata_list);
3189 	spin_lock_init(&svms->deferred_list_lock);
3190 
3191 	for (i = 0; i < p->n_pdds; i++)
3192 		if (KFD_IS_SVM_API_SUPPORTED(p->pdds[i]->dev->adev))
3193 			bitmap_set(svms->bitmap_supported, i, 1);
3194 
3195 	return 0;
3196 }
3197 
3198 /**
3199  * svm_range_check_vm - check if virtual address range mapped already
3200  * @p: current kfd_process
3201  * @start: range start address, in pages
3202  * @last: range last address, in pages
3203  * @bo_s: mapping start address in pages if address range already mapped
3204  * @bo_l: mapping last address in pages if address range already mapped
3205  *
3206  * The purpose is to avoid virtual address ranges already allocated by
3207  * kfd_ioctl_alloc_memory_of_gpu ioctl.
3208  * It looks for each pdd in the kfd_process.
3209  *
3210  * Context: Process context
3211  *
3212  * Return 0 - OK, if the range is not mapped.
3213  * Otherwise error code:
3214  * -EADDRINUSE - if address is mapped already by kfd_ioctl_alloc_memory_of_gpu
3215  * -ERESTARTSYS - A wait for the buffer to become unreserved was interrupted by
3216  * a signal. Release all buffer reservations and return to user-space.
3217  */
3218 static int
3219 svm_range_check_vm(struct kfd_process *p, uint64_t start, uint64_t last,
3220 		   uint64_t *bo_s, uint64_t *bo_l)
3221 {
3222 	struct amdgpu_bo_va_mapping *mapping;
3223 	struct interval_tree_node *node;
3224 	uint32_t i;
3225 	int r;
3226 
3227 	for (i = 0; i < p->n_pdds; i++) {
3228 		struct amdgpu_vm *vm;
3229 
3230 		if (!p->pdds[i]->drm_priv)
3231 			continue;
3232 
3233 		vm = drm_priv_to_vm(p->pdds[i]->drm_priv);
3234 		r = amdgpu_bo_reserve(vm->root.bo, false);
3235 		if (r)
3236 			return r;
3237 
3238 		node = interval_tree_iter_first(&vm->va, start, last);
3239 		if (node) {
3240 			pr_debug("range [0x%llx 0x%llx] already TTM mapped\n",
3241 				 start, last);
3242 			mapping = container_of((struct rb_node *)node,
3243 					       struct amdgpu_bo_va_mapping, rb);
3244 			if (bo_s && bo_l) {
3245 				*bo_s = mapping->start;
3246 				*bo_l = mapping->last;
3247 			}
3248 			amdgpu_bo_unreserve(vm->root.bo);
3249 			return -EADDRINUSE;
3250 		}
3251 		amdgpu_bo_unreserve(vm->root.bo);
3252 	}
3253 
3254 	return 0;
3255 }
3256 
3257 /**
3258  * svm_range_is_valid - check if virtual address range is valid
3259  * @p: current kfd_process
3260  * @start: range start address, in pages
3261  * @size: range size, in pages
3262  *
3263  * Valid virtual address range means it belongs to one or more VMAs
3264  *
3265  * Context: Process context
3266  *
3267  * Return:
3268  *  0 - OK, otherwise error code
3269  */
3270 static int
3271 svm_range_is_valid(struct kfd_process *p, uint64_t start, uint64_t size)
3272 {
3273 	const unsigned long device_vma = VM_IO | VM_PFNMAP | VM_MIXEDMAP;
3274 	struct vm_area_struct *vma;
3275 	unsigned long end;
3276 	unsigned long start_unchg = start;
3277 
3278 	start <<= PAGE_SHIFT;
3279 	end = start + (size << PAGE_SHIFT);
3280 	do {
3281 		vma = vma_lookup(p->mm, start);
3282 		if (!vma || (vma->vm_flags & device_vma))
3283 			return -EFAULT;
3284 		start = min(end, vma->vm_end);
3285 	} while (start < end);
3286 
3287 	return svm_range_check_vm(p, start_unchg, (end - 1) >> PAGE_SHIFT, NULL,
3288 				  NULL);
3289 }
3290 
3291 /**
3292  * svm_range_best_prefetch_location - decide the best prefetch location
3293  * @prange: svm range structure
3294  *
3295  * For xnack off:
3296  * If range map to single GPU, the best prefetch location is prefetch_loc, which
3297  * can be CPU or GPU.
3298  *
3299  * If range is ACCESS or ACCESS_IN_PLACE by mGPUs, only if mGPU connection on
3300  * XGMI same hive, the best prefetch location is prefetch_loc GPU, othervise
3301  * the best prefetch location is always CPU, because GPU can not have coherent
3302  * mapping VRAM of other GPUs even with large-BAR PCIe connection.
3303  *
3304  * For xnack on:
3305  * If range is not ACCESS_IN_PLACE by mGPUs, the best prefetch location is
3306  * prefetch_loc, other GPU access will generate vm fault and trigger migration.
3307  *
3308  * If range is ACCESS_IN_PLACE by mGPUs, only if mGPU connection on XGMI same
3309  * hive, the best prefetch location is prefetch_loc GPU, otherwise the best
3310  * prefetch location is always CPU.
3311  *
3312  * Context: Process context
3313  *
3314  * Return:
3315  * 0 for CPU or GPU id
3316  */
3317 static uint32_t
3318 svm_range_best_prefetch_location(struct svm_range *prange)
3319 {
3320 	DECLARE_BITMAP(bitmap, MAX_GPU_INSTANCE);
3321 	uint32_t best_loc = prange->prefetch_loc;
3322 	struct kfd_process_device *pdd;
3323 	struct kfd_node *bo_node;
3324 	struct kfd_process *p;
3325 	uint32_t gpuidx;
3326 
3327 	p = container_of(prange->svms, struct kfd_process, svms);
3328 
3329 	if (!best_loc || best_loc == KFD_IOCTL_SVM_LOCATION_UNDEFINED)
3330 		goto out;
3331 
3332 	bo_node = svm_range_get_node_by_id(prange, best_loc);
3333 	if (!bo_node) {
3334 		WARN_ONCE(1, "failed to get valid kfd node at id%x\n", best_loc);
3335 		best_loc = 0;
3336 		goto out;
3337 	}
3338 
3339 	if (bo_node->adev->gmc.is_app_apu) {
3340 		best_loc = 0;
3341 		goto out;
3342 	}
3343 
3344 	if (p->xnack_enabled)
3345 		bitmap_copy(bitmap, prange->bitmap_aip, MAX_GPU_INSTANCE);
3346 	else
3347 		bitmap_or(bitmap, prange->bitmap_access, prange->bitmap_aip,
3348 			  MAX_GPU_INSTANCE);
3349 
3350 	for_each_set_bit(gpuidx, bitmap, MAX_GPU_INSTANCE) {
3351 		pdd = kfd_process_device_from_gpuidx(p, gpuidx);
3352 		if (!pdd) {
3353 			pr_debug("failed to get device by idx 0x%x\n", gpuidx);
3354 			continue;
3355 		}
3356 
3357 		if (pdd->dev->adev == bo_node->adev)
3358 			continue;
3359 
3360 		if (!svm_nodes_in_same_hive(pdd->dev, bo_node)) {
3361 			best_loc = 0;
3362 			break;
3363 		}
3364 	}
3365 
3366 out:
3367 	pr_debug("xnack %d svms 0x%p [0x%lx 0x%lx] best loc 0x%x\n",
3368 		 p->xnack_enabled, &p->svms, prange->start, prange->last,
3369 		 best_loc);
3370 
3371 	return best_loc;
3372 }
3373 
3374 /* svm_range_trigger_migration - start page migration if prefetch loc changed
3375  * @mm: current process mm_struct
3376  * @prange: svm range structure
3377  * @migrated: output, true if migration is triggered
3378  *
3379  * If range perfetch_loc is GPU, actual loc is cpu 0, then migrate the range
3380  * from ram to vram.
3381  * If range prefetch_loc is cpu 0, actual loc is GPU, then migrate the range
3382  * from vram to ram.
3383  *
3384  * If GPU vm fault retry is not enabled, migration interact with MMU notifier
3385  * and restore work:
3386  * 1. migrate_vma_setup invalidate pages, MMU notifier callback svm_range_evict
3387  *    stops all queues, schedule restore work
3388  * 2. svm_range_restore_work wait for migration is done by
3389  *    a. svm_range_validate_vram takes prange->migrate_mutex
3390  *    b. svm_range_validate_ram HMM get pages wait for CPU fault handle returns
3391  * 3. restore work update mappings of GPU, resume all queues.
3392  *
3393  * Context: Process context
3394  *
3395  * Return:
3396  * 0 - OK, otherwise - error code of migration
3397  */
3398 static int
3399 svm_range_trigger_migration(struct mm_struct *mm, struct svm_range *prange,
3400 			    bool *migrated)
3401 {
3402 	uint32_t best_loc;
3403 	int r = 0;
3404 
3405 	*migrated = false;
3406 	best_loc = svm_range_best_prefetch_location(prange);
3407 
3408 	if (best_loc == KFD_IOCTL_SVM_LOCATION_UNDEFINED ||
3409 	    best_loc == prange->actual_loc)
3410 		return 0;
3411 
3412 	if (!best_loc) {
3413 		r = svm_migrate_vram_to_ram(prange, mm,
3414 					KFD_MIGRATE_TRIGGER_PREFETCH, NULL);
3415 		*migrated = !r;
3416 		return r;
3417 	}
3418 
3419 	r = svm_migrate_to_vram(prange, best_loc, mm, KFD_MIGRATE_TRIGGER_PREFETCH);
3420 	*migrated = !r;
3421 
3422 	return r;
3423 }
3424 
3425 int svm_range_schedule_evict_svm_bo(struct amdgpu_amdkfd_fence *fence)
3426 {
3427 	if (!fence)
3428 		return -EINVAL;
3429 
3430 	if (dma_fence_is_signaled(&fence->base))
3431 		return 0;
3432 
3433 	if (fence->svm_bo) {
3434 		WRITE_ONCE(fence->svm_bo->evicting, 1);
3435 		schedule_work(&fence->svm_bo->eviction_work);
3436 	}
3437 
3438 	return 0;
3439 }
3440 
3441 static void svm_range_evict_svm_bo_worker(struct work_struct *work)
3442 {
3443 	struct svm_range_bo *svm_bo;
3444 	struct mm_struct *mm;
3445 	int r = 0;
3446 
3447 	svm_bo = container_of(work, struct svm_range_bo, eviction_work);
3448 	if (!svm_bo_ref_unless_zero(svm_bo))
3449 		return; /* svm_bo was freed while eviction was pending */
3450 
3451 	if (mmget_not_zero(svm_bo->eviction_fence->mm)) {
3452 		mm = svm_bo->eviction_fence->mm;
3453 	} else {
3454 		svm_range_bo_unref(svm_bo);
3455 		return;
3456 	}
3457 
3458 	mmap_read_lock(mm);
3459 	spin_lock(&svm_bo->list_lock);
3460 	while (!list_empty(&svm_bo->range_list) && !r) {
3461 		struct svm_range *prange =
3462 				list_first_entry(&svm_bo->range_list,
3463 						struct svm_range, svm_bo_list);
3464 		int retries = 3;
3465 
3466 		list_del_init(&prange->svm_bo_list);
3467 		spin_unlock(&svm_bo->list_lock);
3468 
3469 		pr_debug("svms 0x%p [0x%lx 0x%lx]\n", prange->svms,
3470 			 prange->start, prange->last);
3471 
3472 		mutex_lock(&prange->migrate_mutex);
3473 		do {
3474 			r = svm_migrate_vram_to_ram(prange, mm,
3475 					KFD_MIGRATE_TRIGGER_TTM_EVICTION, NULL);
3476 		} while (!r && prange->actual_loc && --retries);
3477 
3478 		if (!r && prange->actual_loc)
3479 			pr_info_once("Migration failed during eviction");
3480 
3481 		if (!prange->actual_loc) {
3482 			mutex_lock(&prange->lock);
3483 			prange->svm_bo = NULL;
3484 			mutex_unlock(&prange->lock);
3485 		}
3486 		mutex_unlock(&prange->migrate_mutex);
3487 
3488 		spin_lock(&svm_bo->list_lock);
3489 	}
3490 	spin_unlock(&svm_bo->list_lock);
3491 	mmap_read_unlock(mm);
3492 	mmput(mm);
3493 
3494 	dma_fence_signal(&svm_bo->eviction_fence->base);
3495 
3496 	/* This is the last reference to svm_bo, after svm_range_vram_node_free
3497 	 * has been called in svm_migrate_vram_to_ram
3498 	 */
3499 	WARN_ONCE(!r && kref_read(&svm_bo->kref) != 1, "This was not the last reference\n");
3500 	svm_range_bo_unref(svm_bo);
3501 }
3502 
3503 static int
3504 svm_range_set_attr(struct kfd_process *p, struct mm_struct *mm,
3505 		   uint64_t start, uint64_t size, uint32_t nattr,
3506 		   struct kfd_ioctl_svm_attribute *attrs)
3507 {
3508 	struct amdkfd_process_info *process_info = p->kgd_process_info;
3509 	struct list_head update_list;
3510 	struct list_head insert_list;
3511 	struct list_head remove_list;
3512 	struct svm_range_list *svms;
3513 	struct svm_range *prange;
3514 	struct svm_range *next;
3515 	bool update_mapping = false;
3516 	bool flush_tlb;
3517 	int r, ret = 0;
3518 
3519 	pr_debug("pasid 0x%x svms 0x%p [0x%llx 0x%llx] pages 0x%llx\n",
3520 		 p->pasid, &p->svms, start, start + size - 1, size);
3521 
3522 	r = svm_range_check_attr(p, nattr, attrs);
3523 	if (r)
3524 		return r;
3525 
3526 	svms = &p->svms;
3527 
3528 	mutex_lock(&process_info->lock);
3529 
3530 	svm_range_list_lock_and_flush_work(svms, mm);
3531 
3532 	r = svm_range_is_valid(p, start, size);
3533 	if (r) {
3534 		pr_debug("invalid range r=%d\n", r);
3535 		mmap_write_unlock(mm);
3536 		goto out;
3537 	}
3538 
3539 	mutex_lock(&svms->lock);
3540 
3541 	/* Add new range and split existing ranges as needed */
3542 	r = svm_range_add(p, start, size, nattr, attrs, &update_list,
3543 			  &insert_list, &remove_list);
3544 	if (r) {
3545 		mutex_unlock(&svms->lock);
3546 		mmap_write_unlock(mm);
3547 		goto out;
3548 	}
3549 	/* Apply changes as a transaction */
3550 	list_for_each_entry_safe(prange, next, &insert_list, list) {
3551 		svm_range_add_to_svms(prange);
3552 		svm_range_add_notifier_locked(mm, prange);
3553 	}
3554 	list_for_each_entry(prange, &update_list, update_list) {
3555 		svm_range_apply_attrs(p, prange, nattr, attrs, &update_mapping);
3556 		/* TODO: unmap ranges from GPU that lost access */
3557 	}
3558 	list_for_each_entry_safe(prange, next, &remove_list, update_list) {
3559 		pr_debug("unlink old 0x%p prange 0x%p [0x%lx 0x%lx]\n",
3560 			 prange->svms, prange, prange->start,
3561 			 prange->last);
3562 		svm_range_unlink(prange);
3563 		svm_range_remove_notifier(prange);
3564 		svm_range_free(prange, false);
3565 	}
3566 
3567 	mmap_write_downgrade(mm);
3568 	/* Trigger migrations and revalidate and map to GPUs as needed. If
3569 	 * this fails we may be left with partially completed actions. There
3570 	 * is no clean way of rolling back to the previous state in such a
3571 	 * case because the rollback wouldn't be guaranteed to work either.
3572 	 */
3573 	list_for_each_entry(prange, &update_list, update_list) {
3574 		bool migrated;
3575 
3576 		mutex_lock(&prange->migrate_mutex);
3577 
3578 		r = svm_range_trigger_migration(mm, prange, &migrated);
3579 		if (r)
3580 			goto out_unlock_range;
3581 
3582 		if (migrated && (!p->xnack_enabled ||
3583 		    (prange->flags & KFD_IOCTL_SVM_FLAG_GPU_ALWAYS_MAPPED)) &&
3584 		    prange->mapped_to_gpu) {
3585 			pr_debug("restore_work will update mappings of GPUs\n");
3586 			mutex_unlock(&prange->migrate_mutex);
3587 			continue;
3588 		}
3589 
3590 		if (!migrated && !update_mapping) {
3591 			mutex_unlock(&prange->migrate_mutex);
3592 			continue;
3593 		}
3594 
3595 		flush_tlb = !migrated && update_mapping && prange->mapped_to_gpu;
3596 
3597 		r = svm_range_validate_and_map(mm, prange, MAX_GPU_INSTANCE,
3598 					       true, true, flush_tlb);
3599 		if (r)
3600 			pr_debug("failed %d to map svm range\n", r);
3601 
3602 out_unlock_range:
3603 		mutex_unlock(&prange->migrate_mutex);
3604 		if (r)
3605 			ret = r;
3606 	}
3607 
3608 	dynamic_svm_range_dump(svms);
3609 
3610 	mutex_unlock(&svms->lock);
3611 	mmap_read_unlock(mm);
3612 out:
3613 	mutex_unlock(&process_info->lock);
3614 
3615 	pr_debug("pasid 0x%x svms 0x%p [0x%llx 0x%llx] done, r=%d\n", p->pasid,
3616 		 &p->svms, start, start + size - 1, r);
3617 
3618 	return ret ? ret : r;
3619 }
3620 
3621 static int
3622 svm_range_get_attr(struct kfd_process *p, struct mm_struct *mm,
3623 		   uint64_t start, uint64_t size, uint32_t nattr,
3624 		   struct kfd_ioctl_svm_attribute *attrs)
3625 {
3626 	DECLARE_BITMAP(bitmap_access, MAX_GPU_INSTANCE);
3627 	DECLARE_BITMAP(bitmap_aip, MAX_GPU_INSTANCE);
3628 	bool get_preferred_loc = false;
3629 	bool get_prefetch_loc = false;
3630 	bool get_granularity = false;
3631 	bool get_accessible = false;
3632 	bool get_flags = false;
3633 	uint64_t last = start + size - 1UL;
3634 	uint8_t granularity = 0xff;
3635 	struct interval_tree_node *node;
3636 	struct svm_range_list *svms;
3637 	struct svm_range *prange;
3638 	uint32_t prefetch_loc = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3639 	uint32_t location = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3640 	uint32_t flags_and = 0xffffffff;
3641 	uint32_t flags_or = 0;
3642 	int gpuidx;
3643 	uint32_t i;
3644 	int r = 0;
3645 
3646 	pr_debug("svms 0x%p [0x%llx 0x%llx] nattr 0x%x\n", &p->svms, start,
3647 		 start + size - 1, nattr);
3648 
3649 	/* Flush pending deferred work to avoid racing with deferred actions from
3650 	 * previous memory map changes (e.g. munmap). Concurrent memory map changes
3651 	 * can still race with get_attr because we don't hold the mmap lock. But that
3652 	 * would be a race condition in the application anyway, and undefined
3653 	 * behaviour is acceptable in that case.
3654 	 */
3655 	flush_work(&p->svms.deferred_list_work);
3656 
3657 	mmap_read_lock(mm);
3658 	r = svm_range_is_valid(p, start, size);
3659 	mmap_read_unlock(mm);
3660 	if (r) {
3661 		pr_debug("invalid range r=%d\n", r);
3662 		return r;
3663 	}
3664 
3665 	for (i = 0; i < nattr; i++) {
3666 		switch (attrs[i].type) {
3667 		case KFD_IOCTL_SVM_ATTR_PREFERRED_LOC:
3668 			get_preferred_loc = true;
3669 			break;
3670 		case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
3671 			get_prefetch_loc = true;
3672 			break;
3673 		case KFD_IOCTL_SVM_ATTR_ACCESS:
3674 			get_accessible = true;
3675 			break;
3676 		case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
3677 		case KFD_IOCTL_SVM_ATTR_CLR_FLAGS:
3678 			get_flags = true;
3679 			break;
3680 		case KFD_IOCTL_SVM_ATTR_GRANULARITY:
3681 			get_granularity = true;
3682 			break;
3683 		case KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE:
3684 		case KFD_IOCTL_SVM_ATTR_NO_ACCESS:
3685 			fallthrough;
3686 		default:
3687 			pr_debug("get invalid attr type 0x%x\n", attrs[i].type);
3688 			return -EINVAL;
3689 		}
3690 	}
3691 
3692 	svms = &p->svms;
3693 
3694 	mutex_lock(&svms->lock);
3695 
3696 	node = interval_tree_iter_first(&svms->objects, start, last);
3697 	if (!node) {
3698 		pr_debug("range attrs not found return default values\n");
3699 		svm_range_set_default_attributes(&location, &prefetch_loc,
3700 						 &granularity, &flags_and);
3701 		flags_or = flags_and;
3702 		if (p->xnack_enabled)
3703 			bitmap_copy(bitmap_access, svms->bitmap_supported,
3704 				    MAX_GPU_INSTANCE);
3705 		else
3706 			bitmap_zero(bitmap_access, MAX_GPU_INSTANCE);
3707 		bitmap_zero(bitmap_aip, MAX_GPU_INSTANCE);
3708 		goto fill_values;
3709 	}
3710 	bitmap_copy(bitmap_access, svms->bitmap_supported, MAX_GPU_INSTANCE);
3711 	bitmap_copy(bitmap_aip, svms->bitmap_supported, MAX_GPU_INSTANCE);
3712 
3713 	while (node) {
3714 		struct interval_tree_node *next;
3715 
3716 		prange = container_of(node, struct svm_range, it_node);
3717 		next = interval_tree_iter_next(node, start, last);
3718 
3719 		if (get_preferred_loc) {
3720 			if (prange->preferred_loc ==
3721 					KFD_IOCTL_SVM_LOCATION_UNDEFINED ||
3722 			    (location != KFD_IOCTL_SVM_LOCATION_UNDEFINED &&
3723 			     location != prange->preferred_loc)) {
3724 				location = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3725 				get_preferred_loc = false;
3726 			} else {
3727 				location = prange->preferred_loc;
3728 			}
3729 		}
3730 		if (get_prefetch_loc) {
3731 			if (prange->prefetch_loc ==
3732 					KFD_IOCTL_SVM_LOCATION_UNDEFINED ||
3733 			    (prefetch_loc != KFD_IOCTL_SVM_LOCATION_UNDEFINED &&
3734 			     prefetch_loc != prange->prefetch_loc)) {
3735 				prefetch_loc = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3736 				get_prefetch_loc = false;
3737 			} else {
3738 				prefetch_loc = prange->prefetch_loc;
3739 			}
3740 		}
3741 		if (get_accessible) {
3742 			bitmap_and(bitmap_access, bitmap_access,
3743 				   prange->bitmap_access, MAX_GPU_INSTANCE);
3744 			bitmap_and(bitmap_aip, bitmap_aip,
3745 				   prange->bitmap_aip, MAX_GPU_INSTANCE);
3746 		}
3747 		if (get_flags) {
3748 			flags_and &= prange->flags;
3749 			flags_or |= prange->flags;
3750 		}
3751 
3752 		if (get_granularity && prange->granularity < granularity)
3753 			granularity = prange->granularity;
3754 
3755 		node = next;
3756 	}
3757 fill_values:
3758 	mutex_unlock(&svms->lock);
3759 
3760 	for (i = 0; i < nattr; i++) {
3761 		switch (attrs[i].type) {
3762 		case KFD_IOCTL_SVM_ATTR_PREFERRED_LOC:
3763 			attrs[i].value = location;
3764 			break;
3765 		case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
3766 			attrs[i].value = prefetch_loc;
3767 			break;
3768 		case KFD_IOCTL_SVM_ATTR_ACCESS:
3769 			gpuidx = kfd_process_gpuidx_from_gpuid(p,
3770 							       attrs[i].value);
3771 			if (gpuidx < 0) {
3772 				pr_debug("invalid gpuid %x\n", attrs[i].value);
3773 				return -EINVAL;
3774 			}
3775 			if (test_bit(gpuidx, bitmap_access))
3776 				attrs[i].type = KFD_IOCTL_SVM_ATTR_ACCESS;
3777 			else if (test_bit(gpuidx, bitmap_aip))
3778 				attrs[i].type =
3779 					KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE;
3780 			else
3781 				attrs[i].type = KFD_IOCTL_SVM_ATTR_NO_ACCESS;
3782 			break;
3783 		case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
3784 			attrs[i].value = flags_and;
3785 			break;
3786 		case KFD_IOCTL_SVM_ATTR_CLR_FLAGS:
3787 			attrs[i].value = ~flags_or;
3788 			break;
3789 		case KFD_IOCTL_SVM_ATTR_GRANULARITY:
3790 			attrs[i].value = (uint32_t)granularity;
3791 			break;
3792 		}
3793 	}
3794 
3795 	return 0;
3796 }
3797 
3798 int kfd_criu_resume_svm(struct kfd_process *p)
3799 {
3800 	struct kfd_ioctl_svm_attribute *set_attr_new, *set_attr = NULL;
3801 	int nattr_common = 4, nattr_accessibility = 1;
3802 	struct criu_svm_metadata *criu_svm_md = NULL;
3803 	struct svm_range_list *svms = &p->svms;
3804 	struct criu_svm_metadata *next = NULL;
3805 	uint32_t set_flags = 0xffffffff;
3806 	int i, j, num_attrs, ret = 0;
3807 	uint64_t set_attr_size;
3808 	struct mm_struct *mm;
3809 
3810 	if (list_empty(&svms->criu_svm_metadata_list)) {
3811 		pr_debug("No SVM data from CRIU restore stage 2\n");
3812 		return ret;
3813 	}
3814 
3815 	mm = get_task_mm(p->lead_thread);
3816 	if (!mm) {
3817 		pr_err("failed to get mm for the target process\n");
3818 		return -ESRCH;
3819 	}
3820 
3821 	num_attrs = nattr_common + (nattr_accessibility * p->n_pdds);
3822 
3823 	i = j = 0;
3824 	list_for_each_entry(criu_svm_md, &svms->criu_svm_metadata_list, list) {
3825 		pr_debug("criu_svm_md[%d]\n\tstart: 0x%llx size: 0x%llx (npages)\n",
3826 			 i, criu_svm_md->data.start_addr, criu_svm_md->data.size);
3827 
3828 		for (j = 0; j < num_attrs; j++) {
3829 			pr_debug("\ncriu_svm_md[%d]->attrs[%d].type : 0x%x\ncriu_svm_md[%d]->attrs[%d].value : 0x%x\n",
3830 				 i, j, criu_svm_md->data.attrs[j].type,
3831 				 i, j, criu_svm_md->data.attrs[j].value);
3832 			switch (criu_svm_md->data.attrs[j].type) {
3833 			/* During Checkpoint operation, the query for
3834 			 * KFD_IOCTL_SVM_ATTR_PREFETCH_LOC attribute might
3835 			 * return KFD_IOCTL_SVM_LOCATION_UNDEFINED if they were
3836 			 * not used by the range which was checkpointed. Care
3837 			 * must be taken to not restore with an invalid value
3838 			 * otherwise the gpuidx value will be invalid and
3839 			 * set_attr would eventually fail so just replace those
3840 			 * with another dummy attribute such as
3841 			 * KFD_IOCTL_SVM_ATTR_SET_FLAGS.
3842 			 */
3843 			case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
3844 				if (criu_svm_md->data.attrs[j].value ==
3845 				    KFD_IOCTL_SVM_LOCATION_UNDEFINED) {
3846 					criu_svm_md->data.attrs[j].type =
3847 						KFD_IOCTL_SVM_ATTR_SET_FLAGS;
3848 					criu_svm_md->data.attrs[j].value = 0;
3849 				}
3850 				break;
3851 			case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
3852 				set_flags = criu_svm_md->data.attrs[j].value;
3853 				break;
3854 			default:
3855 				break;
3856 			}
3857 		}
3858 
3859 		/* CLR_FLAGS is not available via get_attr during checkpoint but
3860 		 * it needs to be inserted before restoring the ranges so
3861 		 * allocate extra space for it before calling set_attr
3862 		 */
3863 		set_attr_size = sizeof(struct kfd_ioctl_svm_attribute) *
3864 						(num_attrs + 1);
3865 		set_attr_new = krealloc(set_attr, set_attr_size,
3866 					    GFP_KERNEL);
3867 		if (!set_attr_new) {
3868 			ret = -ENOMEM;
3869 			goto exit;
3870 		}
3871 		set_attr = set_attr_new;
3872 
3873 		memcpy(set_attr, criu_svm_md->data.attrs, num_attrs *
3874 					sizeof(struct kfd_ioctl_svm_attribute));
3875 		set_attr[num_attrs].type = KFD_IOCTL_SVM_ATTR_CLR_FLAGS;
3876 		set_attr[num_attrs].value = ~set_flags;
3877 
3878 		ret = svm_range_set_attr(p, mm, criu_svm_md->data.start_addr,
3879 					 criu_svm_md->data.size, num_attrs + 1,
3880 					 set_attr);
3881 		if (ret) {
3882 			pr_err("CRIU: failed to set range attributes\n");
3883 			goto exit;
3884 		}
3885 
3886 		i++;
3887 	}
3888 exit:
3889 	kfree(set_attr);
3890 	list_for_each_entry_safe(criu_svm_md, next, &svms->criu_svm_metadata_list, list) {
3891 		pr_debug("freeing criu_svm_md[]\n\tstart: 0x%llx\n",
3892 						criu_svm_md->data.start_addr);
3893 		kfree(criu_svm_md);
3894 	}
3895 
3896 	mmput(mm);
3897 	return ret;
3898 
3899 }
3900 
3901 int kfd_criu_restore_svm(struct kfd_process *p,
3902 			 uint8_t __user *user_priv_ptr,
3903 			 uint64_t *priv_data_offset,
3904 			 uint64_t max_priv_data_size)
3905 {
3906 	uint64_t svm_priv_data_size, svm_object_md_size, svm_attrs_size;
3907 	int nattr_common = 4, nattr_accessibility = 1;
3908 	struct criu_svm_metadata *criu_svm_md = NULL;
3909 	struct svm_range_list *svms = &p->svms;
3910 	uint32_t num_devices;
3911 	int ret = 0;
3912 
3913 	num_devices = p->n_pdds;
3914 	/* Handle one SVM range object at a time, also the number of gpus are
3915 	 * assumed to be same on the restore node, checking must be done while
3916 	 * evaluating the topology earlier
3917 	 */
3918 
3919 	svm_attrs_size = sizeof(struct kfd_ioctl_svm_attribute) *
3920 		(nattr_common + nattr_accessibility * num_devices);
3921 	svm_object_md_size = sizeof(struct criu_svm_metadata) + svm_attrs_size;
3922 
3923 	svm_priv_data_size = sizeof(struct kfd_criu_svm_range_priv_data) +
3924 								svm_attrs_size;
3925 
3926 	criu_svm_md = kzalloc(svm_object_md_size, GFP_KERNEL);
3927 	if (!criu_svm_md) {
3928 		pr_err("failed to allocate memory to store svm metadata\n");
3929 		return -ENOMEM;
3930 	}
3931 	if (*priv_data_offset + svm_priv_data_size > max_priv_data_size) {
3932 		ret = -EINVAL;
3933 		goto exit;
3934 	}
3935 
3936 	ret = copy_from_user(&criu_svm_md->data, user_priv_ptr + *priv_data_offset,
3937 			     svm_priv_data_size);
3938 	if (ret) {
3939 		ret = -EFAULT;
3940 		goto exit;
3941 	}
3942 	*priv_data_offset += svm_priv_data_size;
3943 
3944 	list_add_tail(&criu_svm_md->list, &svms->criu_svm_metadata_list);
3945 
3946 	return 0;
3947 
3948 
3949 exit:
3950 	kfree(criu_svm_md);
3951 	return ret;
3952 }
3953 
3954 int svm_range_get_info(struct kfd_process *p, uint32_t *num_svm_ranges,
3955 		       uint64_t *svm_priv_data_size)
3956 {
3957 	uint64_t total_size, accessibility_size, common_attr_size;
3958 	int nattr_common = 4, nattr_accessibility = 1;
3959 	int num_devices = p->n_pdds;
3960 	struct svm_range_list *svms;
3961 	struct svm_range *prange;
3962 	uint32_t count = 0;
3963 
3964 	*svm_priv_data_size = 0;
3965 
3966 	svms = &p->svms;
3967 	if (!svms)
3968 		return -EINVAL;
3969 
3970 	mutex_lock(&svms->lock);
3971 	list_for_each_entry(prange, &svms->list, list) {
3972 		pr_debug("prange: 0x%p start: 0x%lx\t npages: 0x%llx\t end: 0x%llx\n",
3973 			 prange, prange->start, prange->npages,
3974 			 prange->start + prange->npages - 1);
3975 		count++;
3976 	}
3977 	mutex_unlock(&svms->lock);
3978 
3979 	*num_svm_ranges = count;
3980 	/* Only the accessbility attributes need to be queried for all the gpus
3981 	 * individually, remaining ones are spanned across the entire process
3982 	 * regardless of the various gpu nodes. Of the remaining attributes,
3983 	 * KFD_IOCTL_SVM_ATTR_CLR_FLAGS need not be saved.
3984 	 *
3985 	 * KFD_IOCTL_SVM_ATTR_PREFERRED_LOC
3986 	 * KFD_IOCTL_SVM_ATTR_PREFETCH_LOC
3987 	 * KFD_IOCTL_SVM_ATTR_SET_FLAGS
3988 	 * KFD_IOCTL_SVM_ATTR_GRANULARITY
3989 	 *
3990 	 * ** ACCESSBILITY ATTRIBUTES **
3991 	 * (Considered as one, type is altered during query, value is gpuid)
3992 	 * KFD_IOCTL_SVM_ATTR_ACCESS
3993 	 * KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE
3994 	 * KFD_IOCTL_SVM_ATTR_NO_ACCESS
3995 	 */
3996 	if (*num_svm_ranges > 0) {
3997 		common_attr_size = sizeof(struct kfd_ioctl_svm_attribute) *
3998 			nattr_common;
3999 		accessibility_size = sizeof(struct kfd_ioctl_svm_attribute) *
4000 			nattr_accessibility * num_devices;
4001 
4002 		total_size = sizeof(struct kfd_criu_svm_range_priv_data) +
4003 			common_attr_size + accessibility_size;
4004 
4005 		*svm_priv_data_size = *num_svm_ranges * total_size;
4006 	}
4007 
4008 	pr_debug("num_svm_ranges %u total_priv_size %llu\n", *num_svm_ranges,
4009 		 *svm_priv_data_size);
4010 	return 0;
4011 }
4012 
4013 int kfd_criu_checkpoint_svm(struct kfd_process *p,
4014 			    uint8_t __user *user_priv_data,
4015 			    uint64_t *priv_data_offset)
4016 {
4017 	struct kfd_criu_svm_range_priv_data *svm_priv = NULL;
4018 	struct kfd_ioctl_svm_attribute *query_attr = NULL;
4019 	uint64_t svm_priv_data_size, query_attr_size = 0;
4020 	int index, nattr_common = 4, ret = 0;
4021 	struct svm_range_list *svms;
4022 	int num_devices = p->n_pdds;
4023 	struct svm_range *prange;
4024 	struct mm_struct *mm;
4025 
4026 	svms = &p->svms;
4027 	if (!svms)
4028 		return -EINVAL;
4029 
4030 	mm = get_task_mm(p->lead_thread);
4031 	if (!mm) {
4032 		pr_err("failed to get mm for the target process\n");
4033 		return -ESRCH;
4034 	}
4035 
4036 	query_attr_size = sizeof(struct kfd_ioctl_svm_attribute) *
4037 				(nattr_common + num_devices);
4038 
4039 	query_attr = kzalloc(query_attr_size, GFP_KERNEL);
4040 	if (!query_attr) {
4041 		ret = -ENOMEM;
4042 		goto exit;
4043 	}
4044 
4045 	query_attr[0].type = KFD_IOCTL_SVM_ATTR_PREFERRED_LOC;
4046 	query_attr[1].type = KFD_IOCTL_SVM_ATTR_PREFETCH_LOC;
4047 	query_attr[2].type = KFD_IOCTL_SVM_ATTR_SET_FLAGS;
4048 	query_attr[3].type = KFD_IOCTL_SVM_ATTR_GRANULARITY;
4049 
4050 	for (index = 0; index < num_devices; index++) {
4051 		struct kfd_process_device *pdd = p->pdds[index];
4052 
4053 		query_attr[index + nattr_common].type =
4054 			KFD_IOCTL_SVM_ATTR_ACCESS;
4055 		query_attr[index + nattr_common].value = pdd->user_gpu_id;
4056 	}
4057 
4058 	svm_priv_data_size = sizeof(*svm_priv) + query_attr_size;
4059 
4060 	svm_priv = kzalloc(svm_priv_data_size, GFP_KERNEL);
4061 	if (!svm_priv) {
4062 		ret = -ENOMEM;
4063 		goto exit_query;
4064 	}
4065 
4066 	index = 0;
4067 	list_for_each_entry(prange, &svms->list, list) {
4068 
4069 		svm_priv->object_type = KFD_CRIU_OBJECT_TYPE_SVM_RANGE;
4070 		svm_priv->start_addr = prange->start;
4071 		svm_priv->size = prange->npages;
4072 		memcpy(&svm_priv->attrs, query_attr, query_attr_size);
4073 		pr_debug("CRIU: prange: 0x%p start: 0x%lx\t npages: 0x%llx end: 0x%llx\t size: 0x%llx\n",
4074 			 prange, prange->start, prange->npages,
4075 			 prange->start + prange->npages - 1,
4076 			 prange->npages * PAGE_SIZE);
4077 
4078 		ret = svm_range_get_attr(p, mm, svm_priv->start_addr,
4079 					 svm_priv->size,
4080 					 (nattr_common + num_devices),
4081 					 svm_priv->attrs);
4082 		if (ret) {
4083 			pr_err("CRIU: failed to obtain range attributes\n");
4084 			goto exit_priv;
4085 		}
4086 
4087 		if (copy_to_user(user_priv_data + *priv_data_offset, svm_priv,
4088 				 svm_priv_data_size)) {
4089 			pr_err("Failed to copy svm priv to user\n");
4090 			ret = -EFAULT;
4091 			goto exit_priv;
4092 		}
4093 
4094 		*priv_data_offset += svm_priv_data_size;
4095 
4096 	}
4097 
4098 
4099 exit_priv:
4100 	kfree(svm_priv);
4101 exit_query:
4102 	kfree(query_attr);
4103 exit:
4104 	mmput(mm);
4105 	return ret;
4106 }
4107 
4108 int
4109 svm_ioctl(struct kfd_process *p, enum kfd_ioctl_svm_op op, uint64_t start,
4110 	  uint64_t size, uint32_t nattrs, struct kfd_ioctl_svm_attribute *attrs)
4111 {
4112 	struct mm_struct *mm = current->mm;
4113 	int r;
4114 
4115 	start >>= PAGE_SHIFT;
4116 	size >>= PAGE_SHIFT;
4117 
4118 	switch (op) {
4119 	case KFD_IOCTL_SVM_OP_SET_ATTR:
4120 		r = svm_range_set_attr(p, mm, start, size, nattrs, attrs);
4121 		break;
4122 	case KFD_IOCTL_SVM_OP_GET_ATTR:
4123 		r = svm_range_get_attr(p, mm, start, size, nattrs, attrs);
4124 		break;
4125 	default:
4126 		r = EINVAL;
4127 		break;
4128 	}
4129 
4130 	return r;
4131 }
4132