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