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