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