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