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