xref: /linux/drivers/gpu/drm/xe/xe_migrate.c (revision 42d3b66d4cdbacfc9d120d2301b8de89cc29a914)
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2020 Intel Corporation
4  */
5 
6 #include "xe_migrate.h"
7 
8 #include <linux/bitfield.h>
9 #include <linux/sizes.h>
10 
11 #include <drm/drm_managed.h>
12 #include <drm/drm_pagemap.h>
13 #include <drm/ttm/ttm_tt.h>
14 #include <uapi/drm/xe_drm.h>
15 
16 #include <generated/xe_wa_oob.h>
17 
18 #include "instructions/xe_gpu_commands.h"
19 #include "instructions/xe_mi_commands.h"
20 #include "regs/xe_gtt_defs.h"
21 #include "tests/xe_test.h"
22 #include "xe_assert.h"
23 #include "xe_bb.h"
24 #include "xe_bo.h"
25 #include "xe_exec_queue.h"
26 #include "xe_ggtt.h"
27 #include "xe_gt.h"
28 #include "xe_gt_printk.h"
29 #include "xe_hw_engine.h"
30 #include "xe_lrc.h"
31 #include "xe_map.h"
32 #include "xe_mocs.h"
33 #include "xe_printk.h"
34 #include "xe_pt.h"
35 #include "xe_res_cursor.h"
36 #include "xe_sa.h"
37 #include "xe_sched_job.h"
38 #include "xe_sriov_vf_ccs.h"
39 #include "xe_svm.h"
40 #include "xe_sync.h"
41 #include "xe_trace_bo.h"
42 #include "xe_validation.h"
43 #include "xe_vm.h"
44 #include "xe_vram.h"
45 
46 /**
47  * struct xe_migrate - migrate context.
48  */
49 struct xe_migrate {
50 	/** @q: Default exec queue used for migration */
51 	struct xe_exec_queue *q;
52 	/** @tile: Backpointer to the tile this struct xe_migrate belongs to. */
53 	struct xe_tile *tile;
54 	/** @job_mutex: Timeline mutex for @eng. */
55 	struct mutex job_mutex;
56 	/** @pt_bo: Page-table buffer object. */
57 	struct xe_bo *pt_bo;
58 	/** @batch_base_ofs: VM offset of the migration batch buffer */
59 	u64 batch_base_ofs;
60 	/** @usm_batch_base_ofs: VM offset of the usm batch buffer */
61 	u64 usm_batch_base_ofs;
62 	/** @cleared_mem_ofs: VM offset of @cleared_bo. */
63 	u64 cleared_mem_ofs;
64 	/** @large_page_copy_ofs: VM offset of 2M pages used for large copies */
65 	u64 large_page_copy_ofs;
66 	/**
67 	 * @large_page_copy_pdes: BO offset to writeout 2M pages (PDEs) used for
68 	 * large copies
69 	 */
70 	u64 large_page_copy_pdes;
71 	/**
72 	 * @fence: dma-fence representing the last migration job batch.
73 	 * Protected by @job_mutex.
74 	 */
75 	struct dma_fence *fence;
76 	/**
77 	 * @vm_update_sa: For integrated, used to suballocate page-tables
78 	 * out of the pt_bo.
79 	 */
80 	struct drm_suballoc_manager vm_update_sa;
81 	/** @min_chunk_size: For dgfx, Minimum chunk size */
82 	u64 min_chunk_size;
83 };
84 
85 #define MAX_PREEMPTDISABLE_TRANSFER SZ_8M /* Around 1ms. */
86 #define MAX_CCS_LIMITED_TRANSFER SZ_4M /* XE_PAGE_SIZE * (FIELD_MAX(XE2_CCS_SIZE_MASK) + 1) */
87 #define NUM_KERNEL_PDE 15
88 #define NUM_PT_SLOTS 32
89 #define LEVEL0_PAGE_TABLE_ENCODE_SIZE SZ_2M
90 #define MAX_NUM_PTE 512
91 #define IDENTITY_OFFSET 256ULL
92 
93 /*
94  * Although MI_STORE_DATA_IMM's "length" field is 10-bits, 0x3FE is the largest
95  * legal value accepted.  Since that instruction field is always stored in
96  * (val-2) format, this translates to 0x400 dwords for the true maximum length
97  * of the instruction.  Subtracting the instruction header (1 dword) and
98  * address (2 dwords), that leaves 0x3FD dwords (0x1FE qwords) for PTE values.
99  */
100 #define MAX_PTE_PER_SDI 0x1FEU
101 
102 static void xe_migrate_fini(void *arg)
103 {
104 	struct xe_migrate *m = arg;
105 
106 	xe_vm_lock(m->q->vm, false);
107 	xe_bo_unpin(m->pt_bo);
108 	xe_vm_unlock(m->q->vm);
109 
110 	dma_fence_put(m->fence);
111 	xe_bo_put(m->pt_bo);
112 	drm_suballoc_manager_fini(&m->vm_update_sa);
113 	mutex_destroy(&m->job_mutex);
114 	xe_vm_close_and_put(m->q->vm);
115 	xe_exec_queue_put(m->q);
116 }
117 
118 static u64 xe_migrate_vm_addr(u64 slot, u32 level)
119 {
120 	XE_WARN_ON(slot >= NUM_PT_SLOTS);
121 
122 	/* First slot is reserved for mapping of PT bo and bb, start from 1 */
123 	return (slot + 1ULL) << xe_pt_shift(level + 1);
124 }
125 
126 static u64 xe_migrate_vram_ofs(struct xe_device *xe, u64 addr, bool is_comp_pte)
127 {
128 	/*
129 	 * Remove the DPA to get a correct offset into identity table for the
130 	 * migrate offset
131 	 */
132 	u64 identity_offset = IDENTITY_OFFSET;
133 
134 	if (GRAPHICS_VER(xe) >= 20 && is_comp_pte)
135 		identity_offset += DIV_ROUND_UP_ULL(xe_vram_region_actual_physical_size
136 							(xe->mem.vram), SZ_1G);
137 
138 	addr -= xe_vram_region_dpa_base(xe->mem.vram);
139 	return addr + (identity_offset << xe_pt_shift(2));
140 }
141 
142 static void xe_migrate_program_identity(struct xe_device *xe, struct xe_vm *vm, struct xe_bo *bo,
143 					u64 map_ofs, u64 vram_offset, u16 pat_index, u64 pt_2m_ofs)
144 {
145 	struct xe_vram_region *vram = xe->mem.vram;
146 	resource_size_t dpa_base = xe_vram_region_dpa_base(vram);
147 	u64 pos, ofs, flags;
148 	u64 entry;
149 	/* XXX: Unclear if this should be usable_size? */
150 	u64 vram_limit = xe_vram_region_actual_physical_size(vram) + dpa_base;
151 	u32 level = 2;
152 
153 	ofs = map_ofs + XE_PAGE_SIZE * level + vram_offset * 8;
154 	flags = vm->pt_ops->pte_encode_addr(xe, 0, pat_index, level,
155 					    true, 0);
156 
157 	xe_assert(xe, IS_ALIGNED(xe_vram_region_usable_size(vram), SZ_2M));
158 
159 	/*
160 	 * Use 1GB pages when possible, last chunk always use 2M
161 	 * pages as mixing reserved memory (stolen, WOCPM) with a single
162 	 * mapping is not allowed on certain platforms.
163 	 */
164 	for (pos = dpa_base; pos < vram_limit;
165 	     pos += SZ_1G, ofs += 8) {
166 		if (pos + SZ_1G >= vram_limit) {
167 			entry = vm->pt_ops->pde_encode_bo(bo, pt_2m_ofs);
168 			xe_map_wr(xe, &bo->vmap, ofs, u64, entry);
169 
170 			flags = vm->pt_ops->pte_encode_addr(xe, 0,
171 							    pat_index,
172 							    level - 1,
173 							    true, 0);
174 
175 			for (ofs = pt_2m_ofs; pos < vram_limit;
176 			     pos += SZ_2M, ofs += 8)
177 				xe_map_wr(xe, &bo->vmap, ofs, u64, pos | flags);
178 			break;	/* Ensure pos == vram_limit assert correct */
179 		}
180 
181 		xe_map_wr(xe, &bo->vmap, ofs, u64, pos | flags);
182 	}
183 
184 	xe_assert(xe, pos == vram_limit);
185 }
186 
187 static int xe_migrate_pt_bo_alloc(struct xe_tile *tile, struct xe_migrate *m,
188 				  struct xe_vm *vm, struct drm_exec *exec)
189 {
190 	struct xe_bo *bo, *batch = tile->mem.kernel_bb_pool->bo;
191 	u32 num_entries = NUM_PT_SLOTS;
192 
193 	/* Can't bump NUM_PT_SLOTS too high */
194 	BUILD_BUG_ON(NUM_PT_SLOTS > SZ_2M/XE_PAGE_SIZE);
195 	/* Must be a multiple of 64K to support all platforms */
196 	BUILD_BUG_ON(NUM_PT_SLOTS * XE_PAGE_SIZE % SZ_64K);
197 	/* And one slot reserved for the 4KiB page table updates */
198 	BUILD_BUG_ON(!(NUM_KERNEL_PDE & 1));
199 
200 	/* Need to be sure everything fits in the first PT, or create more */
201 	xe_tile_assert(tile, m->batch_base_ofs + xe_bo_size(batch) < SZ_2M);
202 
203 	bo = xe_bo_create_pin_map(vm->xe, tile, vm,
204 				  num_entries * XE_PAGE_SIZE,
205 				  ttm_bo_type_kernel,
206 				  XE_BO_FLAG_VRAM_IF_DGFX(tile) |
207 				  XE_BO_FLAG_PAGETABLE, exec);
208 	if (IS_ERR(bo))
209 		return PTR_ERR(bo);
210 
211 	m->pt_bo = bo;
212 	return 0;
213 }
214 
215 static void xe_migrate_prepare_vm(struct xe_tile *tile, struct xe_migrate *m,
216 				  struct xe_vm *vm, u32 *ofs)
217 {
218 	struct xe_device *xe = tile_to_xe(tile);
219 	u16 pat_index = xe->pat.idx[XE_CACHE_WB];
220 	u8 id = tile->id;
221 	u32 num_entries = NUM_PT_SLOTS, num_level = vm->pt_root[id]->level;
222 #define VRAM_IDENTITY_MAP_COUNT	2
223 	u32 num_setup = num_level + VRAM_IDENTITY_MAP_COUNT;
224 #undef VRAM_IDENTITY_MAP_COUNT
225 	u32 map_ofs, level, i;
226 	struct xe_bo *bo = m->pt_bo, *batch = tile->mem.kernel_bb_pool->bo;
227 	u64 entry, pt29_ofs;
228 
229 	/* PT30 & PT31 reserved for 2M identity map */
230 	pt29_ofs = xe_bo_size(bo) - 3 * XE_PAGE_SIZE;
231 	entry = vm->pt_ops->pde_encode_bo(bo, pt29_ofs);
232 	xe_pt_write(xe, &vm->pt_root[id]->bo->vmap, 0, entry);
233 
234 	map_ofs = (num_entries - num_setup) * XE_PAGE_SIZE;
235 
236 	/* Map the entire BO in our level 0 pt */
237 	for (i = 0, level = 0; i < num_entries; level++) {
238 		entry = vm->pt_ops->pte_encode_bo(bo, i * XE_PAGE_SIZE,
239 						  pat_index, 0);
240 
241 		xe_map_wr(xe, &bo->vmap, map_ofs + level * 8, u64, entry);
242 
243 		if (vm->flags & XE_VM_FLAG_64K)
244 			i += 16;
245 		else
246 			i += 1;
247 	}
248 
249 	if (!IS_DGFX(xe)) {
250 		/* Write out batch too */
251 		m->batch_base_ofs = NUM_PT_SLOTS * XE_PAGE_SIZE;
252 		for (i = 0; i < xe_bo_size(batch);
253 		     i += vm->flags & XE_VM_FLAG_64K ? XE_64K_PAGE_SIZE :
254 		     XE_PAGE_SIZE) {
255 			entry = vm->pt_ops->pte_encode_bo(batch, i,
256 							  pat_index, 0);
257 
258 			xe_map_wr(xe, &bo->vmap, map_ofs + level * 8, u64,
259 				  entry);
260 			level++;
261 		}
262 		if (xe->info.has_usm) {
263 			xe_tile_assert(tile, xe_bo_size(batch) == SZ_1M);
264 
265 			batch = tile->primary_gt->usm.bb_pool->bo;
266 			m->usm_batch_base_ofs = m->batch_base_ofs + SZ_1M;
267 			xe_tile_assert(tile, xe_bo_size(batch) == SZ_512K);
268 
269 			for (i = 0; i < xe_bo_size(batch);
270 			     i += vm->flags & XE_VM_FLAG_64K ? XE_64K_PAGE_SIZE :
271 			     XE_PAGE_SIZE) {
272 				entry = vm->pt_ops->pte_encode_bo(batch, i,
273 								  pat_index, 0);
274 
275 				xe_map_wr(xe, &bo->vmap, map_ofs + level * 8, u64,
276 					  entry);
277 				level++;
278 			}
279 		}
280 	} else {
281 		u64 batch_addr = xe_bo_addr(batch, 0, XE_PAGE_SIZE);
282 
283 		m->batch_base_ofs = xe_migrate_vram_ofs(xe, batch_addr, false);
284 
285 		if (xe->info.has_usm) {
286 			batch = tile->primary_gt->usm.bb_pool->bo;
287 			batch_addr = xe_bo_addr(batch, 0, XE_PAGE_SIZE);
288 			m->usm_batch_base_ofs = xe_migrate_vram_ofs(xe, batch_addr, false);
289 		}
290 	}
291 
292 	for (level = 1; level < num_level; level++) {
293 		u32 flags = 0;
294 
295 		if (vm->flags & XE_VM_FLAG_64K && level == 1)
296 			flags = XE_PDE_64K;
297 
298 		entry = vm->pt_ops->pde_encode_bo(bo, map_ofs + (u64)(level - 1) *
299 						  XE_PAGE_SIZE);
300 		xe_map_wr(xe, &bo->vmap, map_ofs + XE_PAGE_SIZE * level, u64,
301 			  entry | flags);
302 	}
303 
304 	/* Write PDE's that point to our BO. */
305 	for (i = 0; i < map_ofs / XE_PAGE_SIZE; i++) {
306 		entry = vm->pt_ops->pde_encode_bo(bo, (u64)i * XE_PAGE_SIZE);
307 
308 		xe_map_wr(xe, &bo->vmap, map_ofs + XE_PAGE_SIZE +
309 			  (i + 1) * 8, u64, entry);
310 	}
311 
312 	/* Reserve 2M PDEs */
313 	level = 1;
314 	m->large_page_copy_ofs = NUM_PT_SLOTS << xe_pt_shift(level);
315 	m->large_page_copy_pdes = map_ofs + XE_PAGE_SIZE * level +
316 		NUM_PT_SLOTS * 8;
317 
318 	/* Set up a 1GiB NULL mapping at 255GiB offset. */
319 	level = 2;
320 	xe_map_wr(xe, &bo->vmap, map_ofs + XE_PAGE_SIZE * level + 255 * 8, u64,
321 		  vm->pt_ops->pte_encode_addr(xe, 0, pat_index, level, IS_DGFX(xe), 0)
322 		  | XE_PTE_NULL);
323 	m->cleared_mem_ofs = (255ULL << xe_pt_shift(level));
324 
325 	/* Identity map the entire vram at 256GiB offset */
326 	if (IS_DGFX(xe)) {
327 		u64 pt30_ofs = xe_bo_size(bo) - 2 * XE_PAGE_SIZE;
328 		resource_size_t actual_phy_size = xe_vram_region_actual_physical_size(xe->mem.vram);
329 
330 		xe_migrate_program_identity(xe, vm, bo, map_ofs, IDENTITY_OFFSET,
331 					    pat_index, pt30_ofs);
332 		xe_assert(xe, actual_phy_size <= (MAX_NUM_PTE - IDENTITY_OFFSET) * SZ_1G);
333 
334 		/*
335 		 * Identity map the entire vram for compressed pat_index for xe2+
336 		 * if flat ccs is enabled.
337 		 */
338 		if (GRAPHICS_VER(xe) >= 20 && xe_device_has_flat_ccs(xe)) {
339 			u16 comp_pat_index = xe->pat.idx[XE_CACHE_NONE_COMPRESSION];
340 			u64 vram_offset = IDENTITY_OFFSET +
341 				DIV_ROUND_UP_ULL(actual_phy_size, SZ_1G);
342 			u64 pt31_ofs = xe_bo_size(bo) - XE_PAGE_SIZE;
343 
344 			xe_assert(xe, actual_phy_size <= (MAX_NUM_PTE - IDENTITY_OFFSET -
345 							  IDENTITY_OFFSET / 2) * SZ_1G);
346 			xe_migrate_program_identity(xe, vm, bo, map_ofs, vram_offset,
347 						    comp_pat_index, pt31_ofs);
348 		}
349 	}
350 
351 	if (ofs)
352 		*ofs = map_ofs;
353 }
354 
355 static void xe_migrate_suballoc_manager_init(struct xe_migrate *m, u32 map_ofs)
356 {
357 	/*
358 	 * Example layout created above, with root level = 3:
359 	 * [PT0...PT7]: kernel PT's for copy/clear; 64 or 4KiB PTE's
360 	 * [PT8]: Kernel PT for VM_BIND, 4 KiB PTE's
361 	 * [PT9...PT26]: Userspace PT's for VM_BIND, 4 KiB PTE's
362 	 * [PT27 = PDE 0] [PT28 = PDE 1] [PT29 = PDE 2] [PT30 & PT31 = 2M vram identity map]
363 	 *
364 	 * This makes the lowest part of the VM point to the pagetables.
365 	 * Hence the lowest 2M in the vm should point to itself, with a few writes
366 	 * and flushes, other parts of the VM can be used either for copying and
367 	 * clearing.
368 	 *
369 	 * For performance, the kernel reserves PDE's, so about 20 are left
370 	 * for async VM updates.
371 	 *
372 	 * To make it easier to work, each scratch PT is put in slot (1 + PT #)
373 	 * everywhere, this allows lockless updates to scratch pages by using
374 	 * the different addresses in VM.
375 	 */
376 #define NUM_VMUSA_UNIT_PER_PAGE	32
377 #define VM_SA_UPDATE_UNIT_SIZE		(XE_PAGE_SIZE / NUM_VMUSA_UNIT_PER_PAGE)
378 #define NUM_VMUSA_WRITES_PER_UNIT	(VM_SA_UPDATE_UNIT_SIZE / sizeof(u64))
379 	drm_suballoc_manager_init(&m->vm_update_sa,
380 				  (size_t)(map_ofs / XE_PAGE_SIZE - NUM_KERNEL_PDE) *
381 				  NUM_VMUSA_UNIT_PER_PAGE, 0);
382 }
383 
384 /*
385  * Including the reserved copy engine is required to avoid deadlocks due to
386  * migrate jobs servicing the faults gets stuck behind the job that faulted.
387  */
388 static u32 xe_migrate_usm_logical_mask(struct xe_gt *gt)
389 {
390 	u32 logical_mask = 0;
391 	struct xe_hw_engine *hwe;
392 	enum xe_hw_engine_id id;
393 
394 	for_each_hw_engine(hwe, gt, id) {
395 		if (hwe->class != XE_ENGINE_CLASS_COPY)
396 			continue;
397 
398 		if (xe_gt_is_usm_hwe(gt, hwe))
399 			logical_mask |= BIT(hwe->logical_instance);
400 	}
401 
402 	return logical_mask;
403 }
404 
405 static bool xe_migrate_needs_ccs_emit(struct xe_device *xe)
406 {
407 	return xe_device_has_flat_ccs(xe) && !(GRAPHICS_VER(xe) >= 20 && IS_DGFX(xe));
408 }
409 
410 /**
411  * xe_migrate_alloc - Allocate a migrate struct for a given &xe_tile
412  * @tile: &xe_tile
413  *
414  * Allocates a &xe_migrate for a given tile.
415  *
416  * Return: &xe_migrate on success, or NULL when out of memory.
417  */
418 struct xe_migrate *xe_migrate_alloc(struct xe_tile *tile)
419 {
420 	struct xe_migrate *m = drmm_kzalloc(&tile_to_xe(tile)->drm, sizeof(*m), GFP_KERNEL);
421 
422 	if (m)
423 		m->tile = tile;
424 	return m;
425 }
426 
427 static int xe_migrate_lock_prepare_vm(struct xe_tile *tile, struct xe_migrate *m, struct xe_vm *vm)
428 {
429 	struct xe_device *xe = tile_to_xe(tile);
430 	struct xe_validation_ctx ctx;
431 	struct drm_exec exec;
432 	u32 map_ofs;
433 	int err = 0;
434 
435 	xe_validation_guard(&ctx, &xe->val, &exec, (struct xe_val_flags) {}, err) {
436 		err = xe_vm_drm_exec_lock(vm, &exec);
437 		if (err)
438 			return err;
439 
440 		drm_exec_retry_on_contention(&exec);
441 
442 		err = xe_migrate_pt_bo_alloc(tile, m, vm, &exec);
443 		if (err)
444 			return err;
445 
446 		xe_migrate_prepare_vm(tile, m, vm, &map_ofs);
447 		xe_migrate_suballoc_manager_init(m, map_ofs);
448 		drm_exec_retry_on_contention(&exec);
449 		xe_validation_retry_on_oom(&ctx, &err);
450 	}
451 
452 	return err;
453 }
454 
455 /**
456  * xe_migrate_init() - Initialize a migrate context
457  * @m: The migration context
458  *
459  * Return: 0 if successful, negative error code on failure
460  */
461 int xe_migrate_init(struct xe_migrate *m)
462 {
463 	struct xe_tile *tile = m->tile;
464 	struct xe_gt *primary_gt = tile->primary_gt;
465 	struct xe_device *xe = tile_to_xe(tile);
466 	struct xe_vm *vm;
467 	int err;
468 
469 	/* Special layout, prepared below.. */
470 	vm = xe_vm_create(xe, XE_VM_FLAG_MIGRATION |
471 			  XE_VM_FLAG_SET_TILE_ID(tile), NULL);
472 	if (IS_ERR(vm))
473 		return PTR_ERR(vm);
474 
475 	err = xe_migrate_lock_prepare_vm(tile, m, vm);
476 	if (err)
477 		goto err_out;
478 
479 	if (xe->info.has_usm) {
480 		struct xe_hw_engine *hwe = xe_gt_hw_engine(primary_gt,
481 							   XE_ENGINE_CLASS_COPY,
482 							   primary_gt->usm.reserved_bcs_instance,
483 							   false);
484 		u32 logical_mask = xe_migrate_usm_logical_mask(primary_gt);
485 
486 		if (!hwe || !logical_mask) {
487 			err = -EINVAL;
488 			goto err_out;
489 		}
490 
491 		/*
492 		 * XXX: Currently only reserving 1 (likely slow) BCS instance on
493 		 * PVC, may want to revisit if performance is needed.
494 		 */
495 		m->q = xe_exec_queue_create(xe, vm, logical_mask, 1, hwe,
496 					    EXEC_QUEUE_FLAG_KERNEL |
497 					    EXEC_QUEUE_FLAG_PERMANENT |
498 					    EXEC_QUEUE_FLAG_HIGH_PRIORITY |
499 					    EXEC_QUEUE_FLAG_MIGRATE |
500 					    EXEC_QUEUE_FLAG_LOW_LATENCY, 0);
501 	} else {
502 		m->q = xe_exec_queue_create_class(xe, primary_gt, vm,
503 						  XE_ENGINE_CLASS_COPY,
504 						  EXEC_QUEUE_FLAG_KERNEL |
505 						  EXEC_QUEUE_FLAG_PERMANENT |
506 						  EXEC_QUEUE_FLAG_MIGRATE, 0);
507 	}
508 	if (IS_ERR(m->q)) {
509 		err = PTR_ERR(m->q);
510 		goto err_out;
511 	}
512 
513 	mutex_init(&m->job_mutex);
514 	fs_reclaim_acquire(GFP_KERNEL);
515 	might_lock(&m->job_mutex);
516 	fs_reclaim_release(GFP_KERNEL);
517 
518 	err = devm_add_action_or_reset(xe->drm.dev, xe_migrate_fini, m);
519 	if (err)
520 		return err;
521 
522 	if (IS_DGFX(xe)) {
523 		if (xe_migrate_needs_ccs_emit(xe))
524 			/* min chunk size corresponds to 4K of CCS Metadata */
525 			m->min_chunk_size = SZ_4K * SZ_64K /
526 				xe_device_ccs_bytes(xe, SZ_64K);
527 		else
528 			/* Somewhat arbitrary to avoid a huge amount of blits */
529 			m->min_chunk_size = SZ_64K;
530 		m->min_chunk_size = roundup_pow_of_two(m->min_chunk_size);
531 		drm_dbg(&xe->drm, "Migrate min chunk size is 0x%08llx\n",
532 			(unsigned long long)m->min_chunk_size);
533 	}
534 
535 	return err;
536 
537 err_out:
538 	xe_vm_close_and_put(vm);
539 	return err;
540 
541 }
542 
543 static u64 max_mem_transfer_per_pass(struct xe_device *xe)
544 {
545 	if (!IS_DGFX(xe) && xe_device_has_flat_ccs(xe))
546 		return MAX_CCS_LIMITED_TRANSFER;
547 
548 	return MAX_PREEMPTDISABLE_TRANSFER;
549 }
550 
551 static u64 xe_migrate_res_sizes(struct xe_migrate *m, struct xe_res_cursor *cur)
552 {
553 	struct xe_device *xe = tile_to_xe(m->tile);
554 	u64 size = min_t(u64, max_mem_transfer_per_pass(xe), cur->remaining);
555 
556 	if (mem_type_is_vram(cur->mem_type)) {
557 		/*
558 		 * VRAM we want to blit in chunks with sizes aligned to
559 		 * min_chunk_size in order for the offset to CCS metadata to be
560 		 * page-aligned. If it's the last chunk it may be smaller.
561 		 *
562 		 * Another constraint is that we need to limit the blit to
563 		 * the VRAM block size, unless size is smaller than
564 		 * min_chunk_size.
565 		 */
566 		u64 chunk = max_t(u64, cur->size, m->min_chunk_size);
567 
568 		size = min_t(u64, size, chunk);
569 		if (size > m->min_chunk_size)
570 			size = round_down(size, m->min_chunk_size);
571 	}
572 
573 	return size;
574 }
575 
576 static bool xe_migrate_allow_identity(u64 size, const struct xe_res_cursor *cur)
577 {
578 	/* If the chunk is not fragmented, allow identity map. */
579 	return cur->size >= size;
580 }
581 
582 #define PTE_UPDATE_FLAG_IS_VRAM		BIT(0)
583 #define PTE_UPDATE_FLAG_IS_COMP_PTE	BIT(1)
584 
585 static u32 pte_update_size(struct xe_migrate *m,
586 			   u32 flags,
587 			   struct ttm_resource *res,
588 			   struct xe_res_cursor *cur,
589 			   u64 *L0, u64 *L0_ofs, u32 *L0_pt,
590 			   u32 cmd_size, u32 pt_ofs, u32 avail_pts)
591 {
592 	u32 cmds = 0;
593 	bool is_vram = PTE_UPDATE_FLAG_IS_VRAM & flags;
594 	bool is_comp_pte = PTE_UPDATE_FLAG_IS_COMP_PTE & flags;
595 
596 	*L0_pt = pt_ofs;
597 	if (is_vram && xe_migrate_allow_identity(*L0, cur)) {
598 		/* Offset into identity map. */
599 		*L0_ofs = xe_migrate_vram_ofs(tile_to_xe(m->tile),
600 					      cur->start + vram_region_gpu_offset(res),
601 					      is_comp_pte);
602 		cmds += cmd_size;
603 	} else {
604 		/* Clip L0 to available size */
605 		u64 size = min(*L0, (u64)avail_pts * SZ_2M);
606 		u32 num_4k_pages = (size + XE_PAGE_SIZE - 1) >> XE_PTE_SHIFT;
607 
608 		*L0 = size;
609 		*L0_ofs = xe_migrate_vm_addr(pt_ofs, 0);
610 
611 		/* MI_STORE_DATA_IMM */
612 		cmds += 3 * DIV_ROUND_UP(num_4k_pages, MAX_PTE_PER_SDI);
613 
614 		/* PDE qwords */
615 		cmds += num_4k_pages * 2;
616 
617 		/* Each chunk has a single blit command */
618 		cmds += cmd_size;
619 	}
620 
621 	return cmds;
622 }
623 
624 static void emit_pte(struct xe_migrate *m,
625 		     struct xe_bb *bb, u32 at_pt,
626 		     bool is_vram, bool is_comp_pte,
627 		     struct xe_res_cursor *cur,
628 		     u32 size, struct ttm_resource *res)
629 {
630 	struct xe_device *xe = tile_to_xe(m->tile);
631 	struct xe_vm *vm = m->q->vm;
632 	u16 pat_index;
633 	u32 ptes;
634 	u64 ofs = (u64)at_pt * XE_PAGE_SIZE;
635 	u64 cur_ofs;
636 
637 	/* Indirect access needs compression enabled uncached PAT index */
638 	if (GRAPHICS_VERx100(xe) >= 2000)
639 		pat_index = is_comp_pte ? xe->pat.idx[XE_CACHE_NONE_COMPRESSION] :
640 					  xe->pat.idx[XE_CACHE_WB];
641 	else
642 		pat_index = xe->pat.idx[XE_CACHE_WB];
643 
644 	ptes = DIV_ROUND_UP(size, XE_PAGE_SIZE);
645 
646 	while (ptes) {
647 		u32 chunk = min(MAX_PTE_PER_SDI, ptes);
648 
649 		bb->cs[bb->len++] = MI_STORE_DATA_IMM | MI_SDI_NUM_QW(chunk);
650 		bb->cs[bb->len++] = ofs;
651 		bb->cs[bb->len++] = 0;
652 
653 		cur_ofs = ofs;
654 		ofs += chunk * 8;
655 		ptes -= chunk;
656 
657 		while (chunk--) {
658 			u64 addr, flags = 0;
659 			bool devmem = false;
660 
661 			addr = xe_res_dma(cur) & PAGE_MASK;
662 			if (is_vram) {
663 				if (vm->flags & XE_VM_FLAG_64K) {
664 					u64 va = cur_ofs * XE_PAGE_SIZE / 8;
665 
666 					xe_assert(xe, (va & (SZ_64K - 1)) ==
667 						  (addr & (SZ_64K - 1)));
668 
669 					flags |= XE_PTE_PS64;
670 				}
671 
672 				addr += vram_region_gpu_offset(res);
673 				devmem = true;
674 			}
675 
676 			addr = vm->pt_ops->pte_encode_addr(m->tile->xe,
677 							   addr, pat_index,
678 							   0, devmem, flags);
679 			bb->cs[bb->len++] = lower_32_bits(addr);
680 			bb->cs[bb->len++] = upper_32_bits(addr);
681 
682 			xe_res_next(cur, min_t(u32, size, PAGE_SIZE));
683 			cur_ofs += 8;
684 		}
685 	}
686 }
687 
688 #define EMIT_COPY_CCS_DW 5
689 static void emit_copy_ccs(struct xe_gt *gt, struct xe_bb *bb,
690 			  u64 dst_ofs, bool dst_is_indirect,
691 			  u64 src_ofs, bool src_is_indirect,
692 			  u32 size)
693 {
694 	struct xe_device *xe = gt_to_xe(gt);
695 	u32 *cs = bb->cs + bb->len;
696 	u32 num_ccs_blks;
697 	u32 num_pages;
698 	u32 ccs_copy_size;
699 	u32 mocs;
700 
701 	if (GRAPHICS_VERx100(xe) >= 2000) {
702 		num_pages = DIV_ROUND_UP(size, XE_PAGE_SIZE);
703 		xe_gt_assert(gt, FIELD_FIT(XE2_CCS_SIZE_MASK, num_pages - 1));
704 
705 		ccs_copy_size = REG_FIELD_PREP(XE2_CCS_SIZE_MASK, num_pages - 1);
706 		mocs = FIELD_PREP(XE2_XY_CTRL_SURF_MOCS_INDEX_MASK, gt->mocs.uc_index);
707 
708 	} else {
709 		num_ccs_blks = DIV_ROUND_UP(xe_device_ccs_bytes(gt_to_xe(gt), size),
710 					    NUM_CCS_BYTES_PER_BLOCK);
711 		xe_gt_assert(gt, FIELD_FIT(CCS_SIZE_MASK, num_ccs_blks - 1));
712 
713 		ccs_copy_size = REG_FIELD_PREP(CCS_SIZE_MASK, num_ccs_blks - 1);
714 		mocs = FIELD_PREP(XY_CTRL_SURF_MOCS_MASK, gt->mocs.uc_index);
715 	}
716 
717 	*cs++ = XY_CTRL_SURF_COPY_BLT |
718 		(src_is_indirect ? 0x0 : 0x1) << SRC_ACCESS_TYPE_SHIFT |
719 		(dst_is_indirect ? 0x0 : 0x1) << DST_ACCESS_TYPE_SHIFT |
720 		ccs_copy_size;
721 	*cs++ = lower_32_bits(src_ofs);
722 	*cs++ = upper_32_bits(src_ofs) | mocs;
723 	*cs++ = lower_32_bits(dst_ofs);
724 	*cs++ = upper_32_bits(dst_ofs) | mocs;
725 
726 	bb->len = cs - bb->cs;
727 }
728 
729 #define EMIT_COPY_DW 10
730 static void emit_xy_fast_copy(struct xe_gt *gt, struct xe_bb *bb, u64 src_ofs,
731 			      u64 dst_ofs, unsigned int size,
732 			      unsigned int pitch)
733 {
734 	struct xe_device *xe = gt_to_xe(gt);
735 	u32 mocs = 0;
736 	u32 tile_y = 0;
737 
738 	xe_gt_assert(gt, !(pitch & 3));
739 	xe_gt_assert(gt, size / pitch <= S16_MAX);
740 	xe_gt_assert(gt, pitch / 4 <= S16_MAX);
741 	xe_gt_assert(gt, pitch <= U16_MAX);
742 
743 	if (GRAPHICS_VER(xe) >= 20)
744 		mocs = FIELD_PREP(XE2_XY_FAST_COPY_BLT_MOCS_INDEX_MASK, gt->mocs.uc_index);
745 
746 	if (GRAPHICS_VERx100(xe) >= 1250)
747 		tile_y = XY_FAST_COPY_BLT_D1_SRC_TILE4 | XY_FAST_COPY_BLT_D1_DST_TILE4;
748 
749 	bb->cs[bb->len++] = XY_FAST_COPY_BLT_CMD | (10 - 2);
750 	bb->cs[bb->len++] = XY_FAST_COPY_BLT_DEPTH_32 | pitch | tile_y | mocs;
751 	bb->cs[bb->len++] = 0;
752 	bb->cs[bb->len++] = (size / pitch) << 16 | pitch / 4;
753 	bb->cs[bb->len++] = lower_32_bits(dst_ofs);
754 	bb->cs[bb->len++] = upper_32_bits(dst_ofs);
755 	bb->cs[bb->len++] = 0;
756 	bb->cs[bb->len++] = pitch | mocs;
757 	bb->cs[bb->len++] = lower_32_bits(src_ofs);
758 	bb->cs[bb->len++] = upper_32_bits(src_ofs);
759 }
760 
761 #define PAGE_COPY_MODE_PS SZ_256 /* hw uses 256 bytes as the page-size */
762 static void emit_mem_copy(struct xe_gt *gt, struct xe_bb *bb, u64 src_ofs,
763 			  u64 dst_ofs, unsigned int size, unsigned int pitch)
764 {
765 	u32 mode, copy_type, width;
766 
767 	xe_gt_assert(gt, IS_ALIGNED(size, pitch));
768 	xe_gt_assert(gt, pitch <= U16_MAX);
769 	xe_gt_assert(gt, pitch);
770 	xe_gt_assert(gt, size);
771 
772 	if (IS_ALIGNED(size, PAGE_COPY_MODE_PS) &&
773 	    IS_ALIGNED(lower_32_bits(src_ofs), PAGE_COPY_MODE_PS) &&
774 	    IS_ALIGNED(lower_32_bits(dst_ofs), PAGE_COPY_MODE_PS)) {
775 		mode = MEM_COPY_PAGE_COPY_MODE;
776 		copy_type = 0; /* linear copy */
777 		width = size / PAGE_COPY_MODE_PS;
778 	} else if (pitch > 1) {
779 		xe_gt_assert(gt, size / pitch <= U16_MAX);
780 		mode = 0; /* BYTE_COPY */
781 		copy_type = MEM_COPY_MATRIX_COPY;
782 		width = pitch;
783 	} else {
784 		mode = 0; /* BYTE_COPY */
785 		copy_type = 0; /* linear copy */
786 		width = size;
787 	}
788 
789 	xe_gt_assert(gt, width <= U16_MAX);
790 
791 	bb->cs[bb->len++] = MEM_COPY_CMD | mode | copy_type;
792 	bb->cs[bb->len++] = width - 1;
793 	bb->cs[bb->len++] = size / pitch - 1; /* ignored by hw for page-copy/linear above */
794 	bb->cs[bb->len++] = pitch - 1;
795 	bb->cs[bb->len++] = pitch - 1;
796 	bb->cs[bb->len++] = lower_32_bits(src_ofs);
797 	bb->cs[bb->len++] = upper_32_bits(src_ofs);
798 	bb->cs[bb->len++] = lower_32_bits(dst_ofs);
799 	bb->cs[bb->len++] = upper_32_bits(dst_ofs);
800 	bb->cs[bb->len++] = FIELD_PREP(MEM_COPY_SRC_MOCS_INDEX_MASK, gt->mocs.uc_index) |
801 			    FIELD_PREP(MEM_COPY_DST_MOCS_INDEX_MASK, gt->mocs.uc_index);
802 }
803 
804 static void emit_copy(struct xe_gt *gt, struct xe_bb *bb,
805 		      u64 src_ofs, u64 dst_ofs, unsigned int size,
806 		      unsigned int pitch)
807 {
808 	struct xe_device *xe = gt_to_xe(gt);
809 
810 	if (xe->info.has_mem_copy_instr)
811 		emit_mem_copy(gt, bb, src_ofs, dst_ofs, size, pitch);
812 	else
813 		emit_xy_fast_copy(gt, bb, src_ofs, dst_ofs, size, pitch);
814 }
815 
816 static u64 xe_migrate_batch_base(struct xe_migrate *m, bool usm)
817 {
818 	return usm ? m->usm_batch_base_ofs : m->batch_base_ofs;
819 }
820 
821 static u32 xe_migrate_ccs_copy(struct xe_migrate *m,
822 			       struct xe_bb *bb,
823 			       u64 src_ofs, bool src_is_indirect,
824 			       u64 dst_ofs, bool dst_is_indirect, u32 dst_size,
825 			       u64 ccs_ofs, bool copy_ccs)
826 {
827 	struct xe_gt *gt = m->tile->primary_gt;
828 	u32 flush_flags = 0;
829 
830 	if (!copy_ccs && dst_is_indirect) {
831 		/*
832 		 * If the src is already in vram, then it should already
833 		 * have been cleared by us, or has been populated by the
834 		 * user. Make sure we copy the CCS aux state as-is.
835 		 *
836 		 * Otherwise if the bo doesn't have any CCS metadata attached,
837 		 * we still need to clear it for security reasons.
838 		 */
839 		u64 ccs_src_ofs =  src_is_indirect ? src_ofs : m->cleared_mem_ofs;
840 
841 		emit_copy_ccs(gt, bb,
842 			      dst_ofs, true,
843 			      ccs_src_ofs, src_is_indirect, dst_size);
844 
845 		flush_flags = MI_FLUSH_DW_CCS;
846 	} else if (copy_ccs) {
847 		if (!src_is_indirect)
848 			src_ofs = ccs_ofs;
849 		else if (!dst_is_indirect)
850 			dst_ofs = ccs_ofs;
851 
852 		xe_gt_assert(gt, src_is_indirect || dst_is_indirect);
853 
854 		emit_copy_ccs(gt, bb, dst_ofs, dst_is_indirect, src_ofs,
855 			      src_is_indirect, dst_size);
856 		if (dst_is_indirect)
857 			flush_flags = MI_FLUSH_DW_CCS;
858 	}
859 
860 	return flush_flags;
861 }
862 
863 static struct dma_fence *__xe_migrate_copy(struct xe_migrate *m,
864 					   struct xe_bo *src_bo,
865 					   struct xe_bo *dst_bo,
866 					   struct ttm_resource *src,
867 					   struct ttm_resource *dst,
868 					   bool copy_only_ccs,
869 					   bool is_vram_resolve)
870 {
871 	struct xe_gt *gt = m->tile->primary_gt;
872 	struct xe_device *xe = gt_to_xe(gt);
873 	struct dma_fence *fence = NULL;
874 	u64 size = xe_bo_size(src_bo);
875 	struct xe_res_cursor src_it, dst_it, ccs_it;
876 	u64 src_L0_ofs, dst_L0_ofs;
877 	u32 src_L0_pt, dst_L0_pt;
878 	u64 src_L0, dst_L0;
879 	int pass = 0;
880 	int err;
881 	bool src_is_pltt = src->mem_type == XE_PL_TT;
882 	bool dst_is_pltt = dst->mem_type == XE_PL_TT;
883 	bool src_is_vram = mem_type_is_vram(src->mem_type);
884 	bool dst_is_vram = mem_type_is_vram(dst->mem_type);
885 	bool type_device = src_bo->ttm.type == ttm_bo_type_device;
886 	bool needs_ccs_emit = type_device && xe_migrate_needs_ccs_emit(xe);
887 	bool copy_ccs = xe_device_has_flat_ccs(xe) &&
888 		xe_bo_needs_ccs_pages(src_bo) && xe_bo_needs_ccs_pages(dst_bo);
889 	bool copy_system_ccs = copy_ccs && (!src_is_vram || !dst_is_vram);
890 
891 	/*
892 	 * For decompression operation, always use the compression PAT index.
893 	 * Otherwise, only use the compression PAT index for device memory
894 	 * when copying from VRAM to system memory.
895 	 */
896 	bool use_comp_pat = is_vram_resolve || (type_device &&
897 			    xe_device_has_flat_ccs(xe) &&
898 			    GRAPHICS_VER(xe) >= 20 && src_is_vram && !dst_is_vram);
899 
900 	/* Copying CCS between two different BOs is not supported yet. */
901 	if (XE_WARN_ON(copy_ccs && src_bo != dst_bo))
902 		return ERR_PTR(-EINVAL);
903 
904 	if (src_bo != dst_bo && XE_WARN_ON(xe_bo_size(src_bo) != xe_bo_size(dst_bo)))
905 		return ERR_PTR(-EINVAL);
906 
907 	if (!src_is_vram)
908 		xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
909 	else
910 		xe_res_first(src, 0, size, &src_it);
911 	if (!dst_is_vram)
912 		xe_res_first_sg(xe_bo_sg(dst_bo), 0, size, &dst_it);
913 	else
914 		xe_res_first(dst, 0, size, &dst_it);
915 
916 	if (copy_system_ccs)
917 		xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
918 				PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
919 				&ccs_it);
920 
921 	while (size) {
922 		u32 batch_size = 1; /* MI_BATCH_BUFFER_END */
923 		struct xe_sched_job *job;
924 		struct xe_bb *bb;
925 		u32 flush_flags = 0;
926 		u32 update_idx;
927 		u64 ccs_ofs, ccs_size;
928 		u32 ccs_pt;
929 		u32 pte_flags;
930 
931 		bool usm = xe->info.has_usm;
932 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
933 
934 		src_L0 = xe_migrate_res_sizes(m, &src_it);
935 		dst_L0 = xe_migrate_res_sizes(m, &dst_it);
936 
937 		drm_dbg(&xe->drm, "Pass %u, sizes: %llu & %llu\n",
938 			pass++, src_L0, dst_L0);
939 
940 		src_L0 = min(src_L0, dst_L0);
941 
942 		pte_flags = src_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
943 		pte_flags |= use_comp_pat ? PTE_UPDATE_FLAG_IS_COMP_PTE : 0;
944 		batch_size += pte_update_size(m, pte_flags, src, &src_it, &src_L0,
945 					      &src_L0_ofs, &src_L0_pt, 0, 0,
946 					      avail_pts);
947 		if (copy_only_ccs) {
948 			dst_L0_ofs = src_L0_ofs;
949 		} else {
950 			pte_flags = dst_is_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
951 			batch_size += pte_update_size(m, pte_flags, dst,
952 						      &dst_it, &src_L0,
953 						      &dst_L0_ofs, &dst_L0_pt,
954 						      0, avail_pts, avail_pts);
955 		}
956 
957 		if (copy_system_ccs) {
958 			xe_assert(xe, type_device);
959 			ccs_size = xe_device_ccs_bytes(xe, src_L0);
960 			batch_size += pte_update_size(m, 0, NULL, &ccs_it, &ccs_size,
961 						      &ccs_ofs, &ccs_pt, 0,
962 						      2 * avail_pts,
963 						      avail_pts);
964 			xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
965 		}
966 
967 		/* Add copy commands size here */
968 		batch_size += ((copy_only_ccs) ? 0 : EMIT_COPY_DW) +
969 			((needs_ccs_emit ? EMIT_COPY_CCS_DW : 0));
970 
971 		bb = xe_bb_new(gt, batch_size, usm);
972 		if (IS_ERR(bb)) {
973 			err = PTR_ERR(bb);
974 			goto err_sync;
975 		}
976 
977 		if (src_is_vram && xe_migrate_allow_identity(src_L0, &src_it))
978 			xe_res_next(&src_it, src_L0);
979 		else
980 			emit_pte(m, bb, src_L0_pt, src_is_vram, copy_system_ccs || use_comp_pat,
981 				 &src_it, src_L0, src);
982 
983 		if (dst_is_vram && xe_migrate_allow_identity(src_L0, &dst_it))
984 			xe_res_next(&dst_it, src_L0);
985 		else if (!copy_only_ccs)
986 			emit_pte(m, bb, dst_L0_pt, dst_is_vram, copy_system_ccs,
987 				 &dst_it, src_L0, dst);
988 
989 		if (copy_system_ccs)
990 			emit_pte(m, bb, ccs_pt, false, false, &ccs_it, ccs_size, src);
991 
992 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
993 		update_idx = bb->len;
994 
995 		if (!copy_only_ccs)
996 			emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, src_L0, XE_PAGE_SIZE);
997 
998 		if (needs_ccs_emit)
999 			flush_flags = xe_migrate_ccs_copy(m, bb, src_L0_ofs,
1000 							  IS_DGFX(xe) ? src_is_vram : src_is_pltt,
1001 							  dst_L0_ofs,
1002 							  IS_DGFX(xe) ? dst_is_vram : dst_is_pltt,
1003 							  src_L0, ccs_ofs, copy_ccs);
1004 
1005 		job = xe_bb_create_migration_job(m->q, bb,
1006 						 xe_migrate_batch_base(m, usm),
1007 						 update_idx);
1008 		if (IS_ERR(job)) {
1009 			err = PTR_ERR(job);
1010 			goto err;
1011 		}
1012 
1013 		xe_sched_job_add_migrate_flush(job, flush_flags | MI_INVALIDATE_TLB);
1014 		if (!fence) {
1015 			err = xe_sched_job_add_deps(job, src_bo->ttm.base.resv,
1016 						    DMA_RESV_USAGE_BOOKKEEP);
1017 			if (!err && src_bo->ttm.base.resv != dst_bo->ttm.base.resv)
1018 				err = xe_sched_job_add_deps(job, dst_bo->ttm.base.resv,
1019 							    DMA_RESV_USAGE_BOOKKEEP);
1020 			if (err)
1021 				goto err_job;
1022 		}
1023 
1024 		mutex_lock(&m->job_mutex);
1025 		xe_sched_job_arm(job);
1026 		dma_fence_put(fence);
1027 		fence = dma_fence_get(&job->drm.s_fence->finished);
1028 		xe_sched_job_push(job);
1029 
1030 		dma_fence_put(m->fence);
1031 		m->fence = dma_fence_get(fence);
1032 
1033 		mutex_unlock(&m->job_mutex);
1034 
1035 		xe_bb_free(bb, fence);
1036 		size -= src_L0;
1037 		continue;
1038 
1039 err_job:
1040 		xe_sched_job_put(job);
1041 err:
1042 		xe_bb_free(bb, NULL);
1043 
1044 err_sync:
1045 		/* Sync partial copy if any. FIXME: under job_mutex? */
1046 		if (fence) {
1047 			dma_fence_wait(fence, false);
1048 			dma_fence_put(fence);
1049 		}
1050 
1051 		return ERR_PTR(err);
1052 	}
1053 
1054 	return fence;
1055 }
1056 
1057 /**
1058  * xe_migrate_copy() - Copy content of TTM resources.
1059  * @m: The migration context.
1060  * @src_bo: The buffer object @src is currently bound to.
1061  * @dst_bo: If copying between resources created for the same bo, set this to
1062  * the same value as @src_bo. If copying between buffer objects, set it to
1063  * the buffer object @dst is currently bound to.
1064  * @src: The source TTM resource.
1065  * @dst: The dst TTM resource.
1066  * @copy_only_ccs: If true copy only CCS metadata
1067  *
1068  * Copies the contents of @src to @dst: On flat CCS devices,
1069  * the CCS metadata is copied as well if needed, or if not present,
1070  * the CCS metadata of @dst is cleared for security reasons.
1071  *
1072  * Return: Pointer to a dma_fence representing the last copy batch, or
1073  * an error pointer on failure. If there is a failure, any copy operation
1074  * started by the function call has been synced.
1075  */
1076 struct dma_fence *xe_migrate_copy(struct xe_migrate *m,
1077 				  struct xe_bo *src_bo,
1078 				  struct xe_bo *dst_bo,
1079 				  struct ttm_resource *src,
1080 				  struct ttm_resource *dst,
1081 				  bool copy_only_ccs)
1082 {
1083 	return __xe_migrate_copy(m, src_bo, dst_bo, src, dst, copy_only_ccs, false);
1084 }
1085 
1086 /**
1087  * xe_migrate_resolve() - Resolve and decompress a buffer object if required.
1088  * @m: The migrate context
1089  * @bo: The buffer object to resolve
1090  * @res: The reservation object
1091  *
1092  * Wrapper around __xe_migrate_copy() with is_vram_resolve set to true
1093  * to trigger decompression if needed.
1094  *
1095  * Return: A dma_fence that signals on completion, or an ERR_PTR on failure.
1096  */
1097 struct dma_fence *xe_migrate_resolve(struct xe_migrate *m,
1098 				     struct xe_bo *bo,
1099 				     struct ttm_resource *res)
1100 {
1101 	return __xe_migrate_copy(m, bo, bo, res, res, false, true);
1102 }
1103 
1104 /**
1105  * xe_migrate_lrc() - Get the LRC from migrate context.
1106  * @migrate: Migrate context.
1107  *
1108  * Return: Pointer to LRC on success, error on failure
1109  */
1110 struct xe_lrc *xe_migrate_lrc(struct xe_migrate *migrate)
1111 {
1112 	return migrate->q->lrc[0];
1113 }
1114 
1115 static u64 migrate_vm_ppgtt_addr_tlb_inval(void)
1116 {
1117 	/*
1118 	 * The migrate VM is self-referential so it can modify its own PTEs (see
1119 	 * pte_update_size() or emit_pte() functions). We reserve NUM_KERNEL_PDE
1120 	 * entries for kernel operations (copies, clears, CCS migrate), and
1121 	 * suballocate the rest to user operations (binds/unbinds). With
1122 	 * NUM_KERNEL_PDE = 15, NUM_KERNEL_PDE - 1 is already used for PTE updates,
1123 	 * so assign NUM_KERNEL_PDE - 2 for TLB invalidation.
1124 	 */
1125 	return (NUM_KERNEL_PDE - 2) * XE_PAGE_SIZE;
1126 }
1127 
1128 static int emit_flush_invalidate(u32 *dw, int i, u32 flags)
1129 {
1130 	u64 addr = migrate_vm_ppgtt_addr_tlb_inval();
1131 
1132 	dw[i++] = MI_FLUSH_DW | MI_INVALIDATE_TLB | MI_FLUSH_DW_OP_STOREDW |
1133 		  MI_FLUSH_IMM_DW | flags;
1134 	dw[i++] = lower_32_bits(addr);
1135 	dw[i++] = upper_32_bits(addr);
1136 	dw[i++] = MI_NOOP;
1137 	dw[i++] = MI_NOOP;
1138 
1139 	return i;
1140 }
1141 
1142 /**
1143  * xe_migrate_ccs_rw_copy() - Copy content of TTM resources.
1144  * @tile: Tile whose migration context to be used.
1145  * @q : Execution to be used along with migration context.
1146  * @src_bo: The buffer object @src is currently bound to.
1147  * @read_write : Creates BB commands for CCS read/write.
1148  *
1149  * Creates batch buffer instructions to copy CCS metadata from CCS pool to
1150  * memory and vice versa.
1151  *
1152  * This function should only be called for IGPU.
1153  *
1154  * Return: 0 if successful, negative error code on failure.
1155  */
1156 int xe_migrate_ccs_rw_copy(struct xe_tile *tile, struct xe_exec_queue *q,
1157 			   struct xe_bo *src_bo,
1158 			   enum xe_sriov_vf_ccs_rw_ctxs read_write)
1159 
1160 {
1161 	bool src_is_pltt = read_write == XE_SRIOV_VF_CCS_READ_CTX;
1162 	bool dst_is_pltt = read_write == XE_SRIOV_VF_CCS_WRITE_CTX;
1163 	struct ttm_resource *src = src_bo->ttm.resource;
1164 	struct xe_migrate *m = tile->migrate;
1165 	struct xe_gt *gt = tile->primary_gt;
1166 	u32 batch_size, batch_size_allocated;
1167 	struct xe_device *xe = gt_to_xe(gt);
1168 	struct xe_res_cursor src_it, ccs_it;
1169 	struct xe_sriov_vf_ccs_ctx *ctx;
1170 	struct xe_sa_manager *bb_pool;
1171 	u64 size = xe_bo_size(src_bo);
1172 	struct xe_bb *bb = NULL;
1173 	u64 src_L0, src_L0_ofs;
1174 	u32 src_L0_pt;
1175 	int err;
1176 
1177 	ctx = &xe->sriov.vf.ccs.contexts[read_write];
1178 
1179 	xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
1180 
1181 	xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
1182 			PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
1183 			&ccs_it);
1184 
1185 	/* Calculate Batch buffer size */
1186 	batch_size = 0;
1187 	while (size) {
1188 		batch_size += 10; /* Flush + ggtt addr + 2 NOP */
1189 		u64 ccs_ofs, ccs_size;
1190 		u32 ccs_pt;
1191 
1192 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1193 
1194 		src_L0 = min_t(u64, max_mem_transfer_per_pass(xe), size);
1195 
1196 		batch_size += pte_update_size(m, false, src, &src_it, &src_L0,
1197 					      &src_L0_ofs, &src_L0_pt, 0, 0,
1198 					      avail_pts);
1199 
1200 		ccs_size = xe_device_ccs_bytes(xe, src_L0);
1201 		batch_size += pte_update_size(m, 0, NULL, &ccs_it, &ccs_size, &ccs_ofs,
1202 					      &ccs_pt, 0, avail_pts, avail_pts);
1203 		xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
1204 
1205 		/* Add copy commands size here */
1206 		batch_size += EMIT_COPY_CCS_DW;
1207 
1208 		size -= src_L0;
1209 	}
1210 
1211 	bb = xe_bb_alloc(gt);
1212 	if (IS_ERR(bb))
1213 		return PTR_ERR(bb);
1214 
1215 	bb_pool = ctx->mem.ccs_bb_pool;
1216 	scoped_guard(mutex, xe_sa_bo_swap_guard(bb_pool)) {
1217 		xe_sa_bo_swap_shadow(bb_pool);
1218 
1219 		err = xe_bb_init(bb, bb_pool, batch_size);
1220 		if (err) {
1221 			xe_gt_err(gt, "BB allocation failed.\n");
1222 			xe_bb_free(bb, NULL);
1223 			return err;
1224 		}
1225 
1226 		batch_size_allocated = batch_size;
1227 		size = xe_bo_size(src_bo);
1228 		batch_size = 0;
1229 
1230 		/*
1231 		 * Emit PTE and copy commands here.
1232 		 * The CCS copy command can only support limited size. If the size to be
1233 		 * copied is more than the limit, divide copy into chunks. So, calculate
1234 		 * sizes here again before copy command is emitted.
1235 		 */
1236 
1237 		while (size) {
1238 			batch_size += 10; /* Flush + ggtt addr + 2 NOP */
1239 			u32 flush_flags = 0;
1240 			u64 ccs_ofs, ccs_size;
1241 			u32 ccs_pt;
1242 
1243 			u32 avail_pts = max_mem_transfer_per_pass(xe) /
1244 					LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1245 
1246 			src_L0 = xe_migrate_res_sizes(m, &src_it);
1247 
1248 			batch_size += pte_update_size(m, false, src, &src_it, &src_L0,
1249 						      &src_L0_ofs, &src_L0_pt, 0, 0,
1250 						      avail_pts);
1251 
1252 			ccs_size = xe_device_ccs_bytes(xe, src_L0);
1253 			batch_size += pte_update_size(m, 0, NULL, &ccs_it, &ccs_size, &ccs_ofs,
1254 						      &ccs_pt, 0, avail_pts, avail_pts);
1255 			xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
1256 			batch_size += EMIT_COPY_CCS_DW;
1257 
1258 			emit_pte(m, bb, src_L0_pt, false, true, &src_it, src_L0, src);
1259 
1260 			emit_pte(m, bb, ccs_pt, false, false, &ccs_it, ccs_size, src);
1261 
1262 			bb->len = emit_flush_invalidate(bb->cs, bb->len, flush_flags);
1263 			flush_flags = xe_migrate_ccs_copy(m, bb, src_L0_ofs, src_is_pltt,
1264 							  src_L0_ofs, dst_is_pltt,
1265 							  src_L0, ccs_ofs, true);
1266 			bb->len = emit_flush_invalidate(bb->cs, bb->len, flush_flags);
1267 
1268 			size -= src_L0;
1269 		}
1270 
1271 		xe_assert(xe, (batch_size_allocated == bb->len));
1272 		src_bo->bb_ccs[read_write] = bb;
1273 
1274 		xe_sriov_vf_ccs_rw_update_bb_addr(ctx);
1275 		xe_sa_bo_sync_shadow(bb->bo);
1276 	}
1277 
1278 	return 0;
1279 }
1280 
1281 /**
1282  * xe_migrate_ccs_rw_copy_clear() - Clear the CCS read/write batch buffer
1283  * content.
1284  * @src_bo: The buffer object @src is currently bound to.
1285  * @read_write : Creates BB commands for CCS read/write.
1286  *
1287  * Directly clearing the BB lacks atomicity and can lead to undefined
1288  * behavior if the vCPU is halted mid-operation during the clearing
1289  * process. To avoid this issue, we use a shadow buffer object approach.
1290  *
1291  * First swap the SA BO address with the shadow BO, perform the clearing
1292  * operation on the BB, update the shadow BO in the ring buffer, then
1293  * sync the shadow and the actual buffer to maintain consistency.
1294  *
1295  * Returns: None.
1296  */
1297 void xe_migrate_ccs_rw_copy_clear(struct xe_bo *src_bo,
1298 				  enum xe_sriov_vf_ccs_rw_ctxs read_write)
1299 {
1300 	struct xe_bb *bb = src_bo->bb_ccs[read_write];
1301 	struct xe_device *xe = xe_bo_device(src_bo);
1302 	struct xe_sriov_vf_ccs_ctx *ctx;
1303 	struct xe_sa_manager *bb_pool;
1304 	u32 *cs;
1305 
1306 	xe_assert(xe, IS_SRIOV_VF(xe));
1307 
1308 	ctx = &xe->sriov.vf.ccs.contexts[read_write];
1309 	bb_pool = ctx->mem.ccs_bb_pool;
1310 
1311 	guard(mutex) (xe_sa_bo_swap_guard(bb_pool));
1312 	xe_sa_bo_swap_shadow(bb_pool);
1313 
1314 	cs = xe_sa_bo_cpu_addr(bb->bo);
1315 	memset(cs, MI_NOOP, bb->len * sizeof(u32));
1316 	xe_sriov_vf_ccs_rw_update_bb_addr(ctx);
1317 
1318 	xe_sa_bo_sync_shadow(bb->bo);
1319 
1320 	xe_bb_free(bb, NULL);
1321 	src_bo->bb_ccs[read_write] = NULL;
1322 }
1323 
1324 /**
1325  * xe_migrate_exec_queue() - Get the execution queue from migrate context.
1326  * @migrate: Migrate context.
1327  *
1328  * Return: Pointer to execution queue on success, error on failure
1329  */
1330 struct xe_exec_queue *xe_migrate_exec_queue(struct xe_migrate *migrate)
1331 {
1332 	return migrate->q;
1333 }
1334 
1335 /**
1336  * xe_migrate_vram_copy_chunk() - Copy a chunk of a VRAM buffer object.
1337  * @vram_bo: The VRAM buffer object.
1338  * @vram_offset: The VRAM offset.
1339  * @sysmem_bo: The sysmem buffer object.
1340  * @sysmem_offset: The sysmem offset.
1341  * @size: The size of VRAM chunk to copy.
1342  * @dir: The direction of the copy operation.
1343  *
1344  * Copies a portion of a buffer object between VRAM and system memory.
1345  * On Xe2 platforms that support flat CCS, VRAM data is decompressed when
1346  * copying to system memory.
1347  *
1348  * Return: Pointer to a dma_fence representing the last copy batch, or
1349  * an error pointer on failure. If there is a failure, any copy operation
1350  * started by the function call has been synced.
1351  */
1352 struct dma_fence *xe_migrate_vram_copy_chunk(struct xe_bo *vram_bo, u64 vram_offset,
1353 					     struct xe_bo *sysmem_bo, u64 sysmem_offset,
1354 					     u64 size, enum xe_migrate_copy_dir dir)
1355 {
1356 	struct xe_device *xe = xe_bo_device(vram_bo);
1357 	struct xe_tile *tile = vram_bo->tile;
1358 	struct xe_gt *gt = tile->primary_gt;
1359 	struct xe_migrate *m = tile->migrate;
1360 	struct dma_fence *fence = NULL;
1361 	struct ttm_resource *vram = vram_bo->ttm.resource;
1362 	struct ttm_resource *sysmem = sysmem_bo->ttm.resource;
1363 	struct xe_res_cursor vram_it, sysmem_it;
1364 	u64 vram_L0_ofs, sysmem_L0_ofs;
1365 	u32 vram_L0_pt, sysmem_L0_pt;
1366 	u64 vram_L0, sysmem_L0;
1367 	bool to_sysmem = (dir == XE_MIGRATE_COPY_TO_SRAM);
1368 	bool use_comp_pat = to_sysmem &&
1369 		GRAPHICS_VER(xe) >= 20 && xe_device_has_flat_ccs(xe);
1370 	int pass = 0;
1371 	int err;
1372 
1373 	xe_assert(xe, IS_ALIGNED(vram_offset | sysmem_offset | size, PAGE_SIZE));
1374 	xe_assert(xe, xe_bo_is_vram(vram_bo));
1375 	xe_assert(xe, !xe_bo_is_vram(sysmem_bo));
1376 	xe_assert(xe, !range_overflows(vram_offset, size, (u64)vram_bo->ttm.base.size));
1377 	xe_assert(xe, !range_overflows(sysmem_offset, size, (u64)sysmem_bo->ttm.base.size));
1378 
1379 	xe_res_first(vram, vram_offset, size, &vram_it);
1380 	xe_res_first_sg(xe_bo_sg(sysmem_bo), sysmem_offset, size, &sysmem_it);
1381 
1382 	while (size) {
1383 		u32 pte_flags = PTE_UPDATE_FLAG_IS_VRAM;
1384 		u32 batch_size = 2; /* arb_clear() + MI_BATCH_BUFFER_END */
1385 		struct xe_sched_job *job;
1386 		struct xe_bb *bb;
1387 		u32 update_idx;
1388 		bool usm = xe->info.has_usm;
1389 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1390 
1391 		sysmem_L0 = xe_migrate_res_sizes(m, &sysmem_it);
1392 		vram_L0 = min(xe_migrate_res_sizes(m, &vram_it), sysmem_L0);
1393 
1394 		xe_dbg(xe, "Pass %u, size: %llu\n", pass++, vram_L0);
1395 
1396 		pte_flags |= use_comp_pat ? PTE_UPDATE_FLAG_IS_COMP_PTE : 0;
1397 		batch_size += pte_update_size(m, pte_flags, vram, &vram_it, &vram_L0,
1398 					      &vram_L0_ofs, &vram_L0_pt, 0, 0, avail_pts);
1399 
1400 		batch_size += pte_update_size(m, 0, sysmem, &sysmem_it, &vram_L0, &sysmem_L0_ofs,
1401 					      &sysmem_L0_pt, 0, avail_pts, avail_pts);
1402 		batch_size += EMIT_COPY_DW;
1403 
1404 		bb = xe_bb_new(gt, batch_size, usm);
1405 		if (IS_ERR(bb)) {
1406 			err = PTR_ERR(bb);
1407 			return ERR_PTR(err);
1408 		}
1409 
1410 		if (xe_migrate_allow_identity(vram_L0, &vram_it))
1411 			xe_res_next(&vram_it, vram_L0);
1412 		else
1413 			emit_pte(m, bb, vram_L0_pt, true, use_comp_pat, &vram_it, vram_L0, vram);
1414 
1415 		emit_pte(m, bb, sysmem_L0_pt, false, false, &sysmem_it, vram_L0, sysmem);
1416 
1417 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
1418 		update_idx = bb->len;
1419 
1420 		if (to_sysmem)
1421 			emit_copy(gt, bb, vram_L0_ofs, sysmem_L0_ofs, vram_L0, XE_PAGE_SIZE);
1422 		else
1423 			emit_copy(gt, bb, sysmem_L0_ofs, vram_L0_ofs, vram_L0, XE_PAGE_SIZE);
1424 
1425 		job = xe_bb_create_migration_job(m->q, bb, xe_migrate_batch_base(m, usm),
1426 						 update_idx);
1427 		if (IS_ERR(job)) {
1428 			xe_bb_free(bb, NULL);
1429 			err = PTR_ERR(job);
1430 			return ERR_PTR(err);
1431 		}
1432 
1433 		xe_sched_job_add_migrate_flush(job, MI_INVALIDATE_TLB);
1434 
1435 		xe_assert(xe, dma_resv_test_signaled(vram_bo->ttm.base.resv,
1436 						     DMA_RESV_USAGE_BOOKKEEP));
1437 		xe_assert(xe, dma_resv_test_signaled(sysmem_bo->ttm.base.resv,
1438 						     DMA_RESV_USAGE_BOOKKEEP));
1439 
1440 		scoped_guard(mutex, &m->job_mutex) {
1441 			xe_sched_job_arm(job);
1442 			dma_fence_put(fence);
1443 			fence = dma_fence_get(&job->drm.s_fence->finished);
1444 			xe_sched_job_push(job);
1445 
1446 			dma_fence_put(m->fence);
1447 			m->fence = dma_fence_get(fence);
1448 		}
1449 
1450 		xe_bb_free(bb, fence);
1451 		size -= vram_L0;
1452 	}
1453 
1454 	return fence;
1455 }
1456 
1457 static void emit_clear_link_copy(struct xe_gt *gt, struct xe_bb *bb, u64 src_ofs,
1458 				 u32 size, u32 pitch)
1459 {
1460 	struct xe_device *xe = gt_to_xe(gt);
1461 	u32 *cs = bb->cs + bb->len;
1462 	u32 len = PVC_MEM_SET_CMD_LEN_DW;
1463 
1464 	*cs++ = PVC_MEM_SET_CMD | PVC_MEM_SET_MATRIX | (len - 2);
1465 	*cs++ = pitch - 1;
1466 	*cs++ = (size / pitch) - 1;
1467 	*cs++ = pitch - 1;
1468 	*cs++ = lower_32_bits(src_ofs);
1469 	*cs++ = upper_32_bits(src_ofs);
1470 	if (GRAPHICS_VERx100(xe) >= 2000)
1471 		*cs++ = FIELD_PREP(XE2_MEM_SET_MOCS_INDEX_MASK, gt->mocs.uc_index);
1472 	else
1473 		*cs++ = FIELD_PREP(PVC_MEM_SET_MOCS_INDEX_MASK, gt->mocs.uc_index);
1474 
1475 	xe_gt_assert(gt, cs - bb->cs == len + bb->len);
1476 
1477 	bb->len += len;
1478 }
1479 
1480 static void emit_clear_main_copy(struct xe_gt *gt, struct xe_bb *bb,
1481 				 u64 src_ofs, u32 size, u32 pitch, bool is_vram)
1482 {
1483 	struct xe_device *xe = gt_to_xe(gt);
1484 	u32 *cs = bb->cs + bb->len;
1485 	u32 len = XY_FAST_COLOR_BLT_DW;
1486 
1487 	if (GRAPHICS_VERx100(xe) < 1250)
1488 		len = 11;
1489 
1490 	*cs++ = XY_FAST_COLOR_BLT_CMD | XY_FAST_COLOR_BLT_DEPTH_32 |
1491 		(len - 2);
1492 	if (GRAPHICS_VERx100(xe) >= 2000)
1493 		*cs++ = FIELD_PREP(XE2_XY_FAST_COLOR_BLT_MOCS_INDEX_MASK, gt->mocs.uc_index) |
1494 			(pitch - 1);
1495 	else
1496 		*cs++ = FIELD_PREP(XY_FAST_COLOR_BLT_MOCS_MASK, gt->mocs.uc_index) |
1497 			(pitch - 1);
1498 	*cs++ = 0;
1499 	*cs++ = (size / pitch) << 16 | pitch / 4;
1500 	*cs++ = lower_32_bits(src_ofs);
1501 	*cs++ = upper_32_bits(src_ofs);
1502 	*cs++ = (is_vram ? 0x0 : 0x1) <<  XY_FAST_COLOR_BLT_MEM_TYPE_SHIFT;
1503 	*cs++ = 0;
1504 	*cs++ = 0;
1505 	*cs++ = 0;
1506 	*cs++ = 0;
1507 
1508 	if (len > 11) {
1509 		*cs++ = 0;
1510 		*cs++ = 0;
1511 		*cs++ = 0;
1512 		*cs++ = 0;
1513 		*cs++ = 0;
1514 	}
1515 
1516 	xe_gt_assert(gt, cs - bb->cs == len + bb->len);
1517 
1518 	bb->len += len;
1519 }
1520 
1521 static bool has_service_copy_support(struct xe_gt *gt)
1522 {
1523 	/*
1524 	 * What we care about is whether the architecture was designed with
1525 	 * service copy functionality (specifically the new MEM_SET / MEM_COPY
1526 	 * instructions) so check the architectural engine list rather than the
1527 	 * actual list since these instructions are usable on BCS0 even if
1528 	 * all of the actual service copy engines (BCS1-BCS8) have been fused
1529 	 * off.
1530 	 */
1531 	return gt->info.engine_mask & GENMASK(XE_HW_ENGINE_BCS8,
1532 					      XE_HW_ENGINE_BCS1);
1533 }
1534 
1535 static u32 emit_clear_cmd_len(struct xe_gt *gt)
1536 {
1537 	if (has_service_copy_support(gt))
1538 		return PVC_MEM_SET_CMD_LEN_DW;
1539 	else
1540 		return XY_FAST_COLOR_BLT_DW;
1541 }
1542 
1543 static void emit_clear(struct xe_gt *gt, struct xe_bb *bb, u64 src_ofs,
1544 		       u32 size, u32 pitch, bool is_vram)
1545 {
1546 	if (has_service_copy_support(gt))
1547 		emit_clear_link_copy(gt, bb, src_ofs, size, pitch);
1548 	else
1549 		emit_clear_main_copy(gt, bb, src_ofs, size, pitch,
1550 				     is_vram);
1551 }
1552 
1553 /**
1554  * xe_migrate_clear() - Copy content of TTM resources.
1555  * @m: The migration context.
1556  * @bo: The buffer object @dst is currently bound to.
1557  * @dst: The dst TTM resource to be cleared.
1558  * @clear_flags: flags to specify which data to clear: CCS, BO, or both.
1559  *
1560  * Clear the contents of @dst to zero when XE_MIGRATE_CLEAR_FLAG_BO_DATA is set.
1561  * On flat CCS devices, the CCS metadata is cleared to zero with XE_MIGRATE_CLEAR_FLAG_CCS_DATA.
1562  * Set XE_MIGRATE_CLEAR_FLAG_FULL to clear bo as well as CCS metadata.
1563  * TODO: Eliminate the @bo argument.
1564  *
1565  * Return: Pointer to a dma_fence representing the last clear batch, or
1566  * an error pointer on failure. If there is a failure, any clear operation
1567  * started by the function call has been synced.
1568  */
1569 struct dma_fence *xe_migrate_clear(struct xe_migrate *m,
1570 				   struct xe_bo *bo,
1571 				   struct ttm_resource *dst,
1572 				   u32 clear_flags)
1573 {
1574 	bool clear_vram = mem_type_is_vram(dst->mem_type);
1575 	bool clear_bo_data = XE_MIGRATE_CLEAR_FLAG_BO_DATA & clear_flags;
1576 	bool clear_ccs = XE_MIGRATE_CLEAR_FLAG_CCS_DATA & clear_flags;
1577 	struct xe_gt *gt = m->tile->primary_gt;
1578 	struct xe_device *xe = gt_to_xe(gt);
1579 	bool clear_only_system_ccs = false;
1580 	struct dma_fence *fence = NULL;
1581 	u64 size = xe_bo_size(bo);
1582 	struct xe_res_cursor src_it;
1583 	struct ttm_resource *src = dst;
1584 	int err;
1585 
1586 	if (WARN_ON(!clear_bo_data && !clear_ccs))
1587 		return NULL;
1588 
1589 	if (!clear_bo_data && clear_ccs && !IS_DGFX(xe))
1590 		clear_only_system_ccs = true;
1591 
1592 	if (!clear_vram)
1593 		xe_res_first_sg(xe_bo_sg(bo), 0, xe_bo_size(bo), &src_it);
1594 	else
1595 		xe_res_first(src, 0, xe_bo_size(bo), &src_it);
1596 
1597 	while (size) {
1598 		u64 clear_L0_ofs;
1599 		u32 clear_L0_pt;
1600 		u32 flush_flags = 0;
1601 		u64 clear_L0;
1602 		struct xe_sched_job *job;
1603 		struct xe_bb *bb;
1604 		u32 batch_size, update_idx;
1605 		u32 pte_flags;
1606 
1607 		bool usm = xe->info.has_usm;
1608 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1609 
1610 		clear_L0 = xe_migrate_res_sizes(m, &src_it);
1611 
1612 		/* Calculate final sizes and batch size.. */
1613 		pte_flags = clear_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
1614 		batch_size = 1 +
1615 			pte_update_size(m, pte_flags, src, &src_it,
1616 					&clear_L0, &clear_L0_ofs, &clear_L0_pt,
1617 					clear_bo_data ? emit_clear_cmd_len(gt) : 0, 0,
1618 					avail_pts);
1619 
1620 		if (xe_migrate_needs_ccs_emit(xe))
1621 			batch_size += EMIT_COPY_CCS_DW;
1622 
1623 		/* Clear commands */
1624 
1625 		if (WARN_ON_ONCE(!clear_L0))
1626 			break;
1627 
1628 		bb = xe_bb_new(gt, batch_size, usm);
1629 		if (IS_ERR(bb)) {
1630 			err = PTR_ERR(bb);
1631 			goto err_sync;
1632 		}
1633 
1634 		size -= clear_L0;
1635 		/* Preemption is enabled again by the ring ops. */
1636 		if (clear_vram && xe_migrate_allow_identity(clear_L0, &src_it)) {
1637 			xe_res_next(&src_it, clear_L0);
1638 		} else {
1639 			emit_pte(m, bb, clear_L0_pt, clear_vram,
1640 				 clear_only_system_ccs, &src_it, clear_L0, dst);
1641 			flush_flags |= MI_INVALIDATE_TLB;
1642 		}
1643 
1644 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
1645 		update_idx = bb->len;
1646 
1647 		if (clear_bo_data)
1648 			emit_clear(gt, bb, clear_L0_ofs, clear_L0, XE_PAGE_SIZE, clear_vram);
1649 
1650 		if (xe_migrate_needs_ccs_emit(xe)) {
1651 			emit_copy_ccs(gt, bb, clear_L0_ofs, true,
1652 				      m->cleared_mem_ofs, false, clear_L0);
1653 			flush_flags |= MI_FLUSH_DW_CCS;
1654 		}
1655 
1656 		job = xe_bb_create_migration_job(m->q, bb,
1657 						 xe_migrate_batch_base(m, usm),
1658 						 update_idx);
1659 		if (IS_ERR(job)) {
1660 			err = PTR_ERR(job);
1661 			goto err;
1662 		}
1663 
1664 		xe_sched_job_add_migrate_flush(job, flush_flags);
1665 		if (!fence) {
1666 			/*
1667 			 * There can't be anything userspace related at this
1668 			 * point, so we just need to respect any potential move
1669 			 * fences, which are always tracked as
1670 			 * DMA_RESV_USAGE_KERNEL.
1671 			 */
1672 			err = xe_sched_job_add_deps(job, bo->ttm.base.resv,
1673 						    DMA_RESV_USAGE_KERNEL);
1674 			if (err)
1675 				goto err_job;
1676 		}
1677 
1678 		mutex_lock(&m->job_mutex);
1679 		xe_sched_job_arm(job);
1680 		dma_fence_put(fence);
1681 		fence = dma_fence_get(&job->drm.s_fence->finished);
1682 		xe_sched_job_push(job);
1683 
1684 		dma_fence_put(m->fence);
1685 		m->fence = dma_fence_get(fence);
1686 
1687 		mutex_unlock(&m->job_mutex);
1688 
1689 		xe_bb_free(bb, fence);
1690 		continue;
1691 
1692 err_job:
1693 		xe_sched_job_put(job);
1694 err:
1695 		xe_bb_free(bb, NULL);
1696 err_sync:
1697 		/* Sync partial copies if any. FIXME: job_mutex? */
1698 		if (fence) {
1699 			dma_fence_wait(fence, false);
1700 			dma_fence_put(fence);
1701 		}
1702 
1703 		return ERR_PTR(err);
1704 	}
1705 
1706 	if (clear_ccs)
1707 		bo->ccs_cleared = true;
1708 
1709 	return fence;
1710 }
1711 
1712 static void write_pgtable(struct xe_tile *tile, struct xe_bb *bb, u64 ppgtt_ofs,
1713 			  const struct xe_vm_pgtable_update_op *pt_op,
1714 			  const struct xe_vm_pgtable_update *update,
1715 			  struct xe_migrate_pt_update *pt_update)
1716 {
1717 	const struct xe_migrate_pt_update_ops *ops = pt_update->ops;
1718 	u32 chunk;
1719 	u32 ofs = update->ofs, size = update->qwords;
1720 
1721 	/*
1722 	 * If we have 512 entries (max), we would populate it ourselves,
1723 	 * and update the PDE above it to the new pointer.
1724 	 * The only time this can only happen if we have to update the top
1725 	 * PDE. This requires a BO that is almost vm->size big.
1726 	 *
1727 	 * This shouldn't be possible in practice.. might change when 16K
1728 	 * pages are used. Hence the assert.
1729 	 */
1730 	xe_tile_assert(tile, update->qwords < MAX_NUM_PTE);
1731 	if (!ppgtt_ofs)
1732 		ppgtt_ofs = xe_migrate_vram_ofs(tile_to_xe(tile),
1733 						xe_bo_addr(update->pt_bo, 0,
1734 							   XE_PAGE_SIZE), false);
1735 
1736 	do {
1737 		u64 addr = ppgtt_ofs + ofs * 8;
1738 
1739 		chunk = min(size, MAX_PTE_PER_SDI);
1740 
1741 		/* Ensure populatefn can do memset64 by aligning bb->cs */
1742 		if (!(bb->len & 1))
1743 			bb->cs[bb->len++] = MI_NOOP;
1744 
1745 		bb->cs[bb->len++] = MI_STORE_DATA_IMM | MI_SDI_NUM_QW(chunk);
1746 		bb->cs[bb->len++] = lower_32_bits(addr);
1747 		bb->cs[bb->len++] = upper_32_bits(addr);
1748 		if (pt_op->bind)
1749 			ops->populate(pt_update, tile, NULL, bb->cs + bb->len,
1750 				      ofs, chunk, update);
1751 		else
1752 			ops->clear(pt_update, tile, NULL, bb->cs + bb->len,
1753 				   ofs, chunk, update);
1754 
1755 		bb->len += chunk * 2;
1756 		ofs += chunk;
1757 		size -= chunk;
1758 	} while (size);
1759 }
1760 
1761 struct xe_vm *xe_migrate_get_vm(struct xe_migrate *m)
1762 {
1763 	return xe_vm_get(m->q->vm);
1764 }
1765 
1766 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
1767 struct migrate_test_params {
1768 	struct xe_test_priv base;
1769 	bool force_gpu;
1770 };
1771 
1772 #define to_migrate_test_params(_priv) \
1773 	container_of(_priv, struct migrate_test_params, base)
1774 #endif
1775 
1776 static struct dma_fence *
1777 xe_migrate_update_pgtables_cpu(struct xe_migrate *m,
1778 			       struct xe_migrate_pt_update *pt_update)
1779 {
1780 	XE_TEST_DECLARE(struct migrate_test_params *test =
1781 			to_migrate_test_params
1782 			(xe_cur_kunit_priv(XE_TEST_LIVE_MIGRATE));)
1783 	const struct xe_migrate_pt_update_ops *ops = pt_update->ops;
1784 	struct xe_vm *vm = pt_update->vops->vm;
1785 	struct xe_vm_pgtable_update_ops *pt_update_ops =
1786 		&pt_update->vops->pt_update_ops[pt_update->tile_id];
1787 	int err;
1788 	u32 i, j;
1789 
1790 	if (XE_TEST_ONLY(test && test->force_gpu))
1791 		return ERR_PTR(-ETIME);
1792 
1793 	if (ops->pre_commit) {
1794 		pt_update->job = NULL;
1795 		err = ops->pre_commit(pt_update);
1796 		if (err)
1797 			return ERR_PTR(err);
1798 	}
1799 
1800 	for (i = 0; i < pt_update_ops->num_ops; ++i) {
1801 		const struct xe_vm_pgtable_update_op *pt_op =
1802 			&pt_update_ops->ops[i];
1803 
1804 		for (j = 0; j < pt_op->num_entries; j++) {
1805 			const struct xe_vm_pgtable_update *update =
1806 				&pt_op->entries[j];
1807 
1808 			if (pt_op->bind)
1809 				ops->populate(pt_update, m->tile,
1810 					      &update->pt_bo->vmap, NULL,
1811 					      update->ofs, update->qwords,
1812 					      update);
1813 			else
1814 				ops->clear(pt_update, m->tile,
1815 					   &update->pt_bo->vmap, NULL,
1816 					   update->ofs, update->qwords, update);
1817 		}
1818 	}
1819 
1820 	trace_xe_vm_cpu_bind(vm);
1821 	xe_device_wmb(vm->xe);
1822 
1823 	return dma_fence_get_stub();
1824 }
1825 
1826 static struct dma_fence *
1827 __xe_migrate_update_pgtables(struct xe_migrate *m,
1828 			     struct xe_migrate_pt_update *pt_update,
1829 			     struct xe_vm_pgtable_update_ops *pt_update_ops)
1830 {
1831 	const struct xe_migrate_pt_update_ops *ops = pt_update->ops;
1832 	struct xe_tile *tile = m->tile;
1833 	struct xe_gt *gt = tile->primary_gt;
1834 	struct xe_device *xe = tile_to_xe(tile);
1835 	struct xe_sched_job *job;
1836 	struct dma_fence *fence;
1837 	struct drm_suballoc *sa_bo = NULL;
1838 	struct xe_bb *bb;
1839 	u32 i, j, batch_size = 0, ppgtt_ofs, update_idx, page_ofs = 0;
1840 	u32 num_updates = 0, current_update = 0;
1841 	u64 addr;
1842 	int err = 0;
1843 	bool is_migrate = pt_update_ops->q == m->q;
1844 	bool usm = is_migrate && xe->info.has_usm;
1845 
1846 	for (i = 0; i < pt_update_ops->num_ops; ++i) {
1847 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
1848 		struct xe_vm_pgtable_update *updates = pt_op->entries;
1849 
1850 		num_updates += pt_op->num_entries;
1851 		for (j = 0; j < pt_op->num_entries; ++j) {
1852 			u32 num_cmds = DIV_ROUND_UP(updates[j].qwords,
1853 						    MAX_PTE_PER_SDI);
1854 
1855 			/* align noop + MI_STORE_DATA_IMM cmd prefix */
1856 			batch_size += 4 * num_cmds + updates[j].qwords * 2;
1857 		}
1858 	}
1859 
1860 	/* fixed + PTE entries */
1861 	if (IS_DGFX(xe))
1862 		batch_size += 2;
1863 	else
1864 		batch_size += 6 * (num_updates / MAX_PTE_PER_SDI + 1) +
1865 			num_updates * 2;
1866 
1867 	bb = xe_bb_new(gt, batch_size, usm);
1868 	if (IS_ERR(bb))
1869 		return ERR_CAST(bb);
1870 
1871 	/* For sysmem PTE's, need to map them in our hole.. */
1872 	if (!IS_DGFX(xe)) {
1873 		u16 pat_index = xe->pat.idx[XE_CACHE_WB];
1874 		u32 ptes, ofs;
1875 
1876 		ppgtt_ofs = NUM_KERNEL_PDE - 1;
1877 		if (!is_migrate) {
1878 			u32 num_units = DIV_ROUND_UP(num_updates,
1879 						     NUM_VMUSA_WRITES_PER_UNIT);
1880 
1881 			if (num_units > m->vm_update_sa.size) {
1882 				err = -ENOBUFS;
1883 				goto err_bb;
1884 			}
1885 			sa_bo = drm_suballoc_new(&m->vm_update_sa, num_units,
1886 						 GFP_KERNEL, true, 0);
1887 			if (IS_ERR(sa_bo)) {
1888 				err = PTR_ERR(sa_bo);
1889 				goto err_bb;
1890 			}
1891 
1892 			ppgtt_ofs = NUM_KERNEL_PDE +
1893 				(drm_suballoc_soffset(sa_bo) /
1894 				 NUM_VMUSA_UNIT_PER_PAGE);
1895 			page_ofs = (drm_suballoc_soffset(sa_bo) %
1896 				    NUM_VMUSA_UNIT_PER_PAGE) *
1897 				VM_SA_UPDATE_UNIT_SIZE;
1898 		}
1899 
1900 		/* Map our PT's to gtt */
1901 		i = 0;
1902 		j = 0;
1903 		ptes = num_updates;
1904 		ofs = ppgtt_ofs * XE_PAGE_SIZE + page_ofs;
1905 		while (ptes) {
1906 			u32 chunk = min(MAX_PTE_PER_SDI, ptes);
1907 			u32 idx = 0;
1908 
1909 			bb->cs[bb->len++] = MI_STORE_DATA_IMM |
1910 				MI_SDI_NUM_QW(chunk);
1911 			bb->cs[bb->len++] = ofs;
1912 			bb->cs[bb->len++] = 0; /* upper_32_bits */
1913 
1914 			for (; i < pt_update_ops->num_ops; ++i) {
1915 				struct xe_vm_pgtable_update_op *pt_op =
1916 					&pt_update_ops->ops[i];
1917 				struct xe_vm_pgtable_update *updates = pt_op->entries;
1918 
1919 				for (; j < pt_op->num_entries; ++j, ++current_update, ++idx) {
1920 					struct xe_vm *vm = pt_update->vops->vm;
1921 					struct xe_bo *pt_bo = updates[j].pt_bo;
1922 
1923 					if (idx == chunk)
1924 						goto next_cmd;
1925 
1926 					xe_tile_assert(tile, xe_bo_size(pt_bo) == SZ_4K);
1927 
1928 					/* Map a PT at most once */
1929 					if (pt_bo->update_index < 0)
1930 						pt_bo->update_index = current_update;
1931 
1932 					addr = vm->pt_ops->pte_encode_bo(pt_bo, 0,
1933 									 pat_index, 0);
1934 					bb->cs[bb->len++] = lower_32_bits(addr);
1935 					bb->cs[bb->len++] = upper_32_bits(addr);
1936 				}
1937 
1938 				j = 0;
1939 			}
1940 
1941 next_cmd:
1942 			ptes -= chunk;
1943 			ofs += chunk * sizeof(u64);
1944 		}
1945 
1946 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
1947 		update_idx = bb->len;
1948 
1949 		addr = xe_migrate_vm_addr(ppgtt_ofs, 0) +
1950 			(page_ofs / sizeof(u64)) * XE_PAGE_SIZE;
1951 		for (i = 0; i < pt_update_ops->num_ops; ++i) {
1952 			struct xe_vm_pgtable_update_op *pt_op =
1953 				&pt_update_ops->ops[i];
1954 			struct xe_vm_pgtable_update *updates = pt_op->entries;
1955 
1956 			for (j = 0; j < pt_op->num_entries; ++j) {
1957 				struct xe_bo *pt_bo = updates[j].pt_bo;
1958 
1959 				write_pgtable(tile, bb, addr +
1960 					      pt_bo->update_index * XE_PAGE_SIZE,
1961 					      pt_op, &updates[j], pt_update);
1962 			}
1963 		}
1964 	} else {
1965 		/* phys pages, no preamble required */
1966 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
1967 		update_idx = bb->len;
1968 
1969 		for (i = 0; i < pt_update_ops->num_ops; ++i) {
1970 			struct xe_vm_pgtable_update_op *pt_op =
1971 				&pt_update_ops->ops[i];
1972 			struct xe_vm_pgtable_update *updates = pt_op->entries;
1973 
1974 			for (j = 0; j < pt_op->num_entries; ++j)
1975 				write_pgtable(tile, bb, 0, pt_op, &updates[j],
1976 					      pt_update);
1977 		}
1978 	}
1979 
1980 	job = xe_bb_create_migration_job(pt_update_ops->q, bb,
1981 					 xe_migrate_batch_base(m, usm),
1982 					 update_idx);
1983 	if (IS_ERR(job)) {
1984 		err = PTR_ERR(job);
1985 		goto err_sa;
1986 	}
1987 
1988 	xe_sched_job_add_migrate_flush(job, MI_INVALIDATE_TLB);
1989 
1990 	if (ops->pre_commit) {
1991 		pt_update->job = job;
1992 		err = ops->pre_commit(pt_update);
1993 		if (err)
1994 			goto err_job;
1995 	}
1996 	if (is_migrate)
1997 		mutex_lock(&m->job_mutex);
1998 
1999 	xe_sched_job_arm(job);
2000 	fence = dma_fence_get(&job->drm.s_fence->finished);
2001 	xe_sched_job_push(job);
2002 
2003 	if (is_migrate)
2004 		mutex_unlock(&m->job_mutex);
2005 
2006 	xe_bb_free(bb, fence);
2007 	drm_suballoc_free(sa_bo, fence);
2008 
2009 	return fence;
2010 
2011 err_job:
2012 	xe_sched_job_put(job);
2013 err_sa:
2014 	drm_suballoc_free(sa_bo, NULL);
2015 err_bb:
2016 	xe_bb_free(bb, NULL);
2017 	return ERR_PTR(err);
2018 }
2019 
2020 /**
2021  * xe_migrate_update_pgtables() - Pipelined page-table update
2022  * @m: The migrate context.
2023  * @pt_update: PT update arguments
2024  *
2025  * Perform a pipelined page-table update. The update descriptors are typically
2026  * built under the same lock critical section as a call to this function. If
2027  * using the default engine for the updates, they will be performed in the
2028  * order they grab the job_mutex. If different engines are used, external
2029  * synchronization is needed for overlapping updates to maintain page-table
2030  * consistency. Note that the meaning of "overlapping" is that the updates
2031  * touch the same page-table, which might be a higher-level page-directory.
2032  * If no pipelining is needed, then updates may be performed by the cpu.
2033  *
2034  * Return: A dma_fence that, when signaled, indicates the update completion.
2035  */
2036 struct dma_fence *
2037 xe_migrate_update_pgtables(struct xe_migrate *m,
2038 			   struct xe_migrate_pt_update *pt_update)
2039 
2040 {
2041 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2042 		&pt_update->vops->pt_update_ops[pt_update->tile_id];
2043 	struct dma_fence *fence;
2044 
2045 	fence =  xe_migrate_update_pgtables_cpu(m, pt_update);
2046 
2047 	/* -ETIME indicates a job is needed, anything else is legit error */
2048 	if (!IS_ERR(fence) || PTR_ERR(fence) != -ETIME)
2049 		return fence;
2050 
2051 	return __xe_migrate_update_pgtables(m, pt_update, pt_update_ops);
2052 }
2053 
2054 /**
2055  * xe_migrate_wait() - Complete all operations using the xe_migrate context
2056  * @m: Migrate context to wait for.
2057  *
2058  * Waits until the GPU no longer uses the migrate context's default engine
2059  * or its page-table objects. FIXME: What about separate page-table update
2060  * engines?
2061  */
2062 void xe_migrate_wait(struct xe_migrate *m)
2063 {
2064 	if (m->fence)
2065 		dma_fence_wait(m->fence, false);
2066 }
2067 
2068 static u32 pte_update_cmd_size(u64 size)
2069 {
2070 	u32 num_dword;
2071 	u64 entries = DIV_U64_ROUND_UP(size, XE_PAGE_SIZE);
2072 
2073 	XE_WARN_ON(size > MAX_PREEMPTDISABLE_TRANSFER);
2074 
2075 	/*
2076 	 * MI_STORE_DATA_IMM command is used to update page table. Each
2077 	 * instruction can update maximumly MAX_PTE_PER_SDI pte entries. To
2078 	 * update n (n <= MAX_PTE_PER_SDI) pte entries, we need:
2079 	 *
2080 	 * - 1 dword for the MI_STORE_DATA_IMM command header (opcode etc)
2081 	 * - 2 dword for the page table's physical location
2082 	 * - 2*n dword for value of pte to fill (each pte entry is 2 dwords)
2083 	 */
2084 	num_dword = (1 + 2) * DIV_U64_ROUND_UP(entries, MAX_PTE_PER_SDI);
2085 	num_dword += entries * 2;
2086 
2087 	return num_dword;
2088 }
2089 
2090 static void build_pt_update_batch_sram(struct xe_migrate *m,
2091 				       struct xe_bb *bb, u32 pt_offset,
2092 				       struct drm_pagemap_addr *sram_addr,
2093 				       u32 size, int level)
2094 {
2095 	u16 pat_index = tile_to_xe(m->tile)->pat.idx[XE_CACHE_WB];
2096 	u64 gpu_page_size = 0x1ull << xe_pt_shift(level);
2097 	u32 ptes;
2098 	int i = 0;
2099 
2100 	xe_tile_assert(m->tile, PAGE_ALIGNED(size));
2101 
2102 	ptes = DIV_ROUND_UP(size, gpu_page_size);
2103 	while (ptes) {
2104 		u32 chunk = min(MAX_PTE_PER_SDI, ptes);
2105 
2106 		if (!level)
2107 			chunk = ALIGN_DOWN(chunk, PAGE_SIZE / XE_PAGE_SIZE);
2108 
2109 		bb->cs[bb->len++] = MI_STORE_DATA_IMM | MI_SDI_NUM_QW(chunk);
2110 		bb->cs[bb->len++] = pt_offset;
2111 		bb->cs[bb->len++] = 0;
2112 
2113 		pt_offset += chunk * 8;
2114 		ptes -= chunk;
2115 
2116 		while (chunk--) {
2117 			u64 addr = sram_addr[i].addr;
2118 			u64 pte;
2119 
2120 			xe_tile_assert(m->tile, sram_addr[i].proto ==
2121 				       DRM_INTERCONNECT_SYSTEM ||
2122 				       sram_addr[i].proto == XE_INTERCONNECT_P2P);
2123 			xe_tile_assert(m->tile, addr);
2124 			xe_tile_assert(m->tile, PAGE_ALIGNED(addr));
2125 
2126 again:
2127 			pte = m->q->vm->pt_ops->pte_encode_addr(m->tile->xe,
2128 								addr, pat_index,
2129 								level, false, 0);
2130 			bb->cs[bb->len++] = lower_32_bits(pte);
2131 			bb->cs[bb->len++] = upper_32_bits(pte);
2132 
2133 			if (gpu_page_size < PAGE_SIZE) {
2134 				addr += XE_PAGE_SIZE;
2135 				if (!PAGE_ALIGNED(addr)) {
2136 					chunk--;
2137 					goto again;
2138 				}
2139 				i++;
2140 			} else {
2141 				i += gpu_page_size / PAGE_SIZE;
2142 			}
2143 		}
2144 	}
2145 }
2146 
2147 static bool xe_migrate_vram_use_pde(struct drm_pagemap_addr *sram_addr,
2148 				    unsigned long size)
2149 {
2150 	u32 large_size = (0x1 << xe_pt_shift(1));
2151 	unsigned long i, incr = large_size / PAGE_SIZE;
2152 
2153 	for (i = 0; i < DIV_ROUND_UP(size, PAGE_SIZE); i += incr)
2154 		if (PAGE_SIZE << sram_addr[i].order != large_size)
2155 			return false;
2156 
2157 	return true;
2158 }
2159 
2160 #define XE_CACHELINE_BYTES	64ull
2161 #define XE_CACHELINE_MASK	(XE_CACHELINE_BYTES - 1)
2162 
2163 static u32 xe_migrate_copy_pitch(struct xe_device *xe, u32 len)
2164 {
2165 	u32 pitch;
2166 
2167 	if (IS_ALIGNED(len, PAGE_SIZE))
2168 		pitch = PAGE_SIZE;
2169 	else if (IS_ALIGNED(len, SZ_4K))
2170 		pitch = SZ_4K;
2171 	else if (IS_ALIGNED(len, SZ_256))
2172 		pitch = SZ_256;
2173 	else if (IS_ALIGNED(len, 4))
2174 		pitch = 4;
2175 	else
2176 		pitch = 1;
2177 
2178 	xe_assert(xe, pitch > 1 || xe->info.has_mem_copy_instr);
2179 	return pitch;
2180 }
2181 
2182 static struct dma_fence *xe_migrate_vram(struct xe_migrate *m,
2183 					 unsigned long len,
2184 					 unsigned long sram_offset,
2185 					 struct drm_pagemap_addr *sram_addr,
2186 					 u64 vram_addr,
2187 					 struct dma_fence *deps,
2188 					 const enum xe_migrate_copy_dir dir)
2189 {
2190 	struct xe_gt *gt = m->tile->primary_gt;
2191 	struct xe_device *xe = gt_to_xe(gt);
2192 	bool use_usm_batch = xe->info.has_usm;
2193 	struct dma_fence *fence = NULL;
2194 	u32 batch_size = 1;
2195 	u64 src_L0_ofs, dst_L0_ofs;
2196 	struct xe_sched_job *job;
2197 	struct xe_bb *bb;
2198 	u32 update_idx, pt_slot = 0;
2199 	unsigned long npages = DIV_ROUND_UP(len + sram_offset, PAGE_SIZE);
2200 	unsigned int pitch = xe_migrate_copy_pitch(xe, len);
2201 	int err;
2202 	unsigned long i, j;
2203 	bool use_pde = xe_migrate_vram_use_pde(sram_addr, len + sram_offset);
2204 
2205 	if (!xe->info.has_mem_copy_instr &&
2206 	    drm_WARN_ON(&xe->drm,
2207 			(!IS_ALIGNED(len, pitch)) || (sram_offset | vram_addr) & XE_CACHELINE_MASK))
2208 		return ERR_PTR(-EOPNOTSUPP);
2209 
2210 	xe_assert(xe, npages * PAGE_SIZE <= MAX_PREEMPTDISABLE_TRANSFER);
2211 
2212 	batch_size += pte_update_cmd_size(npages << PAGE_SHIFT);
2213 	batch_size += EMIT_COPY_DW;
2214 
2215 	bb = xe_bb_new(gt, batch_size, use_usm_batch);
2216 	if (IS_ERR(bb)) {
2217 		err = PTR_ERR(bb);
2218 		return ERR_PTR(err);
2219 	}
2220 
2221 	/*
2222 	 * If the order of a struct drm_pagemap_addr entry is greater than 0,
2223 	 * the entry is populated by GPU pagemap but subsequent entries within
2224 	 * the range of that order are not populated.
2225 	 * build_pt_update_batch_sram() expects a fully populated array of
2226 	 * struct drm_pagemap_addr. Ensure this is the case even with higher
2227 	 * orders.
2228 	 */
2229 	for (i = 0; !use_pde && i < npages;) {
2230 		unsigned int order = sram_addr[i].order;
2231 
2232 		for (j = 1; j < NR_PAGES(order) && i + j < npages; j++)
2233 			if (!sram_addr[i + j].addr)
2234 				sram_addr[i + j].addr = sram_addr[i].addr + j * PAGE_SIZE;
2235 
2236 		i += NR_PAGES(order);
2237 	}
2238 
2239 	if (use_pde)
2240 		build_pt_update_batch_sram(m, bb, m->large_page_copy_pdes,
2241 					   sram_addr, npages << PAGE_SHIFT, 1);
2242 	else
2243 		build_pt_update_batch_sram(m, bb, pt_slot * XE_PAGE_SIZE,
2244 					   sram_addr, npages << PAGE_SHIFT, 0);
2245 
2246 	if (dir == XE_MIGRATE_COPY_TO_VRAM) {
2247 		if (use_pde)
2248 			src_L0_ofs = m->large_page_copy_ofs + sram_offset;
2249 		else
2250 			src_L0_ofs = xe_migrate_vm_addr(pt_slot, 0) + sram_offset;
2251 		dst_L0_ofs = xe_migrate_vram_ofs(xe, vram_addr, false);
2252 
2253 	} else {
2254 		src_L0_ofs = xe_migrate_vram_ofs(xe, vram_addr, false);
2255 		if (use_pde)
2256 			dst_L0_ofs = m->large_page_copy_ofs + sram_offset;
2257 		else
2258 			dst_L0_ofs = xe_migrate_vm_addr(pt_slot, 0) + sram_offset;
2259 	}
2260 
2261 	bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
2262 	update_idx = bb->len;
2263 
2264 	emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, len, pitch);
2265 
2266 	job = xe_bb_create_migration_job(m->q, bb,
2267 					 xe_migrate_batch_base(m, use_usm_batch),
2268 					 update_idx);
2269 	if (IS_ERR(job)) {
2270 		err = PTR_ERR(job);
2271 		goto err;
2272 	}
2273 
2274 	xe_sched_job_add_migrate_flush(job, MI_INVALIDATE_TLB);
2275 
2276 	if (deps && !dma_fence_is_signaled(deps)) {
2277 		dma_fence_get(deps);
2278 		err = drm_sched_job_add_dependency(&job->drm, deps);
2279 		if (err)
2280 			dma_fence_wait(deps, false);
2281 		err = 0;
2282 	}
2283 
2284 	mutex_lock(&m->job_mutex);
2285 	xe_sched_job_arm(job);
2286 	fence = dma_fence_get(&job->drm.s_fence->finished);
2287 	xe_sched_job_push(job);
2288 
2289 	dma_fence_put(m->fence);
2290 	m->fence = dma_fence_get(fence);
2291 	mutex_unlock(&m->job_mutex);
2292 
2293 	xe_bb_free(bb, fence);
2294 
2295 	return fence;
2296 
2297 err:
2298 	xe_bb_free(bb, NULL);
2299 
2300 	return ERR_PTR(err);
2301 }
2302 
2303 /**
2304  * xe_migrate_to_vram() - Migrate to VRAM
2305  * @m: The migration context.
2306  * @npages: Number of pages to migrate.
2307  * @src_addr: Array of DMA information (source of migrate)
2308  * @dst_addr: Device physical address of VRAM (destination of migrate)
2309  * @deps: struct dma_fence representing the dependencies that need
2310  * to be signaled before migration.
2311  *
2312  * Copy from an array dma addresses to a VRAM device physical address
2313  *
2314  * Return: dma fence for migrate to signal completion on success, ERR_PTR on
2315  * failure
2316  */
2317 struct dma_fence *xe_migrate_to_vram(struct xe_migrate *m,
2318 				     unsigned long npages,
2319 				     struct drm_pagemap_addr *src_addr,
2320 				     u64 dst_addr,
2321 				     struct dma_fence *deps)
2322 {
2323 	return xe_migrate_vram(m, npages * PAGE_SIZE, 0, src_addr, dst_addr,
2324 			       deps, XE_MIGRATE_COPY_TO_VRAM);
2325 }
2326 
2327 /**
2328  * xe_migrate_from_vram() - Migrate from VRAM
2329  * @m: The migration context.
2330  * @npages: Number of pages to migrate.
2331  * @src_addr: Device physical address of VRAM (source of migrate)
2332  * @dst_addr: Array of DMA information (destination of migrate)
2333  * @deps: struct dma_fence representing the dependencies that need
2334  * to be signaled before migration.
2335  *
2336  * Copy from a VRAM device physical address to an array dma addresses
2337  *
2338  * Return: dma fence for migrate to signal completion on success, ERR_PTR on
2339  * failure
2340  */
2341 struct dma_fence *xe_migrate_from_vram(struct xe_migrate *m,
2342 				       unsigned long npages,
2343 				       u64 src_addr,
2344 				       struct drm_pagemap_addr *dst_addr,
2345 				       struct dma_fence *deps)
2346 {
2347 	return xe_migrate_vram(m, npages * PAGE_SIZE, 0, dst_addr, src_addr,
2348 			       deps, XE_MIGRATE_COPY_TO_SRAM);
2349 }
2350 
2351 static void xe_migrate_dma_unmap(struct xe_device *xe,
2352 				 struct drm_pagemap_addr *pagemap_addr,
2353 				 int len, int write)
2354 {
2355 	unsigned long i, npages = DIV_ROUND_UP(len, PAGE_SIZE);
2356 
2357 	for (i = 0; i < npages; ++i) {
2358 		if (!pagemap_addr[i].addr)
2359 			break;
2360 
2361 		dma_unmap_page(xe->drm.dev, pagemap_addr[i].addr, PAGE_SIZE,
2362 			       write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
2363 	}
2364 	kfree(pagemap_addr);
2365 }
2366 
2367 static struct drm_pagemap_addr *xe_migrate_dma_map(struct xe_device *xe,
2368 						   void *buf, int len,
2369 						   int write)
2370 {
2371 	struct drm_pagemap_addr *pagemap_addr;
2372 	unsigned long i, npages = DIV_ROUND_UP(len, PAGE_SIZE);
2373 
2374 	pagemap_addr = kzalloc_objs(*pagemap_addr, npages);
2375 	if (!pagemap_addr)
2376 		return ERR_PTR(-ENOMEM);
2377 
2378 	for (i = 0; i < npages; ++i) {
2379 		dma_addr_t addr;
2380 		struct page *page;
2381 		enum dma_data_direction dir = write ? DMA_TO_DEVICE :
2382 						      DMA_FROM_DEVICE;
2383 
2384 		if (is_vmalloc_addr(buf))
2385 			page = vmalloc_to_page(buf);
2386 		else
2387 			page = virt_to_page(buf);
2388 
2389 		addr = dma_map_page(xe->drm.dev, page, 0, PAGE_SIZE, dir);
2390 		if (dma_mapping_error(xe->drm.dev, addr))
2391 			goto err_fault;
2392 
2393 		pagemap_addr[i] =
2394 			drm_pagemap_addr_encode(addr,
2395 						DRM_INTERCONNECT_SYSTEM,
2396 						0, dir);
2397 		buf += PAGE_SIZE;
2398 	}
2399 
2400 	return pagemap_addr;
2401 
2402 err_fault:
2403 	xe_migrate_dma_unmap(xe, pagemap_addr, len, write);
2404 	return ERR_PTR(-EFAULT);
2405 }
2406 
2407 /**
2408  * xe_migrate_access_memory - Access memory of a BO via GPU
2409  *
2410  * @m: The migration context.
2411  * @bo: buffer object
2412  * @offset: access offset into buffer object
2413  * @buf: pointer to caller memory to read into or write from
2414  * @len: length of access
2415  * @write: write access
2416  *
2417  * Access memory of a BO via GPU either reading in or writing from a passed in
2418  * pointer. Pointer is dma mapped for GPU access and GPU commands are issued to
2419  * read to or write from pointer.
2420  *
2421  * Returns:
2422  * 0 if successful, negative error code on failure.
2423  */
2424 int xe_migrate_access_memory(struct xe_migrate *m, struct xe_bo *bo,
2425 			     unsigned long offset, void *buf, int len,
2426 			     int write)
2427 {
2428 	struct xe_tile *tile = m->tile;
2429 	struct xe_device *xe = tile_to_xe(tile);
2430 	struct xe_res_cursor cursor;
2431 	struct dma_fence *fence = NULL;
2432 	struct drm_pagemap_addr *pagemap_addr;
2433 	unsigned long page_offset = (unsigned long)buf & ~PAGE_MASK;
2434 	int bytes_left = len, current_page = 0;
2435 	void *orig_buf = buf;
2436 
2437 	xe_bo_assert_held(bo);
2438 
2439 	/* Use bounce buffer for small access and unaligned access */
2440 	if (!xe->info.has_mem_copy_instr &&
2441 	    (!IS_ALIGNED(len, 4) ||
2442 	     !IS_ALIGNED(page_offset, XE_CACHELINE_BYTES) ||
2443 	     !IS_ALIGNED(offset, XE_CACHELINE_BYTES))) {
2444 		int buf_offset = 0;
2445 		void *bounce;
2446 		int err;
2447 
2448 		BUILD_BUG_ON(!is_power_of_2(XE_CACHELINE_BYTES));
2449 		bounce = kmalloc(XE_CACHELINE_BYTES, GFP_KERNEL);
2450 		if (!bounce)
2451 			return -ENOMEM;
2452 
2453 		/*
2454 		 * Less than ideal for large unaligned access but this should be
2455 		 * fairly rare, can fixup if this becomes common.
2456 		 */
2457 		do {
2458 			int copy_bytes = min_t(int, bytes_left,
2459 					       XE_CACHELINE_BYTES -
2460 					       (offset & XE_CACHELINE_MASK));
2461 			int ptr_offset = offset & XE_CACHELINE_MASK;
2462 
2463 			err = xe_migrate_access_memory(m, bo,
2464 						       offset &
2465 						       ~XE_CACHELINE_MASK,
2466 						       bounce,
2467 						       XE_CACHELINE_BYTES, 0);
2468 			if (err)
2469 				break;
2470 
2471 			if (write) {
2472 				memcpy(bounce + ptr_offset, buf + buf_offset, copy_bytes);
2473 
2474 				err = xe_migrate_access_memory(m, bo,
2475 							       offset & ~XE_CACHELINE_MASK,
2476 							       bounce,
2477 							       XE_CACHELINE_BYTES, write);
2478 				if (err)
2479 					break;
2480 			} else {
2481 				memcpy(buf + buf_offset, bounce + ptr_offset,
2482 				       copy_bytes);
2483 			}
2484 
2485 			bytes_left -= copy_bytes;
2486 			buf_offset += copy_bytes;
2487 			offset += copy_bytes;
2488 		} while (bytes_left);
2489 
2490 		kfree(bounce);
2491 		return err;
2492 	}
2493 
2494 	pagemap_addr = xe_migrate_dma_map(xe, buf, len + page_offset, write);
2495 	if (IS_ERR(pagemap_addr))
2496 		return PTR_ERR(pagemap_addr);
2497 
2498 	xe_res_first(bo->ttm.resource, offset, xe_bo_size(bo) - offset, &cursor);
2499 
2500 	do {
2501 		struct dma_fence *__fence;
2502 		u64 vram_addr = vram_region_gpu_offset(bo->ttm.resource) +
2503 			cursor.start;
2504 		int current_bytes;
2505 		u32 pitch;
2506 
2507 		if (cursor.size > MAX_PREEMPTDISABLE_TRANSFER)
2508 			current_bytes = min_t(int, bytes_left,
2509 					      MAX_PREEMPTDISABLE_TRANSFER);
2510 		else
2511 			current_bytes = min_t(int, bytes_left, cursor.size);
2512 
2513 		pitch = xe_migrate_copy_pitch(xe, current_bytes);
2514 		if (xe->info.has_mem_copy_instr)
2515 			current_bytes = min_t(int, current_bytes, U16_MAX * pitch);
2516 		else
2517 			current_bytes = min_t(int, current_bytes,
2518 					      round_down(S16_MAX * pitch,
2519 							 XE_CACHELINE_BYTES));
2520 
2521 		__fence = xe_migrate_vram(m, current_bytes,
2522 					  (unsigned long)buf & ~PAGE_MASK,
2523 					  &pagemap_addr[current_page],
2524 					  vram_addr, NULL, write ?
2525 					  XE_MIGRATE_COPY_TO_VRAM :
2526 					  XE_MIGRATE_COPY_TO_SRAM);
2527 		if (IS_ERR(__fence)) {
2528 			if (fence) {
2529 				dma_fence_wait(fence, false);
2530 				dma_fence_put(fence);
2531 			}
2532 			fence = __fence;
2533 			goto out_err;
2534 		}
2535 
2536 		dma_fence_put(fence);
2537 		fence = __fence;
2538 
2539 		buf += current_bytes;
2540 		offset += current_bytes;
2541 		current_page = (int)(buf - orig_buf) / PAGE_SIZE;
2542 		bytes_left -= current_bytes;
2543 		if (bytes_left)
2544 			xe_res_next(&cursor, current_bytes);
2545 	} while (bytes_left);
2546 
2547 	dma_fence_wait(fence, false);
2548 	dma_fence_put(fence);
2549 
2550 out_err:
2551 	xe_migrate_dma_unmap(xe, pagemap_addr, len + page_offset, write);
2552 	return IS_ERR(fence) ? PTR_ERR(fence) : 0;
2553 }
2554 
2555 /**
2556  * xe_migrate_job_lock() - Lock migrate job lock
2557  * @m: The migration context.
2558  * @q: Queue associated with the operation which requires a lock
2559  *
2560  * Lock the migrate job lock if the queue is a migration queue, otherwise
2561  * assert the VM's dma-resv is held (user queue's have own locking).
2562  */
2563 void xe_migrate_job_lock(struct xe_migrate *m, struct xe_exec_queue *q)
2564 {
2565 	bool is_migrate = q == m->q;
2566 
2567 	if (is_migrate)
2568 		mutex_lock(&m->job_mutex);
2569 	else
2570 		xe_vm_assert_held(q->user_vm);	/* User queues VM's should be locked */
2571 }
2572 
2573 /**
2574  * xe_migrate_job_unlock() - Unlock migrate job lock
2575  * @m: The migration context.
2576  * @q: Queue associated with the operation which requires a lock
2577  *
2578  * Unlock the migrate job lock if the queue is a migration queue, otherwise
2579  * assert the VM's dma-resv is held (user queue's have own locking).
2580  */
2581 void xe_migrate_job_unlock(struct xe_migrate *m, struct xe_exec_queue *q)
2582 {
2583 	bool is_migrate = q == m->q;
2584 
2585 	if (is_migrate)
2586 		mutex_unlock(&m->job_mutex);
2587 	else
2588 		xe_vm_assert_held(q->user_vm);	/* User queues VM's should be locked */
2589 }
2590 
2591 #if IS_ENABLED(CONFIG_PROVE_LOCKING)
2592 /**
2593  * xe_migrate_job_lock_assert() - Assert migrate job lock held of queue
2594  * @q: Migrate queue
2595  */
2596 void xe_migrate_job_lock_assert(struct xe_exec_queue *q)
2597 {
2598 	struct xe_migrate *m = gt_to_tile(q->gt)->migrate;
2599 
2600 	xe_gt_assert(q->gt, q == m->q);
2601 	lockdep_assert_held(&m->job_mutex);
2602 }
2603 #endif
2604 
2605 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
2606 #include "tests/xe_migrate.c"
2607 #endif
2608