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 #include <linux/types.h>
24 #include <linux/hmm.h>
25 #include <linux/dma-direction.h>
26 #include <linux/dma-mapping.h>
27 #include <linux/migrate.h>
28 #include "amdgpu_sync.h"
29 #include "amdgpu_object.h"
30 #include "amdgpu_vm.h"
31 #include "amdgpu_mn.h"
32 #include "amdgpu_res_cursor.h"
33 #include "kfd_priv.h"
34 #include "kfd_svm.h"
35 #include "kfd_migrate.h"
36 
37 #ifdef dev_fmt
38 #undef dev_fmt
39 #endif
40 #define dev_fmt(fmt) "kfd_migrate: " fmt
41 
42 static uint64_t
43 svm_migrate_direct_mapping_addr(struct amdgpu_device *adev, uint64_t addr)
44 {
45 	return addr + amdgpu_ttm_domain_start(adev, TTM_PL_VRAM);
46 }
47 
48 static int
49 svm_migrate_gart_map(struct amdgpu_ring *ring, uint64_t npages,
50 		     dma_addr_t *addr, uint64_t *gart_addr, uint64_t flags)
51 {
52 	struct amdgpu_device *adev = ring->adev;
53 	struct amdgpu_job *job;
54 	unsigned int num_dw, num_bytes;
55 	struct dma_fence *fence;
56 	uint64_t src_addr, dst_addr;
57 	uint64_t pte_flags;
58 	void *cpu_addr;
59 	int r;
60 
61 	/* use gart window 0 */
62 	*gart_addr = adev->gmc.gart_start;
63 
64 	num_dw = ALIGN(adev->mman.buffer_funcs->copy_num_dw, 8);
65 	num_bytes = npages * 8;
66 
67 	r = amdgpu_job_alloc_with_ib(adev, num_dw * 4 + num_bytes,
68 				     AMDGPU_IB_POOL_DELAYED, &job);
69 	if (r)
70 		return r;
71 
72 	src_addr = num_dw * 4;
73 	src_addr += job->ibs[0].gpu_addr;
74 
75 	dst_addr = amdgpu_bo_gpu_offset(adev->gart.bo);
76 	amdgpu_emit_copy_buffer(adev, &job->ibs[0], src_addr,
77 				dst_addr, num_bytes, false);
78 
79 	amdgpu_ring_pad_ib(ring, &job->ibs[0]);
80 	WARN_ON(job->ibs[0].length_dw > num_dw);
81 
82 	pte_flags = AMDGPU_PTE_VALID | AMDGPU_PTE_READABLE;
83 	pte_flags |= AMDGPU_PTE_SYSTEM | AMDGPU_PTE_SNOOPED;
84 	if (!(flags & KFD_IOCTL_SVM_FLAG_GPU_RO))
85 		pte_flags |= AMDGPU_PTE_WRITEABLE;
86 	pte_flags |= adev->gart.gart_pte_flags;
87 
88 	cpu_addr = &job->ibs[0].ptr[num_dw];
89 
90 	amdgpu_gart_map(adev, 0, npages, addr, pte_flags, cpu_addr);
91 	r = amdgpu_job_submit(job, &adev->mman.entity,
92 			      AMDGPU_FENCE_OWNER_UNDEFINED, &fence);
93 	if (r)
94 		goto error_free;
95 
96 	dma_fence_put(fence);
97 
98 	return r;
99 
100 error_free:
101 	amdgpu_job_free(job);
102 	return r;
103 }
104 
105 /**
106  * svm_migrate_copy_memory_gart - sdma copy data between ram and vram
107  *
108  * @adev: amdgpu device the sdma ring running
109  * @sys: system DMA pointer to be copied
110  * @vram: vram destination DMA pointer
111  * @npages: number of pages to copy
112  * @direction: enum MIGRATION_COPY_DIR
113  * @mfence: output, sdma fence to signal after sdma is done
114  *
115  * ram address uses GART table continuous entries mapping to ram pages,
116  * vram address uses direct mapping of vram pages, which must have npages
117  * number of continuous pages.
118  * GART update and sdma uses same buf copy function ring, sdma is splited to
119  * multiple GTT_MAX_PAGES transfer, all sdma operations are serialized, wait for
120  * the last sdma finish fence which is returned to check copy memory is done.
121  *
122  * Context: Process context, takes and releases gtt_window_lock
123  *
124  * Return:
125  * 0 - OK, otherwise error code
126  */
127 
128 static int
129 svm_migrate_copy_memory_gart(struct amdgpu_device *adev, dma_addr_t *sys,
130 			     uint64_t *vram, uint64_t npages,
131 			     enum MIGRATION_COPY_DIR direction,
132 			     struct dma_fence **mfence)
133 {
134 	const uint64_t GTT_MAX_PAGES = AMDGPU_GTT_MAX_TRANSFER_SIZE;
135 	struct amdgpu_ring *ring = adev->mman.buffer_funcs_ring;
136 	uint64_t gart_s, gart_d;
137 	struct dma_fence *next;
138 	uint64_t size;
139 	int r;
140 
141 	mutex_lock(&adev->mman.gtt_window_lock);
142 
143 	while (npages) {
144 		size = min(GTT_MAX_PAGES, npages);
145 
146 		if (direction == FROM_VRAM_TO_RAM) {
147 			gart_s = svm_migrate_direct_mapping_addr(adev, *vram);
148 			r = svm_migrate_gart_map(ring, size, sys, &gart_d, 0);
149 
150 		} else if (direction == FROM_RAM_TO_VRAM) {
151 			r = svm_migrate_gart_map(ring, size, sys, &gart_s,
152 						 KFD_IOCTL_SVM_FLAG_GPU_RO);
153 			gart_d = svm_migrate_direct_mapping_addr(adev, *vram);
154 		}
155 		if (r) {
156 			dev_err(adev->dev, "fail %d create gart mapping\n", r);
157 			goto out_unlock;
158 		}
159 
160 		r = amdgpu_copy_buffer(ring, gart_s, gart_d, size * PAGE_SIZE,
161 				       NULL, &next, false, true, false);
162 		if (r) {
163 			dev_err(adev->dev, "fail %d to copy memory\n", r);
164 			goto out_unlock;
165 		}
166 
167 		dma_fence_put(*mfence);
168 		*mfence = next;
169 		npages -= size;
170 		if (npages) {
171 			sys += size;
172 			vram += size;
173 		}
174 	}
175 
176 out_unlock:
177 	mutex_unlock(&adev->mman.gtt_window_lock);
178 
179 	return r;
180 }
181 
182 /**
183  * svm_migrate_copy_done - wait for memory copy sdma is done
184  *
185  * @adev: amdgpu device the sdma memory copy is executing on
186  * @mfence: migrate fence
187  *
188  * Wait for dma fence is signaled, if the copy ssplit into multiple sdma
189  * operations, this is the last sdma operation fence.
190  *
191  * Context: called after svm_migrate_copy_memory
192  *
193  * Return:
194  * 0		- success
195  * otherwise	- error code from dma fence signal
196  */
197 static int
198 svm_migrate_copy_done(struct amdgpu_device *adev, struct dma_fence *mfence)
199 {
200 	int r = 0;
201 
202 	if (mfence) {
203 		r = dma_fence_wait(mfence, false);
204 		dma_fence_put(mfence);
205 		pr_debug("sdma copy memory fence done\n");
206 	}
207 
208 	return r;
209 }
210 
211 unsigned long
212 svm_migrate_addr_to_pfn(struct amdgpu_device *adev, unsigned long addr)
213 {
214 	return (addr + adev->kfd.dev->pgmap.range.start) >> PAGE_SHIFT;
215 }
216 
217 static void
218 svm_migrate_get_vram_page(struct svm_range *prange, unsigned long pfn)
219 {
220 	struct page *page;
221 
222 	page = pfn_to_page(pfn);
223 	svm_range_bo_ref(prange->svm_bo);
224 	page->zone_device_data = prange->svm_bo;
225 	lock_page(page);
226 }
227 
228 static void
229 svm_migrate_put_vram_page(struct amdgpu_device *adev, unsigned long addr)
230 {
231 	struct page *page;
232 
233 	page = pfn_to_page(svm_migrate_addr_to_pfn(adev, addr));
234 	unlock_page(page);
235 	put_page(page);
236 }
237 
238 static unsigned long
239 svm_migrate_addr(struct amdgpu_device *adev, struct page *page)
240 {
241 	unsigned long addr;
242 
243 	addr = page_to_pfn(page) << PAGE_SHIFT;
244 	return (addr - adev->kfd.dev->pgmap.range.start);
245 }
246 
247 static struct page *
248 svm_migrate_get_sys_page(struct vm_area_struct *vma, unsigned long addr)
249 {
250 	struct page *page;
251 
252 	page = alloc_page_vma(GFP_HIGHUSER, vma, addr);
253 	if (page)
254 		lock_page(page);
255 
256 	return page;
257 }
258 
259 static void svm_migrate_put_sys_page(unsigned long addr)
260 {
261 	struct page *page;
262 
263 	page = pfn_to_page(addr >> PAGE_SHIFT);
264 	unlock_page(page);
265 	put_page(page);
266 }
267 
268 static unsigned long svm_migrate_successful_pages(struct migrate_vma *migrate)
269 {
270 	unsigned long cpages = 0;
271 	unsigned long i;
272 
273 	for (i = 0; i < migrate->npages; i++) {
274 		if (migrate->src[i] & MIGRATE_PFN_VALID &&
275 		    migrate->src[i] & MIGRATE_PFN_MIGRATE)
276 			cpages++;
277 	}
278 	return cpages;
279 }
280 
281 static unsigned long svm_migrate_unsuccessful_pages(struct migrate_vma *migrate)
282 {
283 	unsigned long upages = 0;
284 	unsigned long i;
285 
286 	for (i = 0; i < migrate->npages; i++) {
287 		if (migrate->src[i] & MIGRATE_PFN_VALID &&
288 		    !(migrate->src[i] & MIGRATE_PFN_MIGRATE))
289 			upages++;
290 	}
291 	return upages;
292 }
293 
294 static int
295 svm_migrate_copy_to_vram(struct amdgpu_device *adev, struct svm_range *prange,
296 			 struct migrate_vma *migrate, struct dma_fence **mfence,
297 			 dma_addr_t *scratch)
298 {
299 	uint64_t npages = migrate->cpages;
300 	struct device *dev = adev->dev;
301 	struct amdgpu_res_cursor cursor;
302 	dma_addr_t *src;
303 	uint64_t *dst;
304 	uint64_t i, j;
305 	int r;
306 
307 	pr_debug("svms 0x%p [0x%lx 0x%lx]\n", prange->svms, prange->start,
308 		 prange->last);
309 
310 	src = scratch;
311 	dst = (uint64_t *)(scratch + npages);
312 
313 	r = svm_range_vram_node_new(adev, prange, true);
314 	if (r) {
315 		dev_dbg(adev->dev, "fail %d to alloc vram\n", r);
316 		goto out;
317 	}
318 
319 	amdgpu_res_first(prange->ttm_res, prange->offset << PAGE_SHIFT,
320 			 npages << PAGE_SHIFT, &cursor);
321 	for (i = j = 0; i < npages; i++) {
322 		struct page *spage;
323 
324 		spage = migrate_pfn_to_page(migrate->src[i]);
325 		if (spage && !is_zone_device_page(spage)) {
326 			dst[i] = cursor.start + (j << PAGE_SHIFT);
327 			migrate->dst[i] = svm_migrate_addr_to_pfn(adev, dst[i]);
328 			svm_migrate_get_vram_page(prange, migrate->dst[i]);
329 			migrate->dst[i] = migrate_pfn(migrate->dst[i]);
330 			src[i] = dma_map_page(dev, spage, 0, PAGE_SIZE,
331 					      DMA_TO_DEVICE);
332 			r = dma_mapping_error(dev, src[i]);
333 			if (r) {
334 				dev_err(adev->dev, "%s: fail %d dma_map_page\n",
335 					__func__, r);
336 				goto out_free_vram_pages;
337 			}
338 		} else {
339 			if (j) {
340 				r = svm_migrate_copy_memory_gart(
341 						adev, src + i - j,
342 						dst + i - j, j,
343 						FROM_RAM_TO_VRAM,
344 						mfence);
345 				if (r)
346 					goto out_free_vram_pages;
347 				amdgpu_res_next(&cursor, j << PAGE_SHIFT);
348 				j = 0;
349 			} else {
350 				amdgpu_res_next(&cursor, PAGE_SIZE);
351 			}
352 			continue;
353 		}
354 
355 		pr_debug_ratelimited("dma mapping src to 0x%llx, pfn 0x%lx\n",
356 				     src[i] >> PAGE_SHIFT, page_to_pfn(spage));
357 
358 		if (j >= (cursor.size >> PAGE_SHIFT) - 1 && i < npages - 1) {
359 			r = svm_migrate_copy_memory_gart(adev, src + i - j,
360 							 dst + i - j, j + 1,
361 							 FROM_RAM_TO_VRAM,
362 							 mfence);
363 			if (r)
364 				goto out_free_vram_pages;
365 			amdgpu_res_next(&cursor, (j + 1) * PAGE_SIZE);
366 			j = 0;
367 		} else {
368 			j++;
369 		}
370 	}
371 
372 	r = svm_migrate_copy_memory_gart(adev, src + i - j, dst + i - j, j,
373 					 FROM_RAM_TO_VRAM, mfence);
374 
375 out_free_vram_pages:
376 	if (r) {
377 		pr_debug("failed %d to copy memory to vram\n", r);
378 		while (i--) {
379 			svm_migrate_put_vram_page(adev, dst[i]);
380 			migrate->dst[i] = 0;
381 		}
382 	}
383 
384 #ifdef DEBUG_FORCE_MIXED_DOMAINS
385 	for (i = 0, j = 0; i < npages; i += 4, j++) {
386 		if (j & 1)
387 			continue;
388 		svm_migrate_put_vram_page(adev, dst[i]);
389 		migrate->dst[i] = 0;
390 		svm_migrate_put_vram_page(adev, dst[i + 1]);
391 		migrate->dst[i + 1] = 0;
392 		svm_migrate_put_vram_page(adev, dst[i + 2]);
393 		migrate->dst[i + 2] = 0;
394 		svm_migrate_put_vram_page(adev, dst[i + 3]);
395 		migrate->dst[i + 3] = 0;
396 	}
397 #endif
398 out:
399 	return r;
400 }
401 
402 static long
403 svm_migrate_vma_to_vram(struct amdgpu_device *adev, struct svm_range *prange,
404 			struct vm_area_struct *vma, uint64_t start,
405 			uint64_t end)
406 {
407 	uint64_t npages = (end - start) >> PAGE_SHIFT;
408 	struct kfd_process_device *pdd;
409 	struct dma_fence *mfence = NULL;
410 	struct migrate_vma migrate;
411 	unsigned long cpages = 0;
412 	dma_addr_t *scratch;
413 	size_t size;
414 	void *buf;
415 	int r = -ENOMEM;
416 
417 	memset(&migrate, 0, sizeof(migrate));
418 	migrate.vma = vma;
419 	migrate.start = start;
420 	migrate.end = end;
421 	migrate.flags = MIGRATE_VMA_SELECT_SYSTEM;
422 	migrate.pgmap_owner = SVM_ADEV_PGMAP_OWNER(adev);
423 
424 	size = 2 * sizeof(*migrate.src) + sizeof(uint64_t) + sizeof(dma_addr_t);
425 	size *= npages;
426 	buf = kvmalloc(size, GFP_KERNEL | __GFP_ZERO);
427 	if (!buf)
428 		goto out;
429 
430 	migrate.src = buf;
431 	migrate.dst = migrate.src + npages;
432 	scratch = (dma_addr_t *)(migrate.dst + npages);
433 
434 	r = migrate_vma_setup(&migrate);
435 	if (r) {
436 		dev_err(adev->dev, "%s: vma setup fail %d range [0x%lx 0x%lx]\n",
437 			__func__, r, prange->start, prange->last);
438 		goto out_free;
439 	}
440 
441 	cpages = migrate.cpages;
442 	if (!cpages) {
443 		pr_debug("failed collect migrate sys pages [0x%lx 0x%lx]\n",
444 			 prange->start, prange->last);
445 		goto out_free;
446 	}
447 	if (cpages != npages)
448 		pr_debug("partial migration, 0x%lx/0x%llx pages migrated\n",
449 			 cpages, npages);
450 	else
451 		pr_debug("0x%lx pages migrated\n", cpages);
452 
453 	r = svm_migrate_copy_to_vram(adev, prange, &migrate, &mfence, scratch);
454 	migrate_vma_pages(&migrate);
455 
456 	pr_debug("successful/cpages/npages 0x%lx/0x%lx/0x%lx\n",
457 		svm_migrate_successful_pages(&migrate), cpages, migrate.npages);
458 
459 	svm_migrate_copy_done(adev, mfence);
460 	migrate_vma_finalize(&migrate);
461 
462 	svm_range_dma_unmap(adev->dev, scratch, 0, npages);
463 	svm_range_free_dma_mappings(prange);
464 
465 out_free:
466 	kvfree(buf);
467 out:
468 	if (!r && cpages) {
469 		pdd = svm_range_get_pdd_by_adev(prange, adev);
470 		if (pdd)
471 			WRITE_ONCE(pdd->page_in, pdd->page_in + cpages);
472 
473 		return cpages;
474 	}
475 	return r;
476 }
477 
478 /**
479  * svm_migrate_ram_to_vram - migrate svm range from system to device
480  * @prange: range structure
481  * @best_loc: the device to migrate to
482  * @mm: the process mm structure
483  *
484  * Context: Process context, caller hold mmap read lock, svms lock, prange lock
485  *
486  * Return:
487  * 0 - OK, otherwise error code
488  */
489 static int
490 svm_migrate_ram_to_vram(struct svm_range *prange, uint32_t best_loc,
491 			struct mm_struct *mm)
492 {
493 	unsigned long addr, start, end;
494 	struct vm_area_struct *vma;
495 	struct amdgpu_device *adev;
496 	unsigned long cpages = 0;
497 	long r = 0;
498 
499 	if (prange->actual_loc == best_loc) {
500 		pr_debug("svms 0x%p [0x%lx 0x%lx] already on best_loc 0x%x\n",
501 			 prange->svms, prange->start, prange->last, best_loc);
502 		return 0;
503 	}
504 
505 	adev = svm_range_get_adev_by_id(prange, best_loc);
506 	if (!adev) {
507 		pr_debug("failed to get device by id 0x%x\n", best_loc);
508 		return -ENODEV;
509 	}
510 
511 	pr_debug("svms 0x%p [0x%lx 0x%lx] to gpu 0x%x\n", prange->svms,
512 		 prange->start, prange->last, best_loc);
513 
514 	/* FIXME: workaround for page locking bug with invalid pages */
515 	svm_range_prefault(prange, mm, SVM_ADEV_PGMAP_OWNER(adev));
516 
517 	start = prange->start << PAGE_SHIFT;
518 	end = (prange->last + 1) << PAGE_SHIFT;
519 
520 	for (addr = start; addr < end;) {
521 		unsigned long next;
522 
523 		vma = find_vma(mm, addr);
524 		if (!vma || addr < vma->vm_start)
525 			break;
526 
527 		next = min(vma->vm_end, end);
528 		r = svm_migrate_vma_to_vram(adev, prange, vma, addr, next);
529 		if (r < 0) {
530 			pr_debug("failed %ld to migrate\n", r);
531 			break;
532 		} else {
533 			cpages += r;
534 		}
535 		addr = next;
536 	}
537 
538 	if (cpages)
539 		prange->actual_loc = best_loc;
540 
541 	return r < 0 ? r : 0;
542 }
543 
544 static void svm_migrate_page_free(struct page *page)
545 {
546 	struct svm_range_bo *svm_bo = page->zone_device_data;
547 
548 	if (svm_bo) {
549 		pr_debug_ratelimited("ref: %d\n", kref_read(&svm_bo->kref));
550 		svm_range_bo_unref_async(svm_bo);
551 	}
552 }
553 
554 static int
555 svm_migrate_copy_to_ram(struct amdgpu_device *adev, struct svm_range *prange,
556 			struct migrate_vma *migrate, struct dma_fence **mfence,
557 			dma_addr_t *scratch, uint64_t npages)
558 {
559 	struct device *dev = adev->dev;
560 	uint64_t *src;
561 	dma_addr_t *dst;
562 	struct page *dpage;
563 	uint64_t i = 0, j;
564 	uint64_t addr;
565 	int r = 0;
566 
567 	pr_debug("svms 0x%p [0x%lx 0x%lx]\n", prange->svms, prange->start,
568 		 prange->last);
569 
570 	addr = prange->start << PAGE_SHIFT;
571 
572 	src = (uint64_t *)(scratch + npages);
573 	dst = scratch;
574 
575 	for (i = 0, j = 0; i < npages; i++, addr += PAGE_SIZE) {
576 		struct page *spage;
577 
578 		spage = migrate_pfn_to_page(migrate->src[i]);
579 		if (!spage || !is_zone_device_page(spage)) {
580 			pr_debug("invalid page. Could be in CPU already svms 0x%p [0x%lx 0x%lx]\n",
581 				 prange->svms, prange->start, prange->last);
582 			if (j) {
583 				r = svm_migrate_copy_memory_gart(adev, dst + i - j,
584 								 src + i - j, j,
585 								 FROM_VRAM_TO_RAM,
586 								 mfence);
587 				if (r)
588 					goto out_oom;
589 				j = 0;
590 			}
591 			continue;
592 		}
593 		src[i] = svm_migrate_addr(adev, spage);
594 		if (i > 0 && src[i] != src[i - 1] + PAGE_SIZE) {
595 			r = svm_migrate_copy_memory_gart(adev, dst + i - j,
596 							 src + i - j, j,
597 							 FROM_VRAM_TO_RAM,
598 							 mfence);
599 			if (r)
600 				goto out_oom;
601 			j = 0;
602 		}
603 
604 		dpage = svm_migrate_get_sys_page(migrate->vma, addr);
605 		if (!dpage) {
606 			pr_debug("failed get page svms 0x%p [0x%lx 0x%lx]\n",
607 				 prange->svms, prange->start, prange->last);
608 			r = -ENOMEM;
609 			goto out_oom;
610 		}
611 
612 		dst[i] = dma_map_page(dev, dpage, 0, PAGE_SIZE, DMA_FROM_DEVICE);
613 		r = dma_mapping_error(dev, dst[i]);
614 		if (r) {
615 			dev_err(adev->dev, "%s: fail %d dma_map_page\n", __func__, r);
616 			goto out_oom;
617 		}
618 
619 		pr_debug_ratelimited("dma mapping dst to 0x%llx, pfn 0x%lx\n",
620 				     dst[i] >> PAGE_SHIFT, page_to_pfn(dpage));
621 
622 		migrate->dst[i] = migrate_pfn(page_to_pfn(dpage));
623 		j++;
624 	}
625 
626 	r = svm_migrate_copy_memory_gart(adev, dst + i - j, src + i - j, j,
627 					 FROM_VRAM_TO_RAM, mfence);
628 
629 out_oom:
630 	if (r) {
631 		pr_debug("failed %d copy to ram\n", r);
632 		while (i--) {
633 			svm_migrate_put_sys_page(dst[i]);
634 			migrate->dst[i] = 0;
635 		}
636 	}
637 
638 	return r;
639 }
640 
641 /**
642  * svm_migrate_vma_to_ram - migrate range inside one vma from device to system
643  *
644  * @adev: amdgpu device to migrate from
645  * @prange: svm range structure
646  * @vma: vm_area_struct that range [start, end] belongs to
647  * @start: range start virtual address in pages
648  * @end: range end virtual address in pages
649  *
650  * Context: Process context, caller hold mmap read lock, prange->migrate_mutex
651  *
652  * Return:
653  *   0 - success with all pages migrated
654  *   negative values - indicate error
655  *   positive values - partial migration, number of pages not migrated
656  */
657 static long
658 svm_migrate_vma_to_ram(struct amdgpu_device *adev, struct svm_range *prange,
659 		       struct vm_area_struct *vma, uint64_t start, uint64_t end)
660 {
661 	uint64_t npages = (end - start) >> PAGE_SHIFT;
662 	unsigned long upages = npages;
663 	unsigned long cpages = 0;
664 	struct kfd_process_device *pdd;
665 	struct dma_fence *mfence = NULL;
666 	struct migrate_vma migrate;
667 	dma_addr_t *scratch;
668 	size_t size;
669 	void *buf;
670 	int r = -ENOMEM;
671 
672 	memset(&migrate, 0, sizeof(migrate));
673 	migrate.vma = vma;
674 	migrate.start = start;
675 	migrate.end = end;
676 	migrate.flags = MIGRATE_VMA_SELECT_DEVICE_PRIVATE;
677 	migrate.pgmap_owner = SVM_ADEV_PGMAP_OWNER(adev);
678 
679 	size = 2 * sizeof(*migrate.src) + sizeof(uint64_t) + sizeof(dma_addr_t);
680 	size *= npages;
681 	buf = kvmalloc(size, GFP_KERNEL | __GFP_ZERO);
682 	if (!buf)
683 		goto out;
684 
685 	migrate.src = buf;
686 	migrate.dst = migrate.src + npages;
687 	scratch = (dma_addr_t *)(migrate.dst + npages);
688 
689 	r = migrate_vma_setup(&migrate);
690 	if (r) {
691 		dev_err(adev->dev, "%s: vma setup fail %d range [0x%lx 0x%lx]\n",
692 			__func__, r, prange->start, prange->last);
693 		goto out_free;
694 	}
695 
696 	cpages = migrate.cpages;
697 	if (!cpages) {
698 		pr_debug("failed collect migrate device pages [0x%lx 0x%lx]\n",
699 			 prange->start, prange->last);
700 		upages = svm_migrate_unsuccessful_pages(&migrate);
701 		goto out_free;
702 	}
703 	if (cpages != npages)
704 		pr_debug("partial migration, 0x%lx/0x%llx pages migrated\n",
705 			 cpages, npages);
706 	else
707 		pr_debug("0x%lx pages migrated\n", cpages);
708 
709 	r = svm_migrate_copy_to_ram(adev, prange, &migrate, &mfence,
710 				    scratch, npages);
711 	migrate_vma_pages(&migrate);
712 
713 	upages = svm_migrate_unsuccessful_pages(&migrate);
714 	pr_debug("unsuccessful/cpages/npages 0x%lx/0x%lx/0x%lx\n",
715 		 upages, cpages, migrate.npages);
716 
717 	svm_migrate_copy_done(adev, mfence);
718 	migrate_vma_finalize(&migrate);
719 	svm_range_dma_unmap(adev->dev, scratch, 0, npages);
720 
721 out_free:
722 	kvfree(buf);
723 out:
724 	if (!r && cpages) {
725 		pdd = svm_range_get_pdd_by_adev(prange, adev);
726 		if (pdd)
727 			WRITE_ONCE(pdd->page_out, pdd->page_out + cpages);
728 	}
729 	return r ? r : upages;
730 }
731 
732 /**
733  * svm_migrate_vram_to_ram - migrate svm range from device to system
734  * @prange: range structure
735  * @mm: process mm, use current->mm if NULL
736  *
737  * Context: Process context, caller hold mmap read lock, prange->migrate_mutex
738  *
739  * Return:
740  * 0 - OK, otherwise error code
741  */
742 int svm_migrate_vram_to_ram(struct svm_range *prange, struct mm_struct *mm)
743 {
744 	struct amdgpu_device *adev;
745 	struct vm_area_struct *vma;
746 	unsigned long addr;
747 	unsigned long start;
748 	unsigned long end;
749 	unsigned long upages = 0;
750 	long r = 0;
751 
752 	if (!prange->actual_loc) {
753 		pr_debug("[0x%lx 0x%lx] already migrated to ram\n",
754 			 prange->start, prange->last);
755 		return 0;
756 	}
757 
758 	adev = svm_range_get_adev_by_id(prange, prange->actual_loc);
759 	if (!adev) {
760 		pr_debug("failed to get device by id 0x%x\n",
761 			 prange->actual_loc);
762 		return -ENODEV;
763 	}
764 
765 	pr_debug("svms 0x%p prange 0x%p [0x%lx 0x%lx] from gpu 0x%x to ram\n",
766 		 prange->svms, prange, prange->start, prange->last,
767 		 prange->actual_loc);
768 
769 	start = prange->start << PAGE_SHIFT;
770 	end = (prange->last + 1) << PAGE_SHIFT;
771 
772 	for (addr = start; addr < end;) {
773 		unsigned long next;
774 
775 		vma = find_vma(mm, addr);
776 		if (!vma || addr < vma->vm_start) {
777 			pr_debug("failed to find vma for prange %p\n", prange);
778 			r = -EFAULT;
779 			break;
780 		}
781 
782 		next = min(vma->vm_end, end);
783 		r = svm_migrate_vma_to_ram(adev, prange, vma, addr, next);
784 		if (r < 0) {
785 			pr_debug("failed %ld to migrate prange %p\n", r, prange);
786 			break;
787 		} else {
788 			upages += r;
789 		}
790 		addr = next;
791 	}
792 
793 	if (r >= 0 && !upages) {
794 		svm_range_vram_node_free(prange);
795 		prange->actual_loc = 0;
796 	}
797 
798 	return r < 0 ? r : 0;
799 }
800 
801 /**
802  * svm_migrate_vram_to_vram - migrate svm range from device to device
803  * @prange: range structure
804  * @best_loc: the device to migrate to
805  * @mm: process mm, use current->mm if NULL
806  *
807  * Context: Process context, caller hold mmap read lock, svms lock, prange lock
808  *
809  * Return:
810  * 0 - OK, otherwise error code
811  */
812 static int
813 svm_migrate_vram_to_vram(struct svm_range *prange, uint32_t best_loc,
814 			 struct mm_struct *mm)
815 {
816 	int r, retries = 3;
817 
818 	/*
819 	 * TODO: for both devices with PCIe large bar or on same xgmi hive, skip
820 	 * system memory as migration bridge
821 	 */
822 
823 	pr_debug("from gpu 0x%x to gpu 0x%x\n", prange->actual_loc, best_loc);
824 
825 	do {
826 		r = svm_migrate_vram_to_ram(prange, mm);
827 		if (r)
828 			return r;
829 	} while (prange->actual_loc && --retries);
830 
831 	if (prange->actual_loc)
832 		return -EDEADLK;
833 
834 	return svm_migrate_ram_to_vram(prange, best_loc, mm);
835 }
836 
837 int
838 svm_migrate_to_vram(struct svm_range *prange, uint32_t best_loc,
839 		    struct mm_struct *mm)
840 {
841 	if  (!prange->actual_loc)
842 		return svm_migrate_ram_to_vram(prange, best_loc, mm);
843 	else
844 		return svm_migrate_vram_to_vram(prange, best_loc, mm);
845 
846 }
847 
848 /**
849  * svm_migrate_to_ram - CPU page fault handler
850  * @vmf: CPU vm fault vma, address
851  *
852  * Context: vm fault handler, caller holds the mmap read lock
853  *
854  * Return:
855  * 0 - OK
856  * VM_FAULT_SIGBUS - notice application to have SIGBUS page fault
857  */
858 static vm_fault_t svm_migrate_to_ram(struct vm_fault *vmf)
859 {
860 	unsigned long addr = vmf->address;
861 	struct vm_area_struct *vma;
862 	enum svm_work_list_ops op;
863 	struct svm_range *parent;
864 	struct svm_range *prange;
865 	struct kfd_process *p;
866 	struct mm_struct *mm;
867 	int r = 0;
868 
869 	vma = vmf->vma;
870 	mm = vma->vm_mm;
871 
872 	p = kfd_lookup_process_by_mm(vma->vm_mm);
873 	if (!p) {
874 		pr_debug("failed find process at fault address 0x%lx\n", addr);
875 		return VM_FAULT_SIGBUS;
876 	}
877 	if (READ_ONCE(p->svms.faulting_task) == current) {
878 		pr_debug("skipping ram migration\n");
879 		kfd_unref_process(p);
880 		return 0;
881 	}
882 	addr >>= PAGE_SHIFT;
883 	pr_debug("CPU page fault svms 0x%p address 0x%lx\n", &p->svms, addr);
884 
885 	mutex_lock(&p->svms.lock);
886 
887 	prange = svm_range_from_addr(&p->svms, addr, &parent);
888 	if (!prange) {
889 		pr_debug("cannot find svm range at 0x%lx\n", addr);
890 		r = -EFAULT;
891 		goto out;
892 	}
893 
894 	mutex_lock(&parent->migrate_mutex);
895 	if (prange != parent)
896 		mutex_lock_nested(&prange->migrate_mutex, 1);
897 
898 	if (!prange->actual_loc)
899 		goto out_unlock_prange;
900 
901 	svm_range_lock(parent);
902 	if (prange != parent)
903 		mutex_lock_nested(&prange->lock, 1);
904 	r = svm_range_split_by_granularity(p, mm, addr, parent, prange);
905 	if (prange != parent)
906 		mutex_unlock(&prange->lock);
907 	svm_range_unlock(parent);
908 	if (r) {
909 		pr_debug("failed %d to split range by granularity\n", r);
910 		goto out_unlock_prange;
911 	}
912 
913 	r = svm_migrate_vram_to_ram(prange, mm);
914 	if (r)
915 		pr_debug("failed %d migrate 0x%p [0x%lx 0x%lx] to ram\n", r,
916 			 prange, prange->start, prange->last);
917 
918 	/* xnack on, update mapping on GPUs with ACCESS_IN_PLACE */
919 	if (p->xnack_enabled && parent == prange)
920 		op = SVM_OP_UPDATE_RANGE_NOTIFIER_AND_MAP;
921 	else
922 		op = SVM_OP_UPDATE_RANGE_NOTIFIER;
923 	svm_range_add_list_work(&p->svms, parent, mm, op);
924 	schedule_deferred_list_work(&p->svms);
925 
926 out_unlock_prange:
927 	if (prange != parent)
928 		mutex_unlock(&prange->migrate_mutex);
929 	mutex_unlock(&parent->migrate_mutex);
930 out:
931 	mutex_unlock(&p->svms.lock);
932 	kfd_unref_process(p);
933 
934 	pr_debug("CPU fault svms 0x%p address 0x%lx done\n", &p->svms, addr);
935 
936 	return r ? VM_FAULT_SIGBUS : 0;
937 }
938 
939 static const struct dev_pagemap_ops svm_migrate_pgmap_ops = {
940 	.page_free		= svm_migrate_page_free,
941 	.migrate_to_ram		= svm_migrate_to_ram,
942 };
943 
944 /* Each VRAM page uses sizeof(struct page) on system memory */
945 #define SVM_HMM_PAGE_STRUCT_SIZE(size) ((size)/PAGE_SIZE * sizeof(struct page))
946 
947 int svm_migrate_init(struct amdgpu_device *adev)
948 {
949 	struct kfd_dev *kfddev = adev->kfd.dev;
950 	struct dev_pagemap *pgmap;
951 	struct resource *res;
952 	unsigned long size;
953 	void *r;
954 
955 	/* Page migration works on Vega10 or newer */
956 	if (!KFD_IS_SOC15(kfddev))
957 		return -EINVAL;
958 
959 	pgmap = &kfddev->pgmap;
960 	memset(pgmap, 0, sizeof(*pgmap));
961 
962 	/* TODO: register all vram to HMM for now.
963 	 * should remove reserved size
964 	 */
965 	size = ALIGN(adev->gmc.real_vram_size, 2ULL << 20);
966 	res = devm_request_free_mem_region(adev->dev, &iomem_resource, size);
967 	if (IS_ERR(res))
968 		return -ENOMEM;
969 
970 	pgmap->type = MEMORY_DEVICE_PRIVATE;
971 	pgmap->nr_range = 1;
972 	pgmap->range.start = res->start;
973 	pgmap->range.end = res->end;
974 	pgmap->ops = &svm_migrate_pgmap_ops;
975 	pgmap->owner = SVM_ADEV_PGMAP_OWNER(adev);
976 	pgmap->flags = MIGRATE_VMA_SELECT_DEVICE_PRIVATE;
977 
978 	/* Device manager releases device-specific resources, memory region and
979 	 * pgmap when driver disconnects from device.
980 	 */
981 	r = devm_memremap_pages(adev->dev, pgmap);
982 	if (IS_ERR(r)) {
983 		pr_err("failed to register HMM device memory\n");
984 
985 		/* Disable SVM support capability */
986 		pgmap->type = 0;
987 		devm_release_mem_region(adev->dev, res->start, resource_size(res));
988 		return PTR_ERR(r);
989 	}
990 
991 	pr_debug("reserve %ldMB system memory for VRAM pages struct\n",
992 		 SVM_HMM_PAGE_STRUCT_SIZE(size) >> 20);
993 
994 	amdgpu_amdkfd_reserve_system_mem(SVM_HMM_PAGE_STRUCT_SIZE(size));
995 
996 	pr_info("HMM registered %ldMB device memory\n", size >> 20);
997 
998 	return 0;
999 }
1000