xref: /openbmc/linux/drivers/gpu/drm/amd/amdkfd/kfd_svm.c (revision 3a9a6f3d)
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 svm_range_list *svms;
1633 	struct svm_range *prange;
1634 	struct kfd_process *p;
1635 	struct mm_struct *mm;
1636 	int evicted_ranges;
1637 	int invalid;
1638 	int r;
1639 
1640 	svms = container_of(dwork, struct svm_range_list, restore_work);
1641 	evicted_ranges = atomic_read(&svms->evicted_ranges);
1642 	if (!evicted_ranges)
1643 		return;
1644 
1645 	pr_debug("restore svm ranges\n");
1646 
1647 	p = container_of(svms, struct kfd_process, svms);
1648 
1649 	/* Keep mm reference when svm_range_validate_and_map ranges */
1650 	mm = get_task_mm(p->lead_thread);
1651 	if (!mm) {
1652 		pr_debug("svms 0x%p process mm gone\n", svms);
1653 		return;
1654 	}
1655 
1656 	svm_range_list_lock_and_flush_work(svms, mm);
1657 	mutex_lock(&svms->lock);
1658 
1659 	evicted_ranges = atomic_read(&svms->evicted_ranges);
1660 
1661 	list_for_each_entry(prange, &svms->list, list) {
1662 		invalid = atomic_read(&prange->invalid);
1663 		if (!invalid)
1664 			continue;
1665 
1666 		pr_debug("restoring svms 0x%p prange 0x%p [0x%lx %lx] inv %d\n",
1667 			 prange->svms, prange, prange->start, prange->last,
1668 			 invalid);
1669 
1670 		/*
1671 		 * If range is migrating, wait for migration is done.
1672 		 */
1673 		mutex_lock(&prange->migrate_mutex);
1674 
1675 		r = svm_range_validate_and_map(mm, prange, MAX_GPU_INSTANCE,
1676 					       false, true);
1677 		if (r)
1678 			pr_debug("failed %d to map 0x%lx to gpus\n", r,
1679 				 prange->start);
1680 
1681 		mutex_unlock(&prange->migrate_mutex);
1682 		if (r)
1683 			goto out_reschedule;
1684 
1685 		if (atomic_cmpxchg(&prange->invalid, invalid, 0) != invalid)
1686 			goto out_reschedule;
1687 	}
1688 
1689 	if (atomic_cmpxchg(&svms->evicted_ranges, evicted_ranges, 0) !=
1690 	    evicted_ranges)
1691 		goto out_reschedule;
1692 
1693 	evicted_ranges = 0;
1694 
1695 	r = kgd2kfd_resume_mm(mm);
1696 	if (r) {
1697 		/* No recovery from this failure. Probably the CP is
1698 		 * hanging. No point trying again.
1699 		 */
1700 		pr_debug("failed %d to resume KFD\n", r);
1701 	}
1702 
1703 	pr_debug("restore svm ranges successfully\n");
1704 
1705 out_reschedule:
1706 	mutex_unlock(&svms->lock);
1707 	mmap_write_unlock(mm);
1708 	mmput(mm);
1709 
1710 	/* If validation failed, reschedule another attempt */
1711 	if (evicted_ranges) {
1712 		pr_debug("reschedule to restore svm range\n");
1713 		schedule_delayed_work(&svms->restore_work,
1714 			msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
1715 	}
1716 }
1717 
1718 /**
1719  * svm_range_evict - evict svm range
1720  * @prange: svm range structure
1721  * @mm: current process mm_struct
1722  * @start: starting process queue number
1723  * @last: last process queue number
1724  *
1725  * Stop all queues of the process to ensure GPU doesn't access the memory, then
1726  * return to let CPU evict the buffer and proceed CPU pagetable update.
1727  *
1728  * Don't need use lock to sync cpu pagetable invalidation with GPU execution.
1729  * If invalidation happens while restore work is running, restore work will
1730  * restart to ensure to get the latest CPU pages mapping to GPU, then start
1731  * the queues.
1732  */
1733 static int
1734 svm_range_evict(struct svm_range *prange, struct mm_struct *mm,
1735 		unsigned long start, unsigned long last)
1736 {
1737 	struct svm_range_list *svms = prange->svms;
1738 	struct svm_range *pchild;
1739 	struct kfd_process *p;
1740 	int r = 0;
1741 
1742 	p = container_of(svms, struct kfd_process, svms);
1743 
1744 	pr_debug("invalidate svms 0x%p prange [0x%lx 0x%lx] [0x%lx 0x%lx]\n",
1745 		 svms, prange->start, prange->last, start, last);
1746 
1747 	if (!p->xnack_enabled) {
1748 		int evicted_ranges;
1749 
1750 		list_for_each_entry(pchild, &prange->child_list, child_list) {
1751 			mutex_lock_nested(&pchild->lock, 1);
1752 			if (pchild->start <= last && pchild->last >= start) {
1753 				pr_debug("increment pchild invalid [0x%lx 0x%lx]\n",
1754 					 pchild->start, pchild->last);
1755 				atomic_inc(&pchild->invalid);
1756 			}
1757 			mutex_unlock(&pchild->lock);
1758 		}
1759 
1760 		if (prange->start <= last && prange->last >= start)
1761 			atomic_inc(&prange->invalid);
1762 
1763 		evicted_ranges = atomic_inc_return(&svms->evicted_ranges);
1764 		if (evicted_ranges != 1)
1765 			return r;
1766 
1767 		pr_debug("evicting svms 0x%p range [0x%lx 0x%lx]\n",
1768 			 prange->svms, prange->start, prange->last);
1769 
1770 		/* First eviction, stop the queues */
1771 		r = kgd2kfd_quiesce_mm(mm);
1772 		if (r)
1773 			pr_debug("failed to quiesce KFD\n");
1774 
1775 		pr_debug("schedule to restore svm %p ranges\n", svms);
1776 		schedule_delayed_work(&svms->restore_work,
1777 			msecs_to_jiffies(AMDGPU_SVM_RANGE_RESTORE_DELAY_MS));
1778 	} else {
1779 		unsigned long s, l;
1780 
1781 		pr_debug("invalidate unmap svms 0x%p [0x%lx 0x%lx] from GPUs\n",
1782 			 prange->svms, start, last);
1783 		list_for_each_entry(pchild, &prange->child_list, child_list) {
1784 			mutex_lock_nested(&pchild->lock, 1);
1785 			s = max(start, pchild->start);
1786 			l = min(last, pchild->last);
1787 			if (l >= s)
1788 				svm_range_unmap_from_gpus(pchild, s, l);
1789 			mutex_unlock(&pchild->lock);
1790 		}
1791 		s = max(start, prange->start);
1792 		l = min(last, prange->last);
1793 		if (l >= s)
1794 			svm_range_unmap_from_gpus(prange, s, l);
1795 	}
1796 
1797 	return r;
1798 }
1799 
1800 static struct svm_range *svm_range_clone(struct svm_range *old)
1801 {
1802 	struct svm_range *new;
1803 
1804 	new = svm_range_new(old->svms, old->start, old->last);
1805 	if (!new)
1806 		return NULL;
1807 
1808 	if (old->svm_bo) {
1809 		new->ttm_res = old->ttm_res;
1810 		new->offset = old->offset;
1811 		new->svm_bo = svm_range_bo_ref(old->svm_bo);
1812 		spin_lock(&new->svm_bo->list_lock);
1813 		list_add(&new->svm_bo_list, &new->svm_bo->range_list);
1814 		spin_unlock(&new->svm_bo->list_lock);
1815 	}
1816 	new->flags = old->flags;
1817 	new->preferred_loc = old->preferred_loc;
1818 	new->prefetch_loc = old->prefetch_loc;
1819 	new->actual_loc = old->actual_loc;
1820 	new->granularity = old->granularity;
1821 	bitmap_copy(new->bitmap_access, old->bitmap_access, MAX_GPU_INSTANCE);
1822 	bitmap_copy(new->bitmap_aip, old->bitmap_aip, MAX_GPU_INSTANCE);
1823 
1824 	return new;
1825 }
1826 
1827 /**
1828  * svm_range_add - add svm range and handle overlap
1829  * @p: the range add to this process svms
1830  * @start: page size aligned
1831  * @size: page size aligned
1832  * @nattr: number of attributes
1833  * @attrs: array of attributes
1834  * @update_list: output, the ranges need validate and update GPU mapping
1835  * @insert_list: output, the ranges need insert to svms
1836  * @remove_list: output, the ranges are replaced and need remove from svms
1837  *
1838  * Check if the virtual address range has overlap with any existing ranges,
1839  * split partly overlapping ranges and add new ranges in the gaps. All changes
1840  * should be applied to the range_list and interval tree transactionally. If
1841  * any range split or allocation fails, the entire update fails. Therefore any
1842  * existing overlapping svm_ranges are cloned and the original svm_ranges left
1843  * unchanged.
1844  *
1845  * If the transaction succeeds, the caller can update and insert clones and
1846  * new ranges, then free the originals.
1847  *
1848  * Otherwise the caller can free the clones and new ranges, while the old
1849  * svm_ranges remain unchanged.
1850  *
1851  * Context: Process context, caller must hold svms->lock
1852  *
1853  * Return:
1854  * 0 - OK, otherwise error code
1855  */
1856 static int
1857 svm_range_add(struct kfd_process *p, uint64_t start, uint64_t size,
1858 	      uint32_t nattr, struct kfd_ioctl_svm_attribute *attrs,
1859 	      struct list_head *update_list, struct list_head *insert_list,
1860 	      struct list_head *remove_list)
1861 {
1862 	unsigned long last = start + size - 1UL;
1863 	struct svm_range_list *svms = &p->svms;
1864 	struct interval_tree_node *node;
1865 	struct svm_range *prange;
1866 	struct svm_range *tmp;
1867 	int r = 0;
1868 
1869 	pr_debug("svms 0x%p [0x%llx 0x%lx]\n", &p->svms, start, last);
1870 
1871 	INIT_LIST_HEAD(update_list);
1872 	INIT_LIST_HEAD(insert_list);
1873 	INIT_LIST_HEAD(remove_list);
1874 
1875 	node = interval_tree_iter_first(&svms->objects, start, last);
1876 	while (node) {
1877 		struct interval_tree_node *next;
1878 		unsigned long next_start;
1879 
1880 		pr_debug("found overlap node [0x%lx 0x%lx]\n", node->start,
1881 			 node->last);
1882 
1883 		prange = container_of(node, struct svm_range, it_node);
1884 		next = interval_tree_iter_next(node, start, last);
1885 		next_start = min(node->last, last) + 1;
1886 
1887 		if (svm_range_is_same_attrs(p, prange, nattr, attrs)) {
1888 			/* nothing to do */
1889 		} else if (node->start < start || node->last > last) {
1890 			/* node intersects the update range and its attributes
1891 			 * will change. Clone and split it, apply updates only
1892 			 * to the overlapping part
1893 			 */
1894 			struct svm_range *old = prange;
1895 
1896 			prange = svm_range_clone(old);
1897 			if (!prange) {
1898 				r = -ENOMEM;
1899 				goto out;
1900 			}
1901 
1902 			list_add(&old->update_list, remove_list);
1903 			list_add(&prange->list, insert_list);
1904 			list_add(&prange->update_list, update_list);
1905 
1906 			if (node->start < start) {
1907 				pr_debug("change old range start\n");
1908 				r = svm_range_split_head(prange, start,
1909 							 insert_list);
1910 				if (r)
1911 					goto out;
1912 			}
1913 			if (node->last > last) {
1914 				pr_debug("change old range last\n");
1915 				r = svm_range_split_tail(prange, last,
1916 							 insert_list);
1917 				if (r)
1918 					goto out;
1919 			}
1920 		} else {
1921 			/* The node is contained within start..last,
1922 			 * just update it
1923 			 */
1924 			list_add(&prange->update_list, update_list);
1925 		}
1926 
1927 		/* insert a new node if needed */
1928 		if (node->start > start) {
1929 			prange = svm_range_new(svms, start, node->start - 1);
1930 			if (!prange) {
1931 				r = -ENOMEM;
1932 				goto out;
1933 			}
1934 
1935 			list_add(&prange->list, insert_list);
1936 			list_add(&prange->update_list, update_list);
1937 		}
1938 
1939 		node = next;
1940 		start = next_start;
1941 	}
1942 
1943 	/* add a final range at the end if needed */
1944 	if (start <= last) {
1945 		prange = svm_range_new(svms, start, last);
1946 		if (!prange) {
1947 			r = -ENOMEM;
1948 			goto out;
1949 		}
1950 		list_add(&prange->list, insert_list);
1951 		list_add(&prange->update_list, update_list);
1952 	}
1953 
1954 out:
1955 	if (r)
1956 		list_for_each_entry_safe(prange, tmp, insert_list, list)
1957 			svm_range_free(prange);
1958 
1959 	return r;
1960 }
1961 
1962 static void
1963 svm_range_update_notifier_and_interval_tree(struct mm_struct *mm,
1964 					    struct svm_range *prange)
1965 {
1966 	unsigned long start;
1967 	unsigned long last;
1968 
1969 	start = prange->notifier.interval_tree.start >> PAGE_SHIFT;
1970 	last = prange->notifier.interval_tree.last >> PAGE_SHIFT;
1971 
1972 	if (prange->start == start && prange->last == last)
1973 		return;
1974 
1975 	pr_debug("up notifier 0x%p prange 0x%p [0x%lx 0x%lx] [0x%lx 0x%lx]\n",
1976 		  prange->svms, prange, start, last, prange->start,
1977 		  prange->last);
1978 
1979 	if (start != 0 && last != 0) {
1980 		interval_tree_remove(&prange->it_node, &prange->svms->objects);
1981 		svm_range_remove_notifier(prange);
1982 	}
1983 	prange->it_node.start = prange->start;
1984 	prange->it_node.last = prange->last;
1985 
1986 	interval_tree_insert(&prange->it_node, &prange->svms->objects);
1987 	svm_range_add_notifier_locked(mm, prange);
1988 }
1989 
1990 static void
1991 svm_range_handle_list_op(struct svm_range_list *svms, struct svm_range *prange,
1992 			 struct mm_struct *mm)
1993 {
1994 	switch (prange->work_item.op) {
1995 	case SVM_OP_NULL:
1996 		pr_debug("NULL OP 0x%p prange 0x%p [0x%lx 0x%lx]\n",
1997 			 svms, prange, prange->start, prange->last);
1998 		break;
1999 	case SVM_OP_UNMAP_RANGE:
2000 		pr_debug("remove 0x%p prange 0x%p [0x%lx 0x%lx]\n",
2001 			 svms, prange, prange->start, prange->last);
2002 		svm_range_unlink(prange);
2003 		svm_range_remove_notifier(prange);
2004 		svm_range_free(prange);
2005 		break;
2006 	case SVM_OP_UPDATE_RANGE_NOTIFIER:
2007 		pr_debug("update notifier 0x%p prange 0x%p [0x%lx 0x%lx]\n",
2008 			 svms, prange, prange->start, prange->last);
2009 		svm_range_update_notifier_and_interval_tree(mm, prange);
2010 		break;
2011 	case SVM_OP_UPDATE_RANGE_NOTIFIER_AND_MAP:
2012 		pr_debug("update and map 0x%p prange 0x%p [0x%lx 0x%lx]\n",
2013 			 svms, prange, prange->start, prange->last);
2014 		svm_range_update_notifier_and_interval_tree(mm, prange);
2015 		/* TODO: implement deferred validation and mapping */
2016 		break;
2017 	case SVM_OP_ADD_RANGE:
2018 		pr_debug("add 0x%p prange 0x%p [0x%lx 0x%lx]\n", svms, prange,
2019 			 prange->start, prange->last);
2020 		svm_range_add_to_svms(prange);
2021 		svm_range_add_notifier_locked(mm, prange);
2022 		break;
2023 	case SVM_OP_ADD_RANGE_AND_MAP:
2024 		pr_debug("add and map 0x%p prange 0x%p [0x%lx 0x%lx]\n", svms,
2025 			 prange, prange->start, prange->last);
2026 		svm_range_add_to_svms(prange);
2027 		svm_range_add_notifier_locked(mm, prange);
2028 		/* TODO: implement deferred validation and mapping */
2029 		break;
2030 	default:
2031 		WARN_ONCE(1, "Unknown prange 0x%p work op %d\n", prange,
2032 			 prange->work_item.op);
2033 	}
2034 }
2035 
2036 static void svm_range_drain_retry_fault(struct svm_range_list *svms)
2037 {
2038 	struct kfd_process_device *pdd;
2039 	struct kfd_process *p;
2040 	int drain;
2041 	uint32_t i;
2042 
2043 	p = container_of(svms, struct kfd_process, svms);
2044 
2045 restart:
2046 	drain = atomic_read(&svms->drain_pagefaults);
2047 	if (!drain)
2048 		return;
2049 
2050 	for_each_set_bit(i, svms->bitmap_supported, p->n_pdds) {
2051 		pdd = p->pdds[i];
2052 		if (!pdd)
2053 			continue;
2054 
2055 		pr_debug("drain retry fault gpu %d svms %p\n", i, svms);
2056 
2057 		amdgpu_ih_wait_on_checkpoint_process_ts(pdd->dev->adev,
2058 						     &pdd->dev->adev->irq.ih1);
2059 		pr_debug("drain retry fault gpu %d svms 0x%p done\n", i, svms);
2060 	}
2061 	if (atomic_cmpxchg(&svms->drain_pagefaults, drain, 0) != drain)
2062 		goto restart;
2063 }
2064 
2065 static void svm_range_deferred_list_work(struct work_struct *work)
2066 {
2067 	struct svm_range_list *svms;
2068 	struct svm_range *prange;
2069 	struct mm_struct *mm;
2070 
2071 	svms = container_of(work, struct svm_range_list, deferred_list_work);
2072 	pr_debug("enter svms 0x%p\n", svms);
2073 
2074 	spin_lock(&svms->deferred_list_lock);
2075 	while (!list_empty(&svms->deferred_range_list)) {
2076 		prange = list_first_entry(&svms->deferred_range_list,
2077 					  struct svm_range, deferred_list);
2078 		spin_unlock(&svms->deferred_list_lock);
2079 
2080 		pr_debug("prange 0x%p [0x%lx 0x%lx] op %d\n", prange,
2081 			 prange->start, prange->last, prange->work_item.op);
2082 
2083 		mm = prange->work_item.mm;
2084 retry:
2085 		mmap_write_lock(mm);
2086 
2087 		/* Checking for the need to drain retry faults must be inside
2088 		 * mmap write lock to serialize with munmap notifiers.
2089 		 */
2090 		if (unlikely(atomic_read(&svms->drain_pagefaults))) {
2091 			mmap_write_unlock(mm);
2092 			svm_range_drain_retry_fault(svms);
2093 			goto retry;
2094 		}
2095 
2096 		/* Remove from deferred_list must be inside mmap write lock, for
2097 		 * two race cases:
2098 		 * 1. unmap_from_cpu may change work_item.op and add the range
2099 		 *    to deferred_list again, cause use after free bug.
2100 		 * 2. svm_range_list_lock_and_flush_work may hold mmap write
2101 		 *    lock and continue because deferred_list is empty, but
2102 		 *    deferred_list work is actually waiting for mmap lock.
2103 		 */
2104 		spin_lock(&svms->deferred_list_lock);
2105 		list_del_init(&prange->deferred_list);
2106 		spin_unlock(&svms->deferred_list_lock);
2107 
2108 		mutex_lock(&svms->lock);
2109 		mutex_lock(&prange->migrate_mutex);
2110 		while (!list_empty(&prange->child_list)) {
2111 			struct svm_range *pchild;
2112 
2113 			pchild = list_first_entry(&prange->child_list,
2114 						struct svm_range, child_list);
2115 			pr_debug("child prange 0x%p op %d\n", pchild,
2116 				 pchild->work_item.op);
2117 			list_del_init(&pchild->child_list);
2118 			svm_range_handle_list_op(svms, pchild, mm);
2119 		}
2120 		mutex_unlock(&prange->migrate_mutex);
2121 
2122 		svm_range_handle_list_op(svms, prange, mm);
2123 		mutex_unlock(&svms->lock);
2124 		mmap_write_unlock(mm);
2125 
2126 		/* Pairs with mmget in svm_range_add_list_work */
2127 		mmput(mm);
2128 
2129 		spin_lock(&svms->deferred_list_lock);
2130 	}
2131 	spin_unlock(&svms->deferred_list_lock);
2132 	pr_debug("exit svms 0x%p\n", svms);
2133 }
2134 
2135 void
2136 svm_range_add_list_work(struct svm_range_list *svms, struct svm_range *prange,
2137 			struct mm_struct *mm, enum svm_work_list_ops op)
2138 {
2139 	spin_lock(&svms->deferred_list_lock);
2140 	/* if prange is on the deferred list */
2141 	if (!list_empty(&prange->deferred_list)) {
2142 		pr_debug("update exist prange 0x%p work op %d\n", prange, op);
2143 		WARN_ONCE(prange->work_item.mm != mm, "unmatch mm\n");
2144 		if (op != SVM_OP_NULL &&
2145 		    prange->work_item.op != SVM_OP_UNMAP_RANGE)
2146 			prange->work_item.op = op;
2147 	} else {
2148 		prange->work_item.op = op;
2149 
2150 		/* Pairs with mmput in deferred_list_work */
2151 		mmget(mm);
2152 		prange->work_item.mm = mm;
2153 		list_add_tail(&prange->deferred_list,
2154 			      &prange->svms->deferred_range_list);
2155 		pr_debug("add prange 0x%p [0x%lx 0x%lx] to work list op %d\n",
2156 			 prange, prange->start, prange->last, op);
2157 	}
2158 	spin_unlock(&svms->deferred_list_lock);
2159 }
2160 
2161 void schedule_deferred_list_work(struct svm_range_list *svms)
2162 {
2163 	spin_lock(&svms->deferred_list_lock);
2164 	if (!list_empty(&svms->deferred_range_list))
2165 		schedule_work(&svms->deferred_list_work);
2166 	spin_unlock(&svms->deferred_list_lock);
2167 }
2168 
2169 static void
2170 svm_range_unmap_split(struct mm_struct *mm, struct svm_range *parent,
2171 		      struct svm_range *prange, unsigned long start,
2172 		      unsigned long last)
2173 {
2174 	struct svm_range *head;
2175 	struct svm_range *tail;
2176 
2177 	if (prange->work_item.op == SVM_OP_UNMAP_RANGE) {
2178 		pr_debug("prange 0x%p [0x%lx 0x%lx] is already freed\n", prange,
2179 			 prange->start, prange->last);
2180 		return;
2181 	}
2182 	if (start > prange->last || last < prange->start)
2183 		return;
2184 
2185 	head = tail = prange;
2186 	if (start > prange->start)
2187 		svm_range_split(prange, prange->start, start - 1, &tail);
2188 	if (last < tail->last)
2189 		svm_range_split(tail, last + 1, tail->last, &head);
2190 
2191 	if (head != prange && tail != prange) {
2192 		svm_range_add_child(parent, mm, head, SVM_OP_UNMAP_RANGE);
2193 		svm_range_add_child(parent, mm, tail, SVM_OP_ADD_RANGE);
2194 	} else if (tail != prange) {
2195 		svm_range_add_child(parent, mm, tail, SVM_OP_UNMAP_RANGE);
2196 	} else if (head != prange) {
2197 		svm_range_add_child(parent, mm, head, SVM_OP_UNMAP_RANGE);
2198 	} else if (parent != prange) {
2199 		prange->work_item.op = SVM_OP_UNMAP_RANGE;
2200 	}
2201 }
2202 
2203 static void
2204 svm_range_unmap_from_cpu(struct mm_struct *mm, struct svm_range *prange,
2205 			 unsigned long start, unsigned long last)
2206 {
2207 	struct svm_range_list *svms;
2208 	struct svm_range *pchild;
2209 	struct kfd_process *p;
2210 	unsigned long s, l;
2211 	bool unmap_parent;
2212 
2213 	p = kfd_lookup_process_by_mm(mm);
2214 	if (!p)
2215 		return;
2216 	svms = &p->svms;
2217 
2218 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] [0x%lx 0x%lx]\n", svms,
2219 		 prange, prange->start, prange->last, start, last);
2220 
2221 	/* Make sure pending page faults are drained in the deferred worker
2222 	 * before the range is freed to avoid straggler interrupts on
2223 	 * unmapped memory causing "phantom faults".
2224 	 */
2225 	atomic_inc(&svms->drain_pagefaults);
2226 
2227 	unmap_parent = start <= prange->start && last >= prange->last;
2228 
2229 	list_for_each_entry(pchild, &prange->child_list, child_list) {
2230 		mutex_lock_nested(&pchild->lock, 1);
2231 		s = max(start, pchild->start);
2232 		l = min(last, pchild->last);
2233 		if (l >= s)
2234 			svm_range_unmap_from_gpus(pchild, s, l);
2235 		svm_range_unmap_split(mm, prange, pchild, start, last);
2236 		mutex_unlock(&pchild->lock);
2237 	}
2238 	s = max(start, prange->start);
2239 	l = min(last, prange->last);
2240 	if (l >= s)
2241 		svm_range_unmap_from_gpus(prange, s, l);
2242 	svm_range_unmap_split(mm, prange, prange, start, last);
2243 
2244 	if (unmap_parent)
2245 		svm_range_add_list_work(svms, prange, mm, SVM_OP_UNMAP_RANGE);
2246 	else
2247 		svm_range_add_list_work(svms, prange, mm,
2248 					SVM_OP_UPDATE_RANGE_NOTIFIER);
2249 	schedule_deferred_list_work(svms);
2250 
2251 	kfd_unref_process(p);
2252 }
2253 
2254 /**
2255  * svm_range_cpu_invalidate_pagetables - interval notifier callback
2256  * @mni: mmu_interval_notifier struct
2257  * @range: mmu_notifier_range struct
2258  * @cur_seq: value to pass to mmu_interval_set_seq()
2259  *
2260  * If event is MMU_NOTIFY_UNMAP, this is from CPU unmap range, otherwise, it
2261  * is from migration, or CPU page invalidation callback.
2262  *
2263  * For unmap event, unmap range from GPUs, remove prange from svms in a delayed
2264  * work thread, and split prange if only part of prange is unmapped.
2265  *
2266  * For invalidation event, if GPU retry fault is not enabled, evict the queues,
2267  * then schedule svm_range_restore_work to update GPU mapping and resume queues.
2268  * If GPU retry fault is enabled, unmap the svm range from GPU, retry fault will
2269  * update GPU mapping to recover.
2270  *
2271  * Context: mmap lock, notifier_invalidate_start lock are held
2272  *          for invalidate event, prange lock is held if this is from migration
2273  */
2274 static bool
2275 svm_range_cpu_invalidate_pagetables(struct mmu_interval_notifier *mni,
2276 				    const struct mmu_notifier_range *range,
2277 				    unsigned long cur_seq)
2278 {
2279 	struct svm_range *prange;
2280 	unsigned long start;
2281 	unsigned long last;
2282 
2283 	if (range->event == MMU_NOTIFY_RELEASE)
2284 		return true;
2285 
2286 	start = mni->interval_tree.start;
2287 	last = mni->interval_tree.last;
2288 	start = max(start, range->start) >> PAGE_SHIFT;
2289 	last = min(last, range->end - 1) >> PAGE_SHIFT;
2290 	pr_debug("[0x%lx 0x%lx] range[0x%lx 0x%lx] notifier[0x%lx 0x%lx] %d\n",
2291 		 start, last, range->start >> PAGE_SHIFT,
2292 		 (range->end - 1) >> PAGE_SHIFT,
2293 		 mni->interval_tree.start >> PAGE_SHIFT,
2294 		 mni->interval_tree.last >> PAGE_SHIFT, range->event);
2295 
2296 	prange = container_of(mni, struct svm_range, notifier);
2297 
2298 	svm_range_lock(prange);
2299 	mmu_interval_set_seq(mni, cur_seq);
2300 
2301 	switch (range->event) {
2302 	case MMU_NOTIFY_UNMAP:
2303 		svm_range_unmap_from_cpu(mni->mm, prange, start, last);
2304 		break;
2305 	default:
2306 		svm_range_evict(prange, mni->mm, start, last);
2307 		break;
2308 	}
2309 
2310 	svm_range_unlock(prange);
2311 
2312 	return true;
2313 }
2314 
2315 /**
2316  * svm_range_from_addr - find svm range from fault address
2317  * @svms: svm range list header
2318  * @addr: address to search range interval tree, in pages
2319  * @parent: parent range if range is on child list
2320  *
2321  * Context: The caller must hold svms->lock
2322  *
2323  * Return: the svm_range found or NULL
2324  */
2325 struct svm_range *
2326 svm_range_from_addr(struct svm_range_list *svms, unsigned long addr,
2327 		    struct svm_range **parent)
2328 {
2329 	struct interval_tree_node *node;
2330 	struct svm_range *prange;
2331 	struct svm_range *pchild;
2332 
2333 	node = interval_tree_iter_first(&svms->objects, addr, addr);
2334 	if (!node)
2335 		return NULL;
2336 
2337 	prange = container_of(node, struct svm_range, it_node);
2338 	pr_debug("address 0x%lx prange [0x%lx 0x%lx] node [0x%lx 0x%lx]\n",
2339 		 addr, prange->start, prange->last, node->start, node->last);
2340 
2341 	if (addr >= prange->start && addr <= prange->last) {
2342 		if (parent)
2343 			*parent = prange;
2344 		return prange;
2345 	}
2346 	list_for_each_entry(pchild, &prange->child_list, child_list)
2347 		if (addr >= pchild->start && addr <= pchild->last) {
2348 			pr_debug("found address 0x%lx pchild [0x%lx 0x%lx]\n",
2349 				 addr, pchild->start, pchild->last);
2350 			if (parent)
2351 				*parent = prange;
2352 			return pchild;
2353 		}
2354 
2355 	return NULL;
2356 }
2357 
2358 /* svm_range_best_restore_location - decide the best fault restore location
2359  * @prange: svm range structure
2360  * @adev: the GPU on which vm fault happened
2361  *
2362  * This is only called when xnack is on, to decide the best location to restore
2363  * the range mapping after GPU vm fault. Caller uses the best location to do
2364  * migration if actual loc is not best location, then update GPU page table
2365  * mapping to the best location.
2366  *
2367  * If the preferred loc is accessible by faulting GPU, use preferred loc.
2368  * If vm fault gpu idx is on range ACCESSIBLE bitmap, best_loc is vm fault gpu
2369  * If vm fault gpu idx is on range ACCESSIBLE_IN_PLACE bitmap, then
2370  *    if range actual loc is cpu, best_loc is cpu
2371  *    if vm fault gpu is on xgmi same hive of range actual loc gpu, best_loc is
2372  *    range actual loc.
2373  * Otherwise, GPU no access, best_loc is -1.
2374  *
2375  * Return:
2376  * -1 means vm fault GPU no access
2377  * 0 for CPU or GPU id
2378  */
2379 static int32_t
2380 svm_range_best_restore_location(struct svm_range *prange,
2381 				struct amdgpu_device *adev,
2382 				int32_t *gpuidx)
2383 {
2384 	struct amdgpu_device *bo_adev, *preferred_adev;
2385 	struct kfd_process *p;
2386 	uint32_t gpuid;
2387 	int r;
2388 
2389 	p = container_of(prange->svms, struct kfd_process, svms);
2390 
2391 	r = kfd_process_gpuid_from_adev(p, adev, &gpuid, gpuidx);
2392 	if (r < 0) {
2393 		pr_debug("failed to get gpuid from kgd\n");
2394 		return -1;
2395 	}
2396 
2397 	if (prange->preferred_loc == gpuid ||
2398 	    prange->preferred_loc == KFD_IOCTL_SVM_LOCATION_SYSMEM) {
2399 		return prange->preferred_loc;
2400 	} else if (prange->preferred_loc != KFD_IOCTL_SVM_LOCATION_UNDEFINED) {
2401 		preferred_adev = svm_range_get_adev_by_id(prange,
2402 							prange->preferred_loc);
2403 		if (amdgpu_xgmi_same_hive(adev, preferred_adev))
2404 			return prange->preferred_loc;
2405 		/* fall through */
2406 	}
2407 
2408 	if (test_bit(*gpuidx, prange->bitmap_access))
2409 		return gpuid;
2410 
2411 	if (test_bit(*gpuidx, prange->bitmap_aip)) {
2412 		if (!prange->actual_loc)
2413 			return 0;
2414 
2415 		bo_adev = svm_range_get_adev_by_id(prange, prange->actual_loc);
2416 		if (amdgpu_xgmi_same_hive(adev, bo_adev))
2417 			return prange->actual_loc;
2418 		else
2419 			return 0;
2420 	}
2421 
2422 	return -1;
2423 }
2424 
2425 static int
2426 svm_range_get_range_boundaries(struct kfd_process *p, int64_t addr,
2427 			       unsigned long *start, unsigned long *last,
2428 			       bool *is_heap_stack)
2429 {
2430 	struct vm_area_struct *vma;
2431 	struct interval_tree_node *node;
2432 	unsigned long start_limit, end_limit;
2433 
2434 	vma = find_vma(p->mm, addr << PAGE_SHIFT);
2435 	if (!vma || (addr << PAGE_SHIFT) < vma->vm_start) {
2436 		pr_debug("VMA does not exist in address [0x%llx]\n", addr);
2437 		return -EFAULT;
2438 	}
2439 
2440 	*is_heap_stack = (vma->vm_start <= vma->vm_mm->brk &&
2441 			  vma->vm_end >= vma->vm_mm->start_brk) ||
2442 			 (vma->vm_start <= vma->vm_mm->start_stack &&
2443 			  vma->vm_end >= vma->vm_mm->start_stack);
2444 
2445 	start_limit = max(vma->vm_start >> PAGE_SHIFT,
2446 		      (unsigned long)ALIGN_DOWN(addr, 2UL << 8));
2447 	end_limit = min(vma->vm_end >> PAGE_SHIFT,
2448 		    (unsigned long)ALIGN(addr + 1, 2UL << 8));
2449 	/* First range that starts after the fault address */
2450 	node = interval_tree_iter_first(&p->svms.objects, addr + 1, ULONG_MAX);
2451 	if (node) {
2452 		end_limit = min(end_limit, node->start);
2453 		/* Last range that ends before the fault address */
2454 		node = container_of(rb_prev(&node->rb),
2455 				    struct interval_tree_node, rb);
2456 	} else {
2457 		/* Last range must end before addr because
2458 		 * there was no range after addr
2459 		 */
2460 		node = container_of(rb_last(&p->svms.objects.rb_root),
2461 				    struct interval_tree_node, rb);
2462 	}
2463 	if (node) {
2464 		if (node->last >= addr) {
2465 			WARN(1, "Overlap with prev node and page fault addr\n");
2466 			return -EFAULT;
2467 		}
2468 		start_limit = max(start_limit, node->last + 1);
2469 	}
2470 
2471 	*start = start_limit;
2472 	*last = end_limit - 1;
2473 
2474 	pr_debug("vma [0x%lx 0x%lx] range [0x%lx 0x%lx] is_heap_stack %d\n",
2475 		 vma->vm_start >> PAGE_SHIFT, vma->vm_end >> PAGE_SHIFT,
2476 		 *start, *last, *is_heap_stack);
2477 
2478 	return 0;
2479 }
2480 
2481 static int
2482 svm_range_check_vm_userptr(struct kfd_process *p, uint64_t start, uint64_t last,
2483 			   uint64_t *bo_s, uint64_t *bo_l)
2484 {
2485 	struct amdgpu_bo_va_mapping *mapping;
2486 	struct interval_tree_node *node;
2487 	struct amdgpu_bo *bo = NULL;
2488 	unsigned long userptr;
2489 	uint32_t i;
2490 	int r;
2491 
2492 	for (i = 0; i < p->n_pdds; i++) {
2493 		struct amdgpu_vm *vm;
2494 
2495 		if (!p->pdds[i]->drm_priv)
2496 			continue;
2497 
2498 		vm = drm_priv_to_vm(p->pdds[i]->drm_priv);
2499 		r = amdgpu_bo_reserve(vm->root.bo, false);
2500 		if (r)
2501 			return r;
2502 
2503 		/* Check userptr by searching entire vm->va interval tree */
2504 		node = interval_tree_iter_first(&vm->va, 0, ~0ULL);
2505 		while (node) {
2506 			mapping = container_of((struct rb_node *)node,
2507 					       struct amdgpu_bo_va_mapping, rb);
2508 			bo = mapping->bo_va->base.bo;
2509 
2510 			if (!amdgpu_ttm_tt_affect_userptr(bo->tbo.ttm,
2511 							 start << PAGE_SHIFT,
2512 							 last << PAGE_SHIFT,
2513 							 &userptr)) {
2514 				node = interval_tree_iter_next(node, 0, ~0ULL);
2515 				continue;
2516 			}
2517 
2518 			pr_debug("[0x%llx 0x%llx] already userptr mapped\n",
2519 				 start, last);
2520 			if (bo_s && bo_l) {
2521 				*bo_s = userptr >> PAGE_SHIFT;
2522 				*bo_l = *bo_s + bo->tbo.ttm->num_pages - 1;
2523 			}
2524 			amdgpu_bo_unreserve(vm->root.bo);
2525 			return -EADDRINUSE;
2526 		}
2527 		amdgpu_bo_unreserve(vm->root.bo);
2528 	}
2529 	return 0;
2530 }
2531 
2532 static struct
2533 svm_range *svm_range_create_unregistered_range(struct amdgpu_device *adev,
2534 						struct kfd_process *p,
2535 						struct mm_struct *mm,
2536 						int64_t addr)
2537 {
2538 	struct svm_range *prange = NULL;
2539 	unsigned long start, last;
2540 	uint32_t gpuid, gpuidx;
2541 	bool is_heap_stack;
2542 	uint64_t bo_s = 0;
2543 	uint64_t bo_l = 0;
2544 	int r;
2545 
2546 	if (svm_range_get_range_boundaries(p, addr, &start, &last,
2547 					   &is_heap_stack))
2548 		return NULL;
2549 
2550 	r = svm_range_check_vm(p, start, last, &bo_s, &bo_l);
2551 	if (r != -EADDRINUSE)
2552 		r = svm_range_check_vm_userptr(p, start, last, &bo_s, &bo_l);
2553 
2554 	if (r == -EADDRINUSE) {
2555 		if (addr >= bo_s && addr <= bo_l)
2556 			return NULL;
2557 
2558 		/* Create one page svm range if 2MB range overlapping */
2559 		start = addr;
2560 		last = addr;
2561 	}
2562 
2563 	prange = svm_range_new(&p->svms, start, last);
2564 	if (!prange) {
2565 		pr_debug("Failed to create prange in address [0x%llx]\n", addr);
2566 		return NULL;
2567 	}
2568 	if (kfd_process_gpuid_from_adev(p, adev, &gpuid, &gpuidx)) {
2569 		pr_debug("failed to get gpuid from kgd\n");
2570 		svm_range_free(prange);
2571 		return NULL;
2572 	}
2573 
2574 	if (is_heap_stack)
2575 		prange->preferred_loc = KFD_IOCTL_SVM_LOCATION_SYSMEM;
2576 
2577 	svm_range_add_to_svms(prange);
2578 	svm_range_add_notifier_locked(mm, prange);
2579 
2580 	return prange;
2581 }
2582 
2583 /* svm_range_skip_recover - decide if prange can be recovered
2584  * @prange: svm range structure
2585  *
2586  * GPU vm retry fault handle skip recover the range for cases:
2587  * 1. prange is on deferred list to be removed after unmap, it is stale fault,
2588  *    deferred list work will drain the stale fault before free the prange.
2589  * 2. prange is on deferred list to add interval notifier after split, or
2590  * 3. prange is child range, it is split from parent prange, recover later
2591  *    after interval notifier is added.
2592  *
2593  * Return: true to skip recover, false to recover
2594  */
2595 static bool svm_range_skip_recover(struct svm_range *prange)
2596 {
2597 	struct svm_range_list *svms = prange->svms;
2598 
2599 	spin_lock(&svms->deferred_list_lock);
2600 	if (list_empty(&prange->deferred_list) &&
2601 	    list_empty(&prange->child_list)) {
2602 		spin_unlock(&svms->deferred_list_lock);
2603 		return false;
2604 	}
2605 	spin_unlock(&svms->deferred_list_lock);
2606 
2607 	if (prange->work_item.op == SVM_OP_UNMAP_RANGE) {
2608 		pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] unmapped\n",
2609 			 svms, prange, prange->start, prange->last);
2610 		return true;
2611 	}
2612 	if (prange->work_item.op == SVM_OP_ADD_RANGE_AND_MAP ||
2613 	    prange->work_item.op == SVM_OP_ADD_RANGE) {
2614 		pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] not added yet\n",
2615 			 svms, prange, prange->start, prange->last);
2616 		return true;
2617 	}
2618 	return false;
2619 }
2620 
2621 static void
2622 svm_range_count_fault(struct amdgpu_device *adev, struct kfd_process *p,
2623 		      int32_t gpuidx)
2624 {
2625 	struct kfd_process_device *pdd;
2626 
2627 	/* fault is on different page of same range
2628 	 * or fault is skipped to recover later
2629 	 * or fault is on invalid virtual address
2630 	 */
2631 	if (gpuidx == MAX_GPU_INSTANCE) {
2632 		uint32_t gpuid;
2633 		int r;
2634 
2635 		r = kfd_process_gpuid_from_adev(p, adev, &gpuid, &gpuidx);
2636 		if (r < 0)
2637 			return;
2638 	}
2639 
2640 	/* fault is recovered
2641 	 * or fault cannot recover because GPU no access on the range
2642 	 */
2643 	pdd = kfd_process_device_from_gpuidx(p, gpuidx);
2644 	if (pdd)
2645 		WRITE_ONCE(pdd->faults, pdd->faults + 1);
2646 }
2647 
2648 static bool
2649 svm_fault_allowed(struct vm_area_struct *vma, bool write_fault)
2650 {
2651 	unsigned long requested = VM_READ;
2652 
2653 	if (write_fault)
2654 		requested |= VM_WRITE;
2655 
2656 	pr_debug("requested 0x%lx, vma permission flags 0x%lx\n", requested,
2657 		vma->vm_flags);
2658 	return (vma->vm_flags & requested) == requested;
2659 }
2660 
2661 int
2662 svm_range_restore_pages(struct amdgpu_device *adev, unsigned int pasid,
2663 			uint64_t addr, bool write_fault)
2664 {
2665 	struct mm_struct *mm = NULL;
2666 	struct svm_range_list *svms;
2667 	struct svm_range *prange;
2668 	struct kfd_process *p;
2669 	uint64_t timestamp;
2670 	int32_t best_loc;
2671 	int32_t gpuidx = MAX_GPU_INSTANCE;
2672 	bool write_locked = false;
2673 	struct vm_area_struct *vma;
2674 	int r = 0;
2675 
2676 	if (!KFD_IS_SVM_API_SUPPORTED(adev->kfd.dev)) {
2677 		pr_debug("device does not support SVM\n");
2678 		return -EFAULT;
2679 	}
2680 
2681 	p = kfd_lookup_process_by_pasid(pasid);
2682 	if (!p) {
2683 		pr_debug("kfd process not founded pasid 0x%x\n", pasid);
2684 		return 0;
2685 	}
2686 	if (!p->xnack_enabled) {
2687 		pr_debug("XNACK not enabled for pasid 0x%x\n", pasid);
2688 		r = -EFAULT;
2689 		goto out;
2690 	}
2691 	svms = &p->svms;
2692 
2693 	pr_debug("restoring svms 0x%p fault address 0x%llx\n", svms, addr);
2694 
2695 	if (atomic_read(&svms->drain_pagefaults)) {
2696 		pr_debug("draining retry fault, drop fault 0x%llx\n", addr);
2697 		r = 0;
2698 		goto out;
2699 	}
2700 
2701 	/* p->lead_thread is available as kfd_process_wq_release flush the work
2702 	 * before releasing task ref.
2703 	 */
2704 	mm = get_task_mm(p->lead_thread);
2705 	if (!mm) {
2706 		pr_debug("svms 0x%p failed to get mm\n", svms);
2707 		r = 0;
2708 		goto out;
2709 	}
2710 
2711 	mmap_read_lock(mm);
2712 retry_write_locked:
2713 	mutex_lock(&svms->lock);
2714 	prange = svm_range_from_addr(svms, addr, NULL);
2715 	if (!prange) {
2716 		pr_debug("failed to find prange svms 0x%p address [0x%llx]\n",
2717 			 svms, addr);
2718 		if (!write_locked) {
2719 			/* Need the write lock to create new range with MMU notifier.
2720 			 * Also flush pending deferred work to make sure the interval
2721 			 * tree is up to date before we add a new range
2722 			 */
2723 			mutex_unlock(&svms->lock);
2724 			mmap_read_unlock(mm);
2725 			mmap_write_lock(mm);
2726 			write_locked = true;
2727 			goto retry_write_locked;
2728 		}
2729 		prange = svm_range_create_unregistered_range(adev, p, mm, addr);
2730 		if (!prange) {
2731 			pr_debug("failed to create unregistered range svms 0x%p address [0x%llx]\n",
2732 				 svms, addr);
2733 			mmap_write_downgrade(mm);
2734 			r = -EFAULT;
2735 			goto out_unlock_svms;
2736 		}
2737 	}
2738 	if (write_locked)
2739 		mmap_write_downgrade(mm);
2740 
2741 	mutex_lock(&prange->migrate_mutex);
2742 
2743 	if (svm_range_skip_recover(prange)) {
2744 		amdgpu_gmc_filter_faults_remove(adev, addr, pasid);
2745 		r = 0;
2746 		goto out_unlock_range;
2747 	}
2748 
2749 	timestamp = ktime_to_us(ktime_get()) - prange->validate_timestamp;
2750 	/* skip duplicate vm fault on different pages of same range */
2751 	if (timestamp < AMDGPU_SVM_RANGE_RETRY_FAULT_PENDING) {
2752 		pr_debug("svms 0x%p [0x%lx %lx] already restored\n",
2753 			 svms, prange->start, prange->last);
2754 		r = 0;
2755 		goto out_unlock_range;
2756 	}
2757 
2758 	/* __do_munmap removed VMA, return success as we are handling stale
2759 	 * retry fault.
2760 	 */
2761 	vma = find_vma(mm, addr << PAGE_SHIFT);
2762 	if (!vma || (addr << PAGE_SHIFT) < vma->vm_start) {
2763 		pr_debug("address 0x%llx VMA is removed\n", addr);
2764 		r = 0;
2765 		goto out_unlock_range;
2766 	}
2767 
2768 	if (!svm_fault_allowed(vma, write_fault)) {
2769 		pr_debug("fault addr 0x%llx no %s permission\n", addr,
2770 			write_fault ? "write" : "read");
2771 		r = -EPERM;
2772 		goto out_unlock_range;
2773 	}
2774 
2775 	best_loc = svm_range_best_restore_location(prange, adev, &gpuidx);
2776 	if (best_loc == -1) {
2777 		pr_debug("svms %p failed get best restore loc [0x%lx 0x%lx]\n",
2778 			 svms, prange->start, prange->last);
2779 		r = -EACCES;
2780 		goto out_unlock_range;
2781 	}
2782 
2783 	pr_debug("svms %p [0x%lx 0x%lx] best restore 0x%x, actual loc 0x%x\n",
2784 		 svms, prange->start, prange->last, best_loc,
2785 		 prange->actual_loc);
2786 
2787 	if (prange->actual_loc != best_loc) {
2788 		if (best_loc) {
2789 			r = svm_migrate_to_vram(prange, best_loc, mm);
2790 			if (r) {
2791 				pr_debug("svm_migrate_to_vram failed (%d) at %llx, falling back to system memory\n",
2792 					 r, addr);
2793 				/* Fallback to system memory if migration to
2794 				 * VRAM failed
2795 				 */
2796 				if (prange->actual_loc)
2797 					r = svm_migrate_vram_to_ram(prange, mm);
2798 				else
2799 					r = 0;
2800 			}
2801 		} else {
2802 			r = svm_migrate_vram_to_ram(prange, mm);
2803 		}
2804 		if (r) {
2805 			pr_debug("failed %d to migrate svms %p [0x%lx 0x%lx]\n",
2806 				 r, svms, prange->start, prange->last);
2807 			goto out_unlock_range;
2808 		}
2809 	}
2810 
2811 	r = svm_range_validate_and_map(mm, prange, gpuidx, false, false);
2812 	if (r)
2813 		pr_debug("failed %d to map svms 0x%p [0x%lx 0x%lx] to gpus\n",
2814 			 r, svms, prange->start, prange->last);
2815 
2816 out_unlock_range:
2817 	mutex_unlock(&prange->migrate_mutex);
2818 out_unlock_svms:
2819 	mutex_unlock(&svms->lock);
2820 	mmap_read_unlock(mm);
2821 
2822 	svm_range_count_fault(adev, p, gpuidx);
2823 
2824 	mmput(mm);
2825 out:
2826 	kfd_unref_process(p);
2827 
2828 	if (r == -EAGAIN) {
2829 		pr_debug("recover vm fault later\n");
2830 		amdgpu_gmc_filter_faults_remove(adev, addr, pasid);
2831 		r = 0;
2832 	}
2833 	return r;
2834 }
2835 
2836 void svm_range_list_fini(struct kfd_process *p)
2837 {
2838 	struct svm_range *prange;
2839 	struct svm_range *next;
2840 
2841 	pr_debug("pasid 0x%x svms 0x%p\n", p->pasid, &p->svms);
2842 
2843 	cancel_delayed_work_sync(&p->svms.restore_work);
2844 
2845 	/* Ensure list work is finished before process is destroyed */
2846 	flush_work(&p->svms.deferred_list_work);
2847 
2848 	/*
2849 	 * Ensure no retry fault comes in afterwards, as page fault handler will
2850 	 * not find kfd process and take mm lock to recover fault.
2851 	 */
2852 	atomic_inc(&p->svms.drain_pagefaults);
2853 	svm_range_drain_retry_fault(&p->svms);
2854 
2855 	list_for_each_entry_safe(prange, next, &p->svms.list, list) {
2856 		svm_range_unlink(prange);
2857 		svm_range_remove_notifier(prange);
2858 		svm_range_free(prange);
2859 	}
2860 
2861 	mutex_destroy(&p->svms.lock);
2862 
2863 	pr_debug("pasid 0x%x svms 0x%p done\n", p->pasid, &p->svms);
2864 }
2865 
2866 int svm_range_list_init(struct kfd_process *p)
2867 {
2868 	struct svm_range_list *svms = &p->svms;
2869 	int i;
2870 
2871 	svms->objects = RB_ROOT_CACHED;
2872 	mutex_init(&svms->lock);
2873 	INIT_LIST_HEAD(&svms->list);
2874 	atomic_set(&svms->evicted_ranges, 0);
2875 	atomic_set(&svms->drain_pagefaults, 0);
2876 	INIT_DELAYED_WORK(&svms->restore_work, svm_range_restore_work);
2877 	INIT_WORK(&svms->deferred_list_work, svm_range_deferred_list_work);
2878 	INIT_LIST_HEAD(&svms->deferred_range_list);
2879 	INIT_LIST_HEAD(&svms->criu_svm_metadata_list);
2880 	spin_lock_init(&svms->deferred_list_lock);
2881 
2882 	for (i = 0; i < p->n_pdds; i++)
2883 		if (KFD_IS_SVM_API_SUPPORTED(p->pdds[i]->dev))
2884 			bitmap_set(svms->bitmap_supported, i, 1);
2885 
2886 	return 0;
2887 }
2888 
2889 /**
2890  * svm_range_check_vm - check if virtual address range mapped already
2891  * @p: current kfd_process
2892  * @start: range start address, in pages
2893  * @last: range last address, in pages
2894  * @bo_s: mapping start address in pages if address range already mapped
2895  * @bo_l: mapping last address in pages if address range already mapped
2896  *
2897  * The purpose is to avoid virtual address ranges already allocated by
2898  * kfd_ioctl_alloc_memory_of_gpu ioctl.
2899  * It looks for each pdd in the kfd_process.
2900  *
2901  * Context: Process context
2902  *
2903  * Return 0 - OK, if the range is not mapped.
2904  * Otherwise error code:
2905  * -EADDRINUSE - if address is mapped already by kfd_ioctl_alloc_memory_of_gpu
2906  * -ERESTARTSYS - A wait for the buffer to become unreserved was interrupted by
2907  * a signal. Release all buffer reservations and return to user-space.
2908  */
2909 static int
2910 svm_range_check_vm(struct kfd_process *p, uint64_t start, uint64_t last,
2911 		   uint64_t *bo_s, uint64_t *bo_l)
2912 {
2913 	struct amdgpu_bo_va_mapping *mapping;
2914 	struct interval_tree_node *node;
2915 	uint32_t i;
2916 	int r;
2917 
2918 	for (i = 0; i < p->n_pdds; i++) {
2919 		struct amdgpu_vm *vm;
2920 
2921 		if (!p->pdds[i]->drm_priv)
2922 			continue;
2923 
2924 		vm = drm_priv_to_vm(p->pdds[i]->drm_priv);
2925 		r = amdgpu_bo_reserve(vm->root.bo, false);
2926 		if (r)
2927 			return r;
2928 
2929 		node = interval_tree_iter_first(&vm->va, start, last);
2930 		if (node) {
2931 			pr_debug("range [0x%llx 0x%llx] already TTM mapped\n",
2932 				 start, last);
2933 			mapping = container_of((struct rb_node *)node,
2934 					       struct amdgpu_bo_va_mapping, rb);
2935 			if (bo_s && bo_l) {
2936 				*bo_s = mapping->start;
2937 				*bo_l = mapping->last;
2938 			}
2939 			amdgpu_bo_unreserve(vm->root.bo);
2940 			return -EADDRINUSE;
2941 		}
2942 		amdgpu_bo_unreserve(vm->root.bo);
2943 	}
2944 
2945 	return 0;
2946 }
2947 
2948 /**
2949  * svm_range_is_valid - check if virtual address range is valid
2950  * @p: current kfd_process
2951  * @start: range start address, in pages
2952  * @size: range size, in pages
2953  *
2954  * Valid virtual address range means it belongs to one or more VMAs
2955  *
2956  * Context: Process context
2957  *
2958  * Return:
2959  *  0 - OK, otherwise error code
2960  */
2961 static int
2962 svm_range_is_valid(struct kfd_process *p, uint64_t start, uint64_t size)
2963 {
2964 	const unsigned long device_vma = VM_IO | VM_PFNMAP | VM_MIXEDMAP;
2965 	struct vm_area_struct *vma;
2966 	unsigned long end;
2967 	unsigned long start_unchg = start;
2968 
2969 	start <<= PAGE_SHIFT;
2970 	end = start + (size << PAGE_SHIFT);
2971 	do {
2972 		vma = find_vma(p->mm, start);
2973 		if (!vma || start < vma->vm_start ||
2974 		    (vma->vm_flags & device_vma))
2975 			return -EFAULT;
2976 		start = min(end, vma->vm_end);
2977 	} while (start < end);
2978 
2979 	return svm_range_check_vm(p, start_unchg, (end - 1) >> PAGE_SHIFT, NULL,
2980 				  NULL);
2981 }
2982 
2983 /**
2984  * svm_range_best_prefetch_location - decide the best prefetch location
2985  * @prange: svm range structure
2986  *
2987  * For xnack off:
2988  * If range map to single GPU, the best prefetch location is prefetch_loc, which
2989  * can be CPU or GPU.
2990  *
2991  * If range is ACCESS or ACCESS_IN_PLACE by mGPUs, only if mGPU connection on
2992  * XGMI same hive, the best prefetch location is prefetch_loc GPU, othervise
2993  * the best prefetch location is always CPU, because GPU can not have coherent
2994  * mapping VRAM of other GPUs even with large-BAR PCIe connection.
2995  *
2996  * For xnack on:
2997  * If range is not ACCESS_IN_PLACE by mGPUs, the best prefetch location is
2998  * prefetch_loc, other GPU access will generate vm fault and trigger migration.
2999  *
3000  * If range is ACCESS_IN_PLACE by mGPUs, only if mGPU connection on XGMI same
3001  * hive, the best prefetch location is prefetch_loc GPU, otherwise the best
3002  * prefetch location is always CPU.
3003  *
3004  * Context: Process context
3005  *
3006  * Return:
3007  * 0 for CPU or GPU id
3008  */
3009 static uint32_t
3010 svm_range_best_prefetch_location(struct svm_range *prange)
3011 {
3012 	DECLARE_BITMAP(bitmap, MAX_GPU_INSTANCE);
3013 	uint32_t best_loc = prange->prefetch_loc;
3014 	struct kfd_process_device *pdd;
3015 	struct amdgpu_device *bo_adev;
3016 	struct kfd_process *p;
3017 	uint32_t gpuidx;
3018 
3019 	p = container_of(prange->svms, struct kfd_process, svms);
3020 
3021 	if (!best_loc || best_loc == KFD_IOCTL_SVM_LOCATION_UNDEFINED)
3022 		goto out;
3023 
3024 	bo_adev = svm_range_get_adev_by_id(prange, best_loc);
3025 	if (!bo_adev) {
3026 		WARN_ONCE(1, "failed to get device by id 0x%x\n", best_loc);
3027 		best_loc = 0;
3028 		goto out;
3029 	}
3030 
3031 	if (p->xnack_enabled)
3032 		bitmap_copy(bitmap, prange->bitmap_aip, MAX_GPU_INSTANCE);
3033 	else
3034 		bitmap_or(bitmap, prange->bitmap_access, prange->bitmap_aip,
3035 			  MAX_GPU_INSTANCE);
3036 
3037 	for_each_set_bit(gpuidx, bitmap, MAX_GPU_INSTANCE) {
3038 		pdd = kfd_process_device_from_gpuidx(p, gpuidx);
3039 		if (!pdd) {
3040 			pr_debug("failed to get device by idx 0x%x\n", gpuidx);
3041 			continue;
3042 		}
3043 
3044 		if (pdd->dev->adev == bo_adev)
3045 			continue;
3046 
3047 		if (!amdgpu_xgmi_same_hive(pdd->dev->adev, bo_adev)) {
3048 			best_loc = 0;
3049 			break;
3050 		}
3051 	}
3052 
3053 out:
3054 	pr_debug("xnack %d svms 0x%p [0x%lx 0x%lx] best loc 0x%x\n",
3055 		 p->xnack_enabled, &p->svms, prange->start, prange->last,
3056 		 best_loc);
3057 
3058 	return best_loc;
3059 }
3060 
3061 /* FIXME: This is a workaround for page locking bug when some pages are
3062  * invalid during migration to VRAM
3063  */
3064 void svm_range_prefault(struct svm_range *prange, struct mm_struct *mm,
3065 			void *owner)
3066 {
3067 	struct hmm_range *hmm_range;
3068 	int r;
3069 
3070 	if (prange->validated_once)
3071 		return;
3072 
3073 	r = amdgpu_hmm_range_get_pages(&prange->notifier, mm, NULL,
3074 				       prange->start << PAGE_SHIFT,
3075 				       prange->npages, &hmm_range,
3076 				       false, true, owner);
3077 	if (!r) {
3078 		amdgpu_hmm_range_get_pages_done(hmm_range);
3079 		prange->validated_once = true;
3080 	}
3081 }
3082 
3083 /* svm_range_trigger_migration - start page migration if prefetch loc changed
3084  * @mm: current process mm_struct
3085  * @prange: svm range structure
3086  * @migrated: output, true if migration is triggered
3087  *
3088  * If range perfetch_loc is GPU, actual loc is cpu 0, then migrate the range
3089  * from ram to vram.
3090  * If range prefetch_loc is cpu 0, actual loc is GPU, then migrate the range
3091  * from vram to ram.
3092  *
3093  * If GPU vm fault retry is not enabled, migration interact with MMU notifier
3094  * and restore work:
3095  * 1. migrate_vma_setup invalidate pages, MMU notifier callback svm_range_evict
3096  *    stops all queues, schedule restore work
3097  * 2. svm_range_restore_work wait for migration is done by
3098  *    a. svm_range_validate_vram takes prange->migrate_mutex
3099  *    b. svm_range_validate_ram HMM get pages wait for CPU fault handle returns
3100  * 3. restore work update mappings of GPU, resume all queues.
3101  *
3102  * Context: Process context
3103  *
3104  * Return:
3105  * 0 - OK, otherwise - error code of migration
3106  */
3107 static int
3108 svm_range_trigger_migration(struct mm_struct *mm, struct svm_range *prange,
3109 			    bool *migrated)
3110 {
3111 	uint32_t best_loc;
3112 	int r = 0;
3113 
3114 	*migrated = false;
3115 	best_loc = svm_range_best_prefetch_location(prange);
3116 
3117 	if (best_loc == KFD_IOCTL_SVM_LOCATION_UNDEFINED ||
3118 	    best_loc == prange->actual_loc)
3119 		return 0;
3120 
3121 	if (!best_loc) {
3122 		r = svm_migrate_vram_to_ram(prange, mm);
3123 		*migrated = !r;
3124 		return r;
3125 	}
3126 
3127 	r = svm_migrate_to_vram(prange, best_loc, mm);
3128 	*migrated = !r;
3129 
3130 	return r;
3131 }
3132 
3133 int svm_range_schedule_evict_svm_bo(struct amdgpu_amdkfd_fence *fence)
3134 {
3135 	if (!fence)
3136 		return -EINVAL;
3137 
3138 	if (dma_fence_is_signaled(&fence->base))
3139 		return 0;
3140 
3141 	if (fence->svm_bo) {
3142 		WRITE_ONCE(fence->svm_bo->evicting, 1);
3143 		schedule_work(&fence->svm_bo->eviction_work);
3144 	}
3145 
3146 	return 0;
3147 }
3148 
3149 static void svm_range_evict_svm_bo_worker(struct work_struct *work)
3150 {
3151 	struct svm_range_bo *svm_bo;
3152 	struct kfd_process *p;
3153 	struct mm_struct *mm;
3154 
3155 	svm_bo = container_of(work, struct svm_range_bo, eviction_work);
3156 	if (!svm_bo_ref_unless_zero(svm_bo))
3157 		return; /* svm_bo was freed while eviction was pending */
3158 
3159 	/* svm_range_bo_release destroys this worker thread. So during
3160 	 * the lifetime of this thread, kfd_process and mm will be valid.
3161 	 */
3162 	p = container_of(svm_bo->svms, struct kfd_process, svms);
3163 	mm = p->mm;
3164 	if (!mm)
3165 		return;
3166 
3167 	mmap_read_lock(mm);
3168 	spin_lock(&svm_bo->list_lock);
3169 	while (!list_empty(&svm_bo->range_list)) {
3170 		struct svm_range *prange =
3171 				list_first_entry(&svm_bo->range_list,
3172 						struct svm_range, svm_bo_list);
3173 		int retries = 3;
3174 
3175 		list_del_init(&prange->svm_bo_list);
3176 		spin_unlock(&svm_bo->list_lock);
3177 
3178 		pr_debug("svms 0x%p [0x%lx 0x%lx]\n", prange->svms,
3179 			 prange->start, prange->last);
3180 
3181 		mutex_lock(&prange->migrate_mutex);
3182 		do {
3183 			svm_migrate_vram_to_ram(prange,
3184 						svm_bo->eviction_fence->mm);
3185 		} while (prange->actual_loc && --retries);
3186 		WARN(prange->actual_loc, "Migration failed during eviction");
3187 
3188 		mutex_lock(&prange->lock);
3189 		prange->svm_bo = NULL;
3190 		mutex_unlock(&prange->lock);
3191 
3192 		mutex_unlock(&prange->migrate_mutex);
3193 
3194 		spin_lock(&svm_bo->list_lock);
3195 	}
3196 	spin_unlock(&svm_bo->list_lock);
3197 	mmap_read_unlock(mm);
3198 
3199 	dma_fence_signal(&svm_bo->eviction_fence->base);
3200 	/* This is the last reference to svm_bo, after svm_range_vram_node_free
3201 	 * has been called in svm_migrate_vram_to_ram
3202 	 */
3203 	WARN_ONCE(kref_read(&svm_bo->kref) != 1, "This was not the last reference\n");
3204 	svm_range_bo_unref(svm_bo);
3205 }
3206 
3207 static int
3208 svm_range_set_attr(struct kfd_process *p, struct mm_struct *mm,
3209 		   uint64_t start, uint64_t size, uint32_t nattr,
3210 		   struct kfd_ioctl_svm_attribute *attrs)
3211 {
3212 	struct list_head update_list;
3213 	struct list_head insert_list;
3214 	struct list_head remove_list;
3215 	struct svm_range_list *svms;
3216 	struct svm_range *prange;
3217 	struct svm_range *next;
3218 	int r = 0;
3219 
3220 	pr_debug("pasid 0x%x svms 0x%p [0x%llx 0x%llx] pages 0x%llx\n",
3221 		 p->pasid, &p->svms, start, start + size - 1, size);
3222 
3223 	r = svm_range_check_attr(p, nattr, attrs);
3224 	if (r)
3225 		return r;
3226 
3227 	svms = &p->svms;
3228 
3229 	svm_range_list_lock_and_flush_work(svms, mm);
3230 
3231 	r = svm_range_is_valid(p, start, size);
3232 	if (r) {
3233 		pr_debug("invalid range r=%d\n", r);
3234 		mmap_write_unlock(mm);
3235 		goto out;
3236 	}
3237 
3238 	mutex_lock(&svms->lock);
3239 
3240 	/* Add new range and split existing ranges as needed */
3241 	r = svm_range_add(p, start, size, nattr, attrs, &update_list,
3242 			  &insert_list, &remove_list);
3243 	if (r) {
3244 		mutex_unlock(&svms->lock);
3245 		mmap_write_unlock(mm);
3246 		goto out;
3247 	}
3248 	/* Apply changes as a transaction */
3249 	list_for_each_entry_safe(prange, next, &insert_list, list) {
3250 		svm_range_add_to_svms(prange);
3251 		svm_range_add_notifier_locked(mm, prange);
3252 	}
3253 	list_for_each_entry(prange, &update_list, update_list) {
3254 		svm_range_apply_attrs(p, prange, nattr, attrs);
3255 		/* TODO: unmap ranges from GPU that lost access */
3256 	}
3257 	list_for_each_entry_safe(prange, next, &remove_list, update_list) {
3258 		pr_debug("unlink old 0x%p prange 0x%p [0x%lx 0x%lx]\n",
3259 			 prange->svms, prange, prange->start,
3260 			 prange->last);
3261 		svm_range_unlink(prange);
3262 		svm_range_remove_notifier(prange);
3263 		svm_range_free(prange);
3264 	}
3265 
3266 	mmap_write_downgrade(mm);
3267 	/* Trigger migrations and revalidate and map to GPUs as needed. If
3268 	 * this fails we may be left with partially completed actions. There
3269 	 * is no clean way of rolling back to the previous state in such a
3270 	 * case because the rollback wouldn't be guaranteed to work either.
3271 	 */
3272 	list_for_each_entry(prange, &update_list, update_list) {
3273 		bool migrated;
3274 
3275 		mutex_lock(&prange->migrate_mutex);
3276 
3277 		r = svm_range_trigger_migration(mm, prange, &migrated);
3278 		if (r)
3279 			goto out_unlock_range;
3280 
3281 		if (migrated && !p->xnack_enabled) {
3282 			pr_debug("restore_work will update mappings of GPUs\n");
3283 			mutex_unlock(&prange->migrate_mutex);
3284 			continue;
3285 		}
3286 
3287 		r = svm_range_validate_and_map(mm, prange, MAX_GPU_INSTANCE,
3288 					       true, true);
3289 		if (r)
3290 			pr_debug("failed %d to map svm range\n", r);
3291 
3292 out_unlock_range:
3293 		mutex_unlock(&prange->migrate_mutex);
3294 		if (r)
3295 			break;
3296 	}
3297 
3298 	svm_range_debug_dump(svms);
3299 
3300 	mutex_unlock(&svms->lock);
3301 	mmap_read_unlock(mm);
3302 out:
3303 	pr_debug("pasid 0x%x svms 0x%p [0x%llx 0x%llx] done, r=%d\n", p->pasid,
3304 		 &p->svms, start, start + size - 1, r);
3305 
3306 	return r;
3307 }
3308 
3309 static int
3310 svm_range_get_attr(struct kfd_process *p, struct mm_struct *mm,
3311 		   uint64_t start, uint64_t size, uint32_t nattr,
3312 		   struct kfd_ioctl_svm_attribute *attrs)
3313 {
3314 	DECLARE_BITMAP(bitmap_access, MAX_GPU_INSTANCE);
3315 	DECLARE_BITMAP(bitmap_aip, MAX_GPU_INSTANCE);
3316 	bool get_preferred_loc = false;
3317 	bool get_prefetch_loc = false;
3318 	bool get_granularity = false;
3319 	bool get_accessible = false;
3320 	bool get_flags = false;
3321 	uint64_t last = start + size - 1UL;
3322 	uint8_t granularity = 0xff;
3323 	struct interval_tree_node *node;
3324 	struct svm_range_list *svms;
3325 	struct svm_range *prange;
3326 	uint32_t prefetch_loc = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3327 	uint32_t location = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3328 	uint32_t flags_and = 0xffffffff;
3329 	uint32_t flags_or = 0;
3330 	int gpuidx;
3331 	uint32_t i;
3332 	int r = 0;
3333 
3334 	pr_debug("svms 0x%p [0x%llx 0x%llx] nattr 0x%x\n", &p->svms, start,
3335 		 start + size - 1, nattr);
3336 
3337 	/* Flush pending deferred work to avoid racing with deferred actions from
3338 	 * previous memory map changes (e.g. munmap). Concurrent memory map changes
3339 	 * can still race with get_attr because we don't hold the mmap lock. But that
3340 	 * would be a race condition in the application anyway, and undefined
3341 	 * behaviour is acceptable in that case.
3342 	 */
3343 	flush_work(&p->svms.deferred_list_work);
3344 
3345 	mmap_read_lock(mm);
3346 	r = svm_range_is_valid(p, start, size);
3347 	mmap_read_unlock(mm);
3348 	if (r) {
3349 		pr_debug("invalid range r=%d\n", r);
3350 		return r;
3351 	}
3352 
3353 	for (i = 0; i < nattr; i++) {
3354 		switch (attrs[i].type) {
3355 		case KFD_IOCTL_SVM_ATTR_PREFERRED_LOC:
3356 			get_preferred_loc = true;
3357 			break;
3358 		case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
3359 			get_prefetch_loc = true;
3360 			break;
3361 		case KFD_IOCTL_SVM_ATTR_ACCESS:
3362 			get_accessible = true;
3363 			break;
3364 		case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
3365 		case KFD_IOCTL_SVM_ATTR_CLR_FLAGS:
3366 			get_flags = true;
3367 			break;
3368 		case KFD_IOCTL_SVM_ATTR_GRANULARITY:
3369 			get_granularity = true;
3370 			break;
3371 		case KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE:
3372 		case KFD_IOCTL_SVM_ATTR_NO_ACCESS:
3373 			fallthrough;
3374 		default:
3375 			pr_debug("get invalid attr type 0x%x\n", attrs[i].type);
3376 			return -EINVAL;
3377 		}
3378 	}
3379 
3380 	svms = &p->svms;
3381 
3382 	mutex_lock(&svms->lock);
3383 
3384 	node = interval_tree_iter_first(&svms->objects, start, last);
3385 	if (!node) {
3386 		pr_debug("range attrs not found return default values\n");
3387 		svm_range_set_default_attributes(&location, &prefetch_loc,
3388 						 &granularity, &flags_and);
3389 		flags_or = flags_and;
3390 		if (p->xnack_enabled)
3391 			bitmap_copy(bitmap_access, svms->bitmap_supported,
3392 				    MAX_GPU_INSTANCE);
3393 		else
3394 			bitmap_zero(bitmap_access, MAX_GPU_INSTANCE);
3395 		bitmap_zero(bitmap_aip, MAX_GPU_INSTANCE);
3396 		goto fill_values;
3397 	}
3398 	bitmap_copy(bitmap_access, svms->bitmap_supported, MAX_GPU_INSTANCE);
3399 	bitmap_copy(bitmap_aip, svms->bitmap_supported, MAX_GPU_INSTANCE);
3400 
3401 	while (node) {
3402 		struct interval_tree_node *next;
3403 
3404 		prange = container_of(node, struct svm_range, it_node);
3405 		next = interval_tree_iter_next(node, start, last);
3406 
3407 		if (get_preferred_loc) {
3408 			if (prange->preferred_loc ==
3409 					KFD_IOCTL_SVM_LOCATION_UNDEFINED ||
3410 			    (location != KFD_IOCTL_SVM_LOCATION_UNDEFINED &&
3411 			     location != prange->preferred_loc)) {
3412 				location = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3413 				get_preferred_loc = false;
3414 			} else {
3415 				location = prange->preferred_loc;
3416 			}
3417 		}
3418 		if (get_prefetch_loc) {
3419 			if (prange->prefetch_loc ==
3420 					KFD_IOCTL_SVM_LOCATION_UNDEFINED ||
3421 			    (prefetch_loc != KFD_IOCTL_SVM_LOCATION_UNDEFINED &&
3422 			     prefetch_loc != prange->prefetch_loc)) {
3423 				prefetch_loc = KFD_IOCTL_SVM_LOCATION_UNDEFINED;
3424 				get_prefetch_loc = false;
3425 			} else {
3426 				prefetch_loc = prange->prefetch_loc;
3427 			}
3428 		}
3429 		if (get_accessible) {
3430 			bitmap_and(bitmap_access, bitmap_access,
3431 				   prange->bitmap_access, MAX_GPU_INSTANCE);
3432 			bitmap_and(bitmap_aip, bitmap_aip,
3433 				   prange->bitmap_aip, MAX_GPU_INSTANCE);
3434 		}
3435 		if (get_flags) {
3436 			flags_and &= prange->flags;
3437 			flags_or |= prange->flags;
3438 		}
3439 
3440 		if (get_granularity && prange->granularity < granularity)
3441 			granularity = prange->granularity;
3442 
3443 		node = next;
3444 	}
3445 fill_values:
3446 	mutex_unlock(&svms->lock);
3447 
3448 	for (i = 0; i < nattr; i++) {
3449 		switch (attrs[i].type) {
3450 		case KFD_IOCTL_SVM_ATTR_PREFERRED_LOC:
3451 			attrs[i].value = location;
3452 			break;
3453 		case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
3454 			attrs[i].value = prefetch_loc;
3455 			break;
3456 		case KFD_IOCTL_SVM_ATTR_ACCESS:
3457 			gpuidx = kfd_process_gpuidx_from_gpuid(p,
3458 							       attrs[i].value);
3459 			if (gpuidx < 0) {
3460 				pr_debug("invalid gpuid %x\n", attrs[i].value);
3461 				return -EINVAL;
3462 			}
3463 			if (test_bit(gpuidx, bitmap_access))
3464 				attrs[i].type = KFD_IOCTL_SVM_ATTR_ACCESS;
3465 			else if (test_bit(gpuidx, bitmap_aip))
3466 				attrs[i].type =
3467 					KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE;
3468 			else
3469 				attrs[i].type = KFD_IOCTL_SVM_ATTR_NO_ACCESS;
3470 			break;
3471 		case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
3472 			attrs[i].value = flags_and;
3473 			break;
3474 		case KFD_IOCTL_SVM_ATTR_CLR_FLAGS:
3475 			attrs[i].value = ~flags_or;
3476 			break;
3477 		case KFD_IOCTL_SVM_ATTR_GRANULARITY:
3478 			attrs[i].value = (uint32_t)granularity;
3479 			break;
3480 		}
3481 	}
3482 
3483 	return 0;
3484 }
3485 
3486 int kfd_criu_resume_svm(struct kfd_process *p)
3487 {
3488 	struct kfd_ioctl_svm_attribute *set_attr_new, *set_attr = NULL;
3489 	int nattr_common = 4, nattr_accessibility = 1;
3490 	struct criu_svm_metadata *criu_svm_md = NULL;
3491 	struct svm_range_list *svms = &p->svms;
3492 	struct criu_svm_metadata *next = NULL;
3493 	uint32_t set_flags = 0xffffffff;
3494 	int i, j, num_attrs, ret = 0;
3495 	uint64_t set_attr_size;
3496 	struct mm_struct *mm;
3497 
3498 	if (list_empty(&svms->criu_svm_metadata_list)) {
3499 		pr_debug("No SVM data from CRIU restore stage 2\n");
3500 		return ret;
3501 	}
3502 
3503 	mm = get_task_mm(p->lead_thread);
3504 	if (!mm) {
3505 		pr_err("failed to get mm for the target process\n");
3506 		return -ESRCH;
3507 	}
3508 
3509 	num_attrs = nattr_common + (nattr_accessibility * p->n_pdds);
3510 
3511 	i = j = 0;
3512 	list_for_each_entry(criu_svm_md, &svms->criu_svm_metadata_list, list) {
3513 		pr_debug("criu_svm_md[%d]\n\tstart: 0x%llx size: 0x%llx (npages)\n",
3514 			 i, criu_svm_md->data.start_addr, criu_svm_md->data.size);
3515 
3516 		for (j = 0; j < num_attrs; j++) {
3517 			pr_debug("\ncriu_svm_md[%d]->attrs[%d].type : 0x%x\ncriu_svm_md[%d]->attrs[%d].value : 0x%x\n",
3518 				 i, j, criu_svm_md->data.attrs[j].type,
3519 				 i, j, criu_svm_md->data.attrs[j].value);
3520 			switch (criu_svm_md->data.attrs[j].type) {
3521 			/* During Checkpoint operation, the query for
3522 			 * KFD_IOCTL_SVM_ATTR_PREFETCH_LOC attribute might
3523 			 * return KFD_IOCTL_SVM_LOCATION_UNDEFINED if they were
3524 			 * not used by the range which was checkpointed. Care
3525 			 * must be taken to not restore with an invalid value
3526 			 * otherwise the gpuidx value will be invalid and
3527 			 * set_attr would eventually fail so just replace those
3528 			 * with another dummy attribute such as
3529 			 * KFD_IOCTL_SVM_ATTR_SET_FLAGS.
3530 			 */
3531 			case KFD_IOCTL_SVM_ATTR_PREFETCH_LOC:
3532 				if (criu_svm_md->data.attrs[j].value ==
3533 				    KFD_IOCTL_SVM_LOCATION_UNDEFINED) {
3534 					criu_svm_md->data.attrs[j].type =
3535 						KFD_IOCTL_SVM_ATTR_SET_FLAGS;
3536 					criu_svm_md->data.attrs[j].value = 0;
3537 				}
3538 				break;
3539 			case KFD_IOCTL_SVM_ATTR_SET_FLAGS:
3540 				set_flags = criu_svm_md->data.attrs[j].value;
3541 				break;
3542 			default:
3543 				break;
3544 			}
3545 		}
3546 
3547 		/* CLR_FLAGS is not available via get_attr during checkpoint but
3548 		 * it needs to be inserted before restoring the ranges so
3549 		 * allocate extra space for it before calling set_attr
3550 		 */
3551 		set_attr_size = sizeof(struct kfd_ioctl_svm_attribute) *
3552 						(num_attrs + 1);
3553 		set_attr_new = krealloc(set_attr, set_attr_size,
3554 					    GFP_KERNEL);
3555 		if (!set_attr_new) {
3556 			ret = -ENOMEM;
3557 			goto exit;
3558 		}
3559 		set_attr = set_attr_new;
3560 
3561 		memcpy(set_attr, criu_svm_md->data.attrs, num_attrs *
3562 					sizeof(struct kfd_ioctl_svm_attribute));
3563 		set_attr[num_attrs].type = KFD_IOCTL_SVM_ATTR_CLR_FLAGS;
3564 		set_attr[num_attrs].value = ~set_flags;
3565 
3566 		ret = svm_range_set_attr(p, mm, criu_svm_md->data.start_addr,
3567 					 criu_svm_md->data.size, num_attrs + 1,
3568 					 set_attr);
3569 		if (ret) {
3570 			pr_err("CRIU: failed to set range attributes\n");
3571 			goto exit;
3572 		}
3573 
3574 		i++;
3575 	}
3576 exit:
3577 	kfree(set_attr);
3578 	list_for_each_entry_safe(criu_svm_md, next, &svms->criu_svm_metadata_list, list) {
3579 		pr_debug("freeing criu_svm_md[]\n\tstart: 0x%llx\n",
3580 						criu_svm_md->data.start_addr);
3581 		kfree(criu_svm_md);
3582 	}
3583 
3584 	mmput(mm);
3585 	return ret;
3586 
3587 }
3588 
3589 int kfd_criu_restore_svm(struct kfd_process *p,
3590 			 uint8_t __user *user_priv_ptr,
3591 			 uint64_t *priv_data_offset,
3592 			 uint64_t max_priv_data_size)
3593 {
3594 	uint64_t svm_priv_data_size, svm_object_md_size, svm_attrs_size;
3595 	int nattr_common = 4, nattr_accessibility = 1;
3596 	struct criu_svm_metadata *criu_svm_md = NULL;
3597 	struct svm_range_list *svms = &p->svms;
3598 	uint32_t num_devices;
3599 	int ret = 0;
3600 
3601 	num_devices = p->n_pdds;
3602 	/* Handle one SVM range object at a time, also the number of gpus are
3603 	 * assumed to be same on the restore node, checking must be done while
3604 	 * evaluating the topology earlier
3605 	 */
3606 
3607 	svm_attrs_size = sizeof(struct kfd_ioctl_svm_attribute) *
3608 		(nattr_common + nattr_accessibility * num_devices);
3609 	svm_object_md_size = sizeof(struct criu_svm_metadata) + svm_attrs_size;
3610 
3611 	svm_priv_data_size = sizeof(struct kfd_criu_svm_range_priv_data) +
3612 								svm_attrs_size;
3613 
3614 	criu_svm_md = kzalloc(svm_object_md_size, GFP_KERNEL);
3615 	if (!criu_svm_md) {
3616 		pr_err("failed to allocate memory to store svm metadata\n");
3617 		return -ENOMEM;
3618 	}
3619 	if (*priv_data_offset + svm_priv_data_size > max_priv_data_size) {
3620 		ret = -EINVAL;
3621 		goto exit;
3622 	}
3623 
3624 	ret = copy_from_user(&criu_svm_md->data, user_priv_ptr + *priv_data_offset,
3625 			     svm_priv_data_size);
3626 	if (ret) {
3627 		ret = -EFAULT;
3628 		goto exit;
3629 	}
3630 	*priv_data_offset += svm_priv_data_size;
3631 
3632 	list_add_tail(&criu_svm_md->list, &svms->criu_svm_metadata_list);
3633 
3634 	return 0;
3635 
3636 
3637 exit:
3638 	kfree(criu_svm_md);
3639 	return ret;
3640 }
3641 
3642 int svm_range_get_info(struct kfd_process *p, uint32_t *num_svm_ranges,
3643 		       uint64_t *svm_priv_data_size)
3644 {
3645 	uint64_t total_size, accessibility_size, common_attr_size;
3646 	int nattr_common = 4, nattr_accessibility = 1;
3647 	int num_devices = p->n_pdds;
3648 	struct svm_range_list *svms;
3649 	struct svm_range *prange;
3650 	uint32_t count = 0;
3651 
3652 	*svm_priv_data_size = 0;
3653 
3654 	svms = &p->svms;
3655 	if (!svms)
3656 		return -EINVAL;
3657 
3658 	mutex_lock(&svms->lock);
3659 	list_for_each_entry(prange, &svms->list, list) {
3660 		pr_debug("prange: 0x%p start: 0x%lx\t npages: 0x%llx\t end: 0x%llx\n",
3661 			 prange, prange->start, prange->npages,
3662 			 prange->start + prange->npages - 1);
3663 		count++;
3664 	}
3665 	mutex_unlock(&svms->lock);
3666 
3667 	*num_svm_ranges = count;
3668 	/* Only the accessbility attributes need to be queried for all the gpus
3669 	 * individually, remaining ones are spanned across the entire process
3670 	 * regardless of the various gpu nodes. Of the remaining attributes,
3671 	 * KFD_IOCTL_SVM_ATTR_CLR_FLAGS need not be saved.
3672 	 *
3673 	 * KFD_IOCTL_SVM_ATTR_PREFERRED_LOC
3674 	 * KFD_IOCTL_SVM_ATTR_PREFETCH_LOC
3675 	 * KFD_IOCTL_SVM_ATTR_SET_FLAGS
3676 	 * KFD_IOCTL_SVM_ATTR_GRANULARITY
3677 	 *
3678 	 * ** ACCESSBILITY ATTRIBUTES **
3679 	 * (Considered as one, type is altered during query, value is gpuid)
3680 	 * KFD_IOCTL_SVM_ATTR_ACCESS
3681 	 * KFD_IOCTL_SVM_ATTR_ACCESS_IN_PLACE
3682 	 * KFD_IOCTL_SVM_ATTR_NO_ACCESS
3683 	 */
3684 	if (*num_svm_ranges > 0) {
3685 		common_attr_size = sizeof(struct kfd_ioctl_svm_attribute) *
3686 			nattr_common;
3687 		accessibility_size = sizeof(struct kfd_ioctl_svm_attribute) *
3688 			nattr_accessibility * num_devices;
3689 
3690 		total_size = sizeof(struct kfd_criu_svm_range_priv_data) +
3691 			common_attr_size + accessibility_size;
3692 
3693 		*svm_priv_data_size = *num_svm_ranges * total_size;
3694 	}
3695 
3696 	pr_debug("num_svm_ranges %u total_priv_size %llu\n", *num_svm_ranges,
3697 		 *svm_priv_data_size);
3698 	return 0;
3699 }
3700 
3701 int kfd_criu_checkpoint_svm(struct kfd_process *p,
3702 			    uint8_t __user *user_priv_data,
3703 			    uint64_t *priv_data_offset)
3704 {
3705 	struct kfd_criu_svm_range_priv_data *svm_priv = NULL;
3706 	struct kfd_ioctl_svm_attribute *query_attr = NULL;
3707 	uint64_t svm_priv_data_size, query_attr_size = 0;
3708 	int index, nattr_common = 4, ret = 0;
3709 	struct svm_range_list *svms;
3710 	int num_devices = p->n_pdds;
3711 	struct svm_range *prange;
3712 	struct mm_struct *mm;
3713 
3714 	svms = &p->svms;
3715 	if (!svms)
3716 		return -EINVAL;
3717 
3718 	mm = get_task_mm(p->lead_thread);
3719 	if (!mm) {
3720 		pr_err("failed to get mm for the target process\n");
3721 		return -ESRCH;
3722 	}
3723 
3724 	query_attr_size = sizeof(struct kfd_ioctl_svm_attribute) *
3725 				(nattr_common + num_devices);
3726 
3727 	query_attr = kzalloc(query_attr_size, GFP_KERNEL);
3728 	if (!query_attr) {
3729 		ret = -ENOMEM;
3730 		goto exit;
3731 	}
3732 
3733 	query_attr[0].type = KFD_IOCTL_SVM_ATTR_PREFERRED_LOC;
3734 	query_attr[1].type = KFD_IOCTL_SVM_ATTR_PREFETCH_LOC;
3735 	query_attr[2].type = KFD_IOCTL_SVM_ATTR_SET_FLAGS;
3736 	query_attr[3].type = KFD_IOCTL_SVM_ATTR_GRANULARITY;
3737 
3738 	for (index = 0; index < num_devices; index++) {
3739 		struct kfd_process_device *pdd = p->pdds[index];
3740 
3741 		query_attr[index + nattr_common].type =
3742 			KFD_IOCTL_SVM_ATTR_ACCESS;
3743 		query_attr[index + nattr_common].value = pdd->user_gpu_id;
3744 	}
3745 
3746 	svm_priv_data_size = sizeof(*svm_priv) + query_attr_size;
3747 
3748 	svm_priv = kzalloc(svm_priv_data_size, GFP_KERNEL);
3749 	if (!svm_priv) {
3750 		ret = -ENOMEM;
3751 		goto exit_query;
3752 	}
3753 
3754 	index = 0;
3755 	list_for_each_entry(prange, &svms->list, list) {
3756 
3757 		svm_priv->object_type = KFD_CRIU_OBJECT_TYPE_SVM_RANGE;
3758 		svm_priv->start_addr = prange->start;
3759 		svm_priv->size = prange->npages;
3760 		memcpy(&svm_priv->attrs, query_attr, query_attr_size);
3761 		pr_debug("CRIU: prange: 0x%p start: 0x%lx\t npages: 0x%llx end: 0x%llx\t size: 0x%llx\n",
3762 			 prange, prange->start, prange->npages,
3763 			 prange->start + prange->npages - 1,
3764 			 prange->npages * PAGE_SIZE);
3765 
3766 		ret = svm_range_get_attr(p, mm, svm_priv->start_addr,
3767 					 svm_priv->size,
3768 					 (nattr_common + num_devices),
3769 					 svm_priv->attrs);
3770 		if (ret) {
3771 			pr_err("CRIU: failed to obtain range attributes\n");
3772 			goto exit_priv;
3773 		}
3774 
3775 		if (copy_to_user(user_priv_data + *priv_data_offset, svm_priv,
3776 				 svm_priv_data_size)) {
3777 			pr_err("Failed to copy svm priv to user\n");
3778 			ret = -EFAULT;
3779 			goto exit_priv;
3780 		}
3781 
3782 		*priv_data_offset += svm_priv_data_size;
3783 
3784 	}
3785 
3786 
3787 exit_priv:
3788 	kfree(svm_priv);
3789 exit_query:
3790 	kfree(query_attr);
3791 exit:
3792 	mmput(mm);
3793 	return ret;
3794 }
3795 
3796 int
3797 svm_ioctl(struct kfd_process *p, enum kfd_ioctl_svm_op op, uint64_t start,
3798 	  uint64_t size, uint32_t nattrs, struct kfd_ioctl_svm_attribute *attrs)
3799 {
3800 	struct mm_struct *mm = current->mm;
3801 	int r;
3802 
3803 	start >>= PAGE_SHIFT;
3804 	size >>= PAGE_SHIFT;
3805 
3806 	switch (op) {
3807 	case KFD_IOCTL_SVM_OP_SET_ATTR:
3808 		r = svm_range_set_attr(p, mm, start, size, nattrs, attrs);
3809 		break;
3810 	case KFD_IOCTL_SVM_OP_GET_ATTR:
3811 		r = svm_range_get_attr(p, mm, start, size, nattrs, attrs);
3812 		break;
3813 	default:
3814 		r = EINVAL;
3815 		break;
3816 	}
3817 
3818 	return r;
3819 }
3820