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