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