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