xref: /linux/drivers/gpu/drm/xe/xe_migrate.c (revision c27e360545373b7aee9862a5beef3b9fb3df0c25)
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  * @new_mem: The (not yet committed) destination resource @src_bo is being
1170  *          moved into; src_bo->ttm.resource is still the old resource.
1171  * @read_write : Creates BB commands for CCS read/write.
1172  *
1173  * Creates batch buffer instructions to copy CCS metadata from CCS pool to
1174  * memory and vice versa.
1175  *
1176  * This function should only be called for IGPU.
1177  *
1178  * Return: 0 if successful, negative error code on failure.
1179  */
1180 int xe_migrate_ccs_rw_copy(struct xe_tile *tile, struct xe_exec_queue *q,
1181 			   struct xe_bo *src_bo,
1182 			   struct ttm_resource *new_mem,
1183 			   enum xe_sriov_vf_ccs_rw_ctxs read_write)
1184 
1185 {
1186 	bool src_is_pltt = read_write == XE_SRIOV_VF_CCS_READ_CTX;
1187 	bool dst_is_pltt = read_write == XE_SRIOV_VF_CCS_WRITE_CTX;
1188 	struct ttm_resource *src = new_mem;
1189 	struct xe_migrate *m = tile->migrate;
1190 	struct xe_gt *gt = tile->primary_gt;
1191 	u32 batch_size, batch_size_allocated;
1192 	struct xe_device *xe = gt_to_xe(gt);
1193 	struct xe_res_cursor src_it, ccs_it;
1194 	struct xe_mem_pool *bb_pool;
1195 	struct xe_sriov_vf_ccs_ctx *ctx;
1196 	u64 size = xe_bo_size(src_bo);
1197 	struct xe_mem_pool_node *bb;
1198 	u64 src_L0, src_L0_ofs;
1199 	struct xe_bb xe_bb_tmp;
1200 	u32 src_L0_pt;
1201 	int err;
1202 
1203 	ctx = &xe->sriov.vf.ccs.contexts[read_write];
1204 
1205 	xe_res_first_sg(xe_bo_sg(src_bo), 0, size, &src_it);
1206 
1207 	xe_res_first_sg(xe_bo_sg(src_bo), xe_bo_ccs_pages_start(src_bo),
1208 			PAGE_ALIGN(xe_device_ccs_bytes(xe, size)),
1209 			&ccs_it);
1210 
1211 	/* Calculate Batch buffer size */
1212 	batch_size = 0;
1213 	while (size) {
1214 		batch_size += 10; /* Flush + ggtt addr + 2 NOP */
1215 		u64 ccs_ofs, ccs_size;
1216 		u32 ccs_pt;
1217 
1218 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1219 
1220 		src_L0 = min_t(u64, max_mem_transfer_per_pass(xe), size);
1221 
1222 		batch_size += pte_update_size(m, false, src, &src_it, &src_L0,
1223 					      &src_L0_ofs, &src_L0_pt, 0, 0,
1224 					      avail_pts);
1225 
1226 		ccs_size = xe_device_ccs_bytes(xe, src_L0);
1227 		batch_size += pte_update_size(m, 0, NULL, &ccs_it, &ccs_size, &ccs_ofs,
1228 					      &ccs_pt, 0, avail_pts, avail_pts);
1229 		xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
1230 
1231 		/* Add copy commands size here */
1232 		batch_size += EMIT_COPY_CCS_DW;
1233 
1234 		size -= src_L0;
1235 	}
1236 
1237 	bb = xe_mem_pool_alloc_node();
1238 	if (IS_ERR(bb))
1239 		return PTR_ERR(bb);
1240 
1241 	bb_pool = ctx->mem.ccs_bb_pool;
1242 	scoped_guard(mutex, xe_mem_pool_bo_swap_guard(bb_pool)) {
1243 		xe_mem_pool_swap_shadow_locked(bb_pool);
1244 
1245 		err = xe_mem_pool_insert_node(bb_pool, bb, batch_size * sizeof(u32));
1246 		if (err) {
1247 			xe_gt_err(gt, "BB allocation failed.\n");
1248 			kfree(bb);
1249 			return err;
1250 		}
1251 
1252 		batch_size_allocated = batch_size;
1253 		size = xe_bo_size(src_bo);
1254 		batch_size = 0;
1255 
1256 		xe_bb_tmp = (struct xe_bb){ .cs = xe_mem_pool_node_cpu_addr(bb), .len = 0 };
1257 		/*
1258 		 * Emit PTE and copy commands here.
1259 		 * The CCS copy command can only support limited size. If the size to be
1260 		 * copied is more than the limit, divide copy into chunks. So, calculate
1261 		 * sizes here again before copy command is emitted.
1262 		 */
1263 
1264 		while (size) {
1265 			batch_size += 10; /* Flush + ggtt addr + 2 NOP */
1266 			u32 flush_flags = 0;
1267 			u64 ccs_ofs, ccs_size;
1268 			u32 ccs_pt;
1269 
1270 			u32 avail_pts = max_mem_transfer_per_pass(xe) /
1271 					LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1272 
1273 			src_L0 = xe_migrate_res_sizes(m, &src_it);
1274 
1275 			batch_size += pte_update_size(m, false, src, &src_it, &src_L0,
1276 						      &src_L0_ofs, &src_L0_pt, 0, 0,
1277 						      avail_pts);
1278 
1279 			ccs_size = xe_device_ccs_bytes(xe, src_L0);
1280 			batch_size += pte_update_size(m, 0, NULL, &ccs_it, &ccs_size, &ccs_ofs,
1281 						      &ccs_pt, 0, avail_pts, avail_pts);
1282 			xe_assert(xe, IS_ALIGNED(ccs_it.start, PAGE_SIZE));
1283 			batch_size += EMIT_COPY_CCS_DW;
1284 
1285 			emit_pte(m, &xe_bb_tmp, src_L0_pt, false, true, &src_it, src_L0, src);
1286 
1287 			emit_pte(m, &xe_bb_tmp, ccs_pt, false, false, &ccs_it, ccs_size, src);
1288 
1289 			xe_bb_tmp.len = emit_flush_invalidate(xe_bb_tmp.cs, xe_bb_tmp.len,
1290 							      flush_flags);
1291 			flush_flags = xe_migrate_ccs_copy(m, &xe_bb_tmp, src_L0_ofs, src_is_pltt,
1292 							  src_L0_ofs, dst_is_pltt,
1293 							  src_L0, ccs_ofs, true);
1294 			xe_bb_tmp.len = emit_flush_invalidate(xe_bb_tmp.cs, xe_bb_tmp.len,
1295 							      flush_flags);
1296 
1297 			size -= src_L0;
1298 		}
1299 
1300 		xe_assert(xe, (batch_size_allocated == xe_bb_tmp.len));
1301 		xe_assert(xe, bb->sa_node.size == xe_bb_tmp.len * sizeof(u32));
1302 		src_bo->bb_ccs[read_write] = bb;
1303 
1304 		xe_sriov_vf_ccs_rw_update_bb_addr(ctx);
1305 		xe_mem_pool_sync_shadow_locked(bb);
1306 	}
1307 
1308 	return 0;
1309 }
1310 
1311 /**
1312  * xe_migrate_ccs_rw_copy_clear() - Clear the CCS read/write batch buffer
1313  * content.
1314  * @src_bo: The buffer object @src is currently bound to.
1315  * @read_write : Creates BB commands for CCS read/write.
1316  * @bound: Device is bound
1317  *
1318  * Directly clearing the BB lacks atomicity and can lead to undefined
1319  * behavior if the vCPU is halted mid-operation during the clearing
1320  * process. To avoid this issue, we use a shadow buffer object approach.
1321  *
1322  * First swap the SA BO address with the shadow BO, perform the clearing
1323  * operation on the BB, update the shadow BO in the ring buffer, then
1324  * sync the shadow and the actual buffer to maintain consistency.
1325  *
1326  * Returns: None.
1327  */
1328 void xe_migrate_ccs_rw_copy_clear(struct xe_bo *src_bo,
1329 				  enum xe_sriov_vf_ccs_rw_ctxs read_write,
1330 				  bool bound)
1331 {
1332 	struct xe_mem_pool_node *bb = src_bo->bb_ccs[read_write];
1333 	struct xe_device *xe = xe_bo_device(src_bo);
1334 	struct xe_mem_pool *bb_pool;
1335 	struct xe_sriov_vf_ccs_ctx *ctx;
1336 	u32 *cs;
1337 
1338 	xe_assert(xe, IS_SRIOV_VF(xe));
1339 
1340 	ctx = &xe->sriov.vf.ccs.contexts[read_write];
1341 	bb_pool = ctx->mem.ccs_bb_pool;
1342 
1343 	scoped_guard(mutex, xe_mem_pool_bo_swap_guard(bb_pool)) {
1344 		if (bound) {
1345 			xe_mem_pool_swap_shadow_locked(bb_pool);
1346 
1347 			cs = xe_mem_pool_node_cpu_addr(bb);
1348 			memset(cs, MI_NOOP, bb->sa_node.size);
1349 			xe_sriov_vf_ccs_rw_update_bb_addr(ctx);
1350 
1351 			xe_mem_pool_sync_shadow_locked(bb);
1352 		}
1353 		xe_mem_pool_free_node(bb);
1354 		src_bo->bb_ccs[read_write] = NULL;
1355 	}
1356 }
1357 
1358 /**
1359  * xe_migrate_exec_queue() - Get the execution queue from migrate context.
1360  * @migrate: Migrate context.
1361  *
1362  * Return: Pointer to execution queue on success, error on failure
1363  */
1364 struct xe_exec_queue *xe_migrate_exec_queue(struct xe_migrate *migrate)
1365 {
1366 	return migrate->q;
1367 }
1368 
1369 /**
1370  * xe_migrate_vram_copy_chunk() - Copy a chunk of a VRAM buffer object.
1371  * @vram_bo: The VRAM buffer object.
1372  * @vram_offset: The VRAM offset.
1373  * @sysmem_bo: The sysmem buffer object.
1374  * @sysmem_offset: The sysmem offset.
1375  * @size: The size of VRAM chunk to copy.
1376  * @dir: The direction of the copy operation.
1377  *
1378  * Copies a portion of a buffer object between VRAM and system memory.
1379  * On Xe2 platforms that support flat CCS, VRAM data is decompressed when
1380  * copying to system memory.
1381  *
1382  * Return: Pointer to a dma_fence representing the last copy batch, or
1383  * an error pointer on failure. If there is a failure, any copy operation
1384  * started by the function call has been synced.
1385  */
1386 struct dma_fence *xe_migrate_vram_copy_chunk(struct xe_bo *vram_bo, u64 vram_offset,
1387 					     struct xe_bo *sysmem_bo, u64 sysmem_offset,
1388 					     u64 size, enum xe_migrate_copy_dir dir)
1389 {
1390 	struct xe_device *xe = xe_bo_device(vram_bo);
1391 	struct xe_tile *tile = vram_bo->tile;
1392 	struct xe_gt *gt = tile->primary_gt;
1393 	struct xe_migrate *m = tile->migrate;
1394 	struct dma_fence *fence = NULL;
1395 	struct ttm_resource *vram = vram_bo->ttm.resource;
1396 	struct ttm_resource *sysmem = sysmem_bo->ttm.resource;
1397 	struct xe_res_cursor vram_it, sysmem_it;
1398 	u64 vram_L0_ofs, sysmem_L0_ofs;
1399 	u32 vram_L0_pt, sysmem_L0_pt;
1400 	u64 vram_L0, sysmem_L0;
1401 	bool to_sysmem = (dir == XE_MIGRATE_COPY_TO_SRAM);
1402 	bool use_comp_pat = to_sysmem &&
1403 		GRAPHICS_VER(xe) >= 20 && xe_device_has_flat_ccs(xe);
1404 	int pass = 0;
1405 	int err;
1406 
1407 	xe_assert(xe, IS_ALIGNED(vram_offset | sysmem_offset | size, PAGE_SIZE));
1408 	xe_assert(xe, xe_bo_is_vram(vram_bo));
1409 	xe_assert(xe, !xe_bo_is_vram(sysmem_bo));
1410 	xe_assert(xe, !range_overflows(vram_offset, size, (u64)vram_bo->ttm.base.size));
1411 	xe_assert(xe, !range_overflows(sysmem_offset, size, (u64)sysmem_bo->ttm.base.size));
1412 
1413 	xe_res_first(vram, vram_offset, size, &vram_it);
1414 	xe_res_first_sg(xe_bo_sg(sysmem_bo), sysmem_offset, size, &sysmem_it);
1415 
1416 	while (size) {
1417 		u32 pte_flags = PTE_UPDATE_FLAG_IS_VRAM;
1418 		u32 batch_size = 2; /* arb_clear() + MI_BATCH_BUFFER_END */
1419 		struct xe_sched_job *job;
1420 		struct xe_bb *bb;
1421 		u32 update_idx;
1422 		bool usm = xe->info.has_usm;
1423 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1424 
1425 		sysmem_L0 = xe_migrate_res_sizes(m, &sysmem_it);
1426 		vram_L0 = min(xe_migrate_res_sizes(m, &vram_it), sysmem_L0);
1427 
1428 		xe_dbg(xe, "Pass %u, size: %llu\n", pass++, vram_L0);
1429 
1430 		pte_flags |= use_comp_pat ? PTE_UPDATE_FLAG_IS_COMP_PTE : 0;
1431 		batch_size += pte_update_size(m, pte_flags, vram, &vram_it, &vram_L0,
1432 					      &vram_L0_ofs, &vram_L0_pt, 0, 0, avail_pts);
1433 
1434 		batch_size += pte_update_size(m, 0, sysmem, &sysmem_it, &vram_L0, &sysmem_L0_ofs,
1435 					      &sysmem_L0_pt, 0, avail_pts, avail_pts);
1436 		batch_size += emit_copy_cmd_len(xe);
1437 
1438 		bb = xe_bb_new(gt, batch_size, usm);
1439 		if (IS_ERR(bb)) {
1440 			err = PTR_ERR(bb);
1441 			return ERR_PTR(err);
1442 		}
1443 
1444 		if (xe_migrate_allow_identity(vram_L0, &vram_it))
1445 			xe_res_next(&vram_it, vram_L0);
1446 		else
1447 			emit_pte(m, bb, vram_L0_pt, true, use_comp_pat, &vram_it, vram_L0, vram);
1448 
1449 		emit_pte(m, bb, sysmem_L0_pt, false, false, &sysmem_it, vram_L0, sysmem);
1450 
1451 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
1452 		update_idx = bb->len;
1453 
1454 		if (to_sysmem)
1455 			emit_copy(gt, bb, vram_L0_ofs, sysmem_L0_ofs, vram_L0, XE_PAGE_SIZE);
1456 		else
1457 			emit_copy(gt, bb, sysmem_L0_ofs, vram_L0_ofs, vram_L0, XE_PAGE_SIZE);
1458 
1459 		job = xe_bb_create_migration_job(m->q, bb, xe_migrate_batch_base(m, usm),
1460 						 update_idx);
1461 		if (IS_ERR(job)) {
1462 			xe_bb_free(bb, NULL);
1463 			err = PTR_ERR(job);
1464 			return ERR_PTR(err);
1465 		}
1466 
1467 		xe_sched_job_add_migrate_flush(job, MI_INVALIDATE_TLB);
1468 
1469 		xe_assert(xe, dma_resv_test_signaled(vram_bo->ttm.base.resv,
1470 						     DMA_RESV_USAGE_BOOKKEEP));
1471 		xe_assert(xe, dma_resv_test_signaled(sysmem_bo->ttm.base.resv,
1472 						     DMA_RESV_USAGE_BOOKKEEP));
1473 
1474 		scoped_guard(mutex, &m->job_mutex) {
1475 			xe_sched_job_arm(job);
1476 			dma_fence_put(fence);
1477 			fence = dma_fence_get(&job->drm.s_fence->finished);
1478 			xe_sched_job_push(job);
1479 
1480 			dma_fence_put(m->fence);
1481 			m->fence = dma_fence_get(fence);
1482 		}
1483 
1484 		xe_bb_free(bb, fence);
1485 		size -= vram_L0;
1486 	}
1487 
1488 	return fence;
1489 }
1490 
1491 static u32 blt_mem_set_cmd_len(struct xe_device *xe)
1492 {
1493 	return 7;
1494 }
1495 
1496 static void emit_clear_link_copy(struct xe_gt *gt, struct xe_bb *bb, u64 src_ofs,
1497 				 u32 size, u32 pitch)
1498 {
1499 	struct xe_device *xe = gt_to_xe(gt);
1500 	u32 *cs = bb->cs + bb->len;
1501 	u32 len = blt_mem_set_cmd_len(xe);
1502 
1503 	*cs++ = PVC_MEM_SET_CMD | PVC_MEM_SET_MATRIX | (len - 2);
1504 	*cs++ = pitch - 1;
1505 	*cs++ = (size / pitch) - 1;
1506 	*cs++ = pitch - 1;
1507 	*cs++ = lower_32_bits(src_ofs);
1508 	*cs++ = upper_32_bits(src_ofs);
1509 	if (GRAPHICS_VERx100(xe) >= 2000)
1510 		*cs++ = FIELD_PREP(XE2_MEM_SET_MOCS_INDEX_MASK, gt->mocs.uc_index);
1511 	else
1512 		*cs++ = FIELD_PREP(PVC_MEM_SET_MOCS_INDEX_MASK, gt->mocs.uc_index);
1513 
1514 	xe_gt_assert(gt, cs - bb->cs == len + bb->len);
1515 
1516 	bb->len += len;
1517 }
1518 
1519 static u32 blt_fast_color_cmd_len(struct xe_device *xe)
1520 {
1521 	if (GRAPHICS_VERx100(xe) >= 1250)
1522 		return 16;
1523 	else
1524 		return 11;
1525 }
1526 
1527 static void emit_clear_main_copy(struct xe_gt *gt, struct xe_bb *bb,
1528 				 u64 src_ofs, u32 size, u32 pitch, bool is_vram)
1529 {
1530 	struct xe_device *xe = gt_to_xe(gt);
1531 	u32 *cs = bb->cs + bb->len;
1532 	u32 len = blt_fast_color_cmd_len(xe);
1533 
1534 
1535 	*cs++ = XY_FAST_COLOR_BLT_CMD | XY_FAST_COLOR_BLT_DEPTH_32 |
1536 		(len - 2);
1537 	if (GRAPHICS_VERx100(xe) >= 2000)
1538 		*cs++ = FIELD_PREP(XE2_XY_FAST_COLOR_BLT_MOCS_INDEX_MASK, gt->mocs.uc_index) |
1539 			(pitch - 1);
1540 	else
1541 		*cs++ = FIELD_PREP(XY_FAST_COLOR_BLT_MOCS_MASK, gt->mocs.uc_index) |
1542 			(pitch - 1);
1543 	*cs++ = 0;
1544 	*cs++ = (size / pitch) << 16 | pitch / 4;
1545 	*cs++ = lower_32_bits(src_ofs);
1546 	*cs++ = upper_32_bits(src_ofs);
1547 	*cs++ = (is_vram ? 0x0 : 0x1) <<  XY_FAST_COLOR_BLT_MEM_TYPE_SHIFT;
1548 	*cs++ = 0;
1549 	*cs++ = 0;
1550 	*cs++ = 0;
1551 	*cs++ = 0;
1552 
1553 	if (len > 11) {
1554 		*cs++ = 0;
1555 		*cs++ = 0;
1556 		*cs++ = 0;
1557 		*cs++ = 0;
1558 		*cs++ = 0;
1559 	}
1560 
1561 	xe_gt_assert(gt, cs - bb->cs == len + bb->len);
1562 
1563 	bb->len += len;
1564 }
1565 
1566 static u32 emit_clear_cmd_len(struct xe_gt *gt)
1567 {
1568 	struct xe_device *xe = gt_to_xe(gt);
1569 
1570 	if (gt->info.has_xe2_blt_instructions)
1571 		return blt_mem_set_cmd_len(xe);
1572 	else
1573 		return blt_fast_color_cmd_len(xe);
1574 }
1575 
1576 static void emit_clear(struct xe_gt *gt, struct xe_bb *bb, u64 src_ofs,
1577 		       u32 size, u32 pitch, bool is_vram)
1578 {
1579 	if (gt->info.has_xe2_blt_instructions)
1580 		emit_clear_link_copy(gt, bb, src_ofs, size, pitch);
1581 	else
1582 		emit_clear_main_copy(gt, bb, src_ofs, size, pitch,
1583 				     is_vram);
1584 }
1585 
1586 /**
1587  * xe_migrate_clear() - Copy content of TTM resources.
1588  * @m: The migration context.
1589  * @bo: The buffer object @dst is currently bound to.
1590  * @dst: The dst TTM resource to be cleared.
1591  * @clear_flags: flags to specify which data to clear: CCS, BO, or both.
1592  *
1593  * Clear the contents of @dst to zero when XE_MIGRATE_CLEAR_FLAG_BO_DATA is set.
1594  * On flat CCS devices, the CCS metadata is cleared to zero with XE_MIGRATE_CLEAR_FLAG_CCS_DATA.
1595  * Set XE_MIGRATE_CLEAR_FLAG_FULL to clear bo as well as CCS metadata.
1596  * TODO: Eliminate the @bo argument.
1597  *
1598  * Return: Pointer to a dma_fence representing the last clear batch, or
1599  * an error pointer on failure. If there is a failure, any clear operation
1600  * started by the function call has been synced.
1601  */
1602 struct dma_fence *xe_migrate_clear(struct xe_migrate *m,
1603 				   struct xe_bo *bo,
1604 				   struct ttm_resource *dst,
1605 				   u32 clear_flags)
1606 {
1607 	bool clear_vram = mem_type_is_vram(dst->mem_type);
1608 	bool clear_bo_data = XE_MIGRATE_CLEAR_FLAG_BO_DATA & clear_flags;
1609 	bool clear_ccs = XE_MIGRATE_CLEAR_FLAG_CCS_DATA & clear_flags;
1610 	struct xe_gt *gt = m->tile->primary_gt;
1611 	struct xe_device *xe = gt_to_xe(gt);
1612 	bool clear_only_system_ccs = false;
1613 	struct dma_fence *fence = NULL;
1614 	u64 size = xe_bo_size(bo);
1615 	struct xe_res_cursor src_it;
1616 	struct ttm_resource *src = dst;
1617 	int err;
1618 
1619 	if (WARN_ON(!clear_bo_data && !clear_ccs))
1620 		return NULL;
1621 
1622 	if (!clear_bo_data && clear_ccs && !IS_DGFX(xe))
1623 		clear_only_system_ccs = true;
1624 
1625 	if (!clear_vram)
1626 		xe_res_first_sg(xe_bo_sg(bo), 0, xe_bo_size(bo), &src_it);
1627 	else
1628 		xe_res_first(src, 0, xe_bo_size(bo), &src_it);
1629 
1630 	while (size) {
1631 		u64 clear_L0_ofs;
1632 		u32 clear_L0_pt;
1633 		u32 flush_flags = 0;
1634 		u64 clear_L0;
1635 		struct xe_sched_job *job;
1636 		struct xe_bb *bb;
1637 		u32 batch_size, update_idx;
1638 		u32 pte_flags;
1639 
1640 		bool usm = xe->info.has_usm;
1641 		u32 avail_pts = max_mem_transfer_per_pass(xe) / LEVEL0_PAGE_TABLE_ENCODE_SIZE;
1642 
1643 		clear_L0 = xe_migrate_res_sizes(m, &src_it);
1644 
1645 		/* Calculate final sizes and batch size.. */
1646 		pte_flags = clear_vram ? PTE_UPDATE_FLAG_IS_VRAM : 0;
1647 		batch_size = 1 +
1648 			pte_update_size(m, pte_flags, src, &src_it,
1649 					&clear_L0, &clear_L0_ofs, &clear_L0_pt,
1650 					clear_bo_data ? emit_clear_cmd_len(gt) : 0, 0,
1651 					avail_pts);
1652 
1653 		if (xe_migrate_needs_ccs_emit(xe))
1654 			batch_size += EMIT_COPY_CCS_DW;
1655 
1656 		/* Clear commands */
1657 
1658 		if (WARN_ON_ONCE(!clear_L0))
1659 			break;
1660 
1661 		bb = xe_bb_new(gt, batch_size, usm);
1662 		if (IS_ERR(bb)) {
1663 			err = PTR_ERR(bb);
1664 			goto err_sync;
1665 		}
1666 
1667 		size -= clear_L0;
1668 		/* Preemption is enabled again by the ring ops. */
1669 		if (clear_vram && xe_migrate_allow_identity(clear_L0, &src_it)) {
1670 			xe_res_next(&src_it, clear_L0);
1671 		} else {
1672 			emit_pte(m, bb, clear_L0_pt, clear_vram,
1673 				 clear_only_system_ccs, &src_it, clear_L0, dst);
1674 			flush_flags |= MI_INVALIDATE_TLB;
1675 		}
1676 
1677 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
1678 		update_idx = bb->len;
1679 
1680 		if (clear_bo_data)
1681 			emit_clear(gt, bb, clear_L0_ofs, clear_L0, XE_PAGE_SIZE, clear_vram);
1682 
1683 		if (xe_migrate_needs_ccs_emit(xe)) {
1684 			emit_copy_ccs(gt, bb, clear_L0_ofs, true,
1685 				      m->cleared_mem_ofs, false, clear_L0);
1686 			flush_flags |= MI_FLUSH_DW_CCS;
1687 		}
1688 
1689 		job = xe_bb_create_migration_job(m->q, bb,
1690 						 xe_migrate_batch_base(m, usm),
1691 						 update_idx);
1692 		if (IS_ERR(job)) {
1693 			err = PTR_ERR(job);
1694 			goto err;
1695 		}
1696 
1697 		xe_sched_job_add_migrate_flush(job, flush_flags);
1698 		if (!fence) {
1699 			/*
1700 			 * There can't be anything userspace related at this
1701 			 * point, so we just need to respect any potential move
1702 			 * fences, which are always tracked as
1703 			 * DMA_RESV_USAGE_KERNEL.
1704 			 */
1705 			err = xe_sched_job_add_deps(job, bo->ttm.base.resv,
1706 						    DMA_RESV_USAGE_KERNEL);
1707 			if (err)
1708 				goto err_job;
1709 		}
1710 
1711 		mutex_lock(&m->job_mutex);
1712 		xe_sched_job_arm(job);
1713 		dma_fence_put(fence);
1714 		fence = dma_fence_get(&job->drm.s_fence->finished);
1715 		xe_sched_job_push(job);
1716 
1717 		dma_fence_put(m->fence);
1718 		m->fence = dma_fence_get(fence);
1719 
1720 		mutex_unlock(&m->job_mutex);
1721 
1722 		xe_bb_free(bb, fence);
1723 		continue;
1724 
1725 err_job:
1726 		xe_sched_job_put(job);
1727 err:
1728 		xe_bb_free(bb, NULL);
1729 err_sync:
1730 		/* Sync partial copies if any. FIXME: job_mutex? */
1731 		if (fence) {
1732 			dma_fence_wait(fence, false);
1733 			dma_fence_put(fence);
1734 		}
1735 
1736 		return ERR_PTR(err);
1737 	}
1738 
1739 	if (clear_ccs)
1740 		bo->ccs_cleared = true;
1741 
1742 	return fence;
1743 }
1744 
1745 static void write_pgtable(struct xe_tile *tile, struct xe_bb *bb, u64 ppgtt_ofs,
1746 			  const struct xe_vm_pgtable_update_op *pt_op,
1747 			  const struct xe_vm_pgtable_update *update,
1748 			  struct xe_migrate_pt_update *pt_update)
1749 {
1750 	const struct xe_migrate_pt_update_ops *ops = pt_update->ops;
1751 	u32 chunk;
1752 	u32 ofs = update->ofs, size = update->qwords;
1753 
1754 	/*
1755 	 * If we have 512 entries (max), we would populate it ourselves,
1756 	 * and update the PDE above it to the new pointer.
1757 	 * The only time this can only happen if we have to update the top
1758 	 * PDE. This requires a BO that is almost vm->size big.
1759 	 *
1760 	 * This shouldn't be possible in practice.. might change when 16K
1761 	 * pages are used. Hence the assert.
1762 	 */
1763 	xe_tile_assert(tile, update->qwords < MAX_NUM_PTE);
1764 	if (!ppgtt_ofs)
1765 		ppgtt_ofs = xe_migrate_vram_ofs(tile_to_xe(tile),
1766 						xe_bo_addr(update->pt_bo, 0,
1767 							   XE_PAGE_SIZE), false);
1768 
1769 	do {
1770 		u64 addr = ppgtt_ofs + ofs * 8;
1771 
1772 		chunk = min(size, MAX_PTE_PER_SDI);
1773 
1774 		/* Ensure populatefn can do memset64 by aligning bb->cs */
1775 		if (!(bb->len & 1))
1776 			bb->cs[bb->len++] = MI_NOOP;
1777 
1778 		bb->cs[bb->len++] = MI_STORE_DATA_IMM | MI_SDI_NUM_QW(chunk);
1779 		bb->cs[bb->len++] = lower_32_bits(addr);
1780 		bb->cs[bb->len++] = upper_32_bits(addr);
1781 		if (pt_op->bind)
1782 			ops->populate(pt_update, tile, NULL, bb->cs + bb->len,
1783 				      ofs, chunk, update);
1784 		else
1785 			ops->clear(pt_update, tile, NULL, bb->cs + bb->len,
1786 				   ofs, chunk, update);
1787 
1788 		bb->len += chunk * 2;
1789 		ofs += chunk;
1790 		size -= chunk;
1791 	} while (size);
1792 }
1793 
1794 struct xe_vm *xe_migrate_get_vm(struct xe_migrate *m)
1795 {
1796 	return xe_vm_get(m->q->vm);
1797 }
1798 
1799 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
1800 struct migrate_test_params {
1801 	struct xe_test_priv base;
1802 	bool force_gpu;
1803 };
1804 
1805 #define to_migrate_test_params(_priv) \
1806 	container_of(_priv, struct migrate_test_params, base)
1807 #endif
1808 
1809 static struct dma_fence *
1810 xe_migrate_update_pgtables_cpu(struct xe_migrate *m,
1811 			       struct xe_migrate_pt_update *pt_update)
1812 {
1813 	XE_TEST_DECLARE(struct migrate_test_params *test =
1814 			to_migrate_test_params
1815 			(xe_cur_kunit_priv(XE_TEST_LIVE_MIGRATE));)
1816 	const struct xe_migrate_pt_update_ops *ops = pt_update->ops;
1817 	struct xe_vm *vm = pt_update->vops->vm;
1818 	struct xe_vm_pgtable_update_ops *pt_update_ops =
1819 		&pt_update->vops->pt_update_ops[pt_update->tile_id];
1820 	int err;
1821 	u32 i, j;
1822 
1823 	if (XE_TEST_ONLY(test && test->force_gpu))
1824 		return ERR_PTR(-ETIME);
1825 
1826 	if (ops->pre_commit) {
1827 		pt_update->job = NULL;
1828 		err = ops->pre_commit(pt_update);
1829 		if (err)
1830 			return ERR_PTR(err);
1831 	}
1832 
1833 	for (i = 0; i < pt_update_ops->num_ops; ++i) {
1834 		const struct xe_vm_pgtable_update_op *pt_op =
1835 			&pt_update_ops->ops[i];
1836 
1837 		for (j = 0; j < pt_op->num_entries; j++) {
1838 			const struct xe_vm_pgtable_update *update =
1839 				&pt_op->entries[j];
1840 
1841 			if (pt_op->bind)
1842 				ops->populate(pt_update, m->tile,
1843 					      &update->pt_bo->vmap, NULL,
1844 					      update->ofs, update->qwords,
1845 					      update);
1846 			else
1847 				ops->clear(pt_update, m->tile,
1848 					   &update->pt_bo->vmap, NULL,
1849 					   update->ofs, update->qwords, update);
1850 		}
1851 	}
1852 
1853 	trace_xe_vm_cpu_bind(vm);
1854 	xe_device_wmb(vm->xe);
1855 
1856 	return dma_fence_get_stub();
1857 }
1858 
1859 static struct dma_fence *
1860 __xe_migrate_update_pgtables(struct xe_migrate *m,
1861 			     struct xe_migrate_pt_update *pt_update,
1862 			     struct xe_vm_pgtable_update_ops *pt_update_ops)
1863 {
1864 	const struct xe_migrate_pt_update_ops *ops = pt_update->ops;
1865 	struct xe_tile *tile = m->tile;
1866 	struct xe_gt *gt = tile->primary_gt;
1867 	struct xe_device *xe = tile_to_xe(tile);
1868 	struct xe_sched_job *job;
1869 	struct dma_fence *fence;
1870 	struct drm_suballoc *sa_bo = NULL;
1871 	struct xe_bb *bb;
1872 	u32 i, j, batch_size = 0, ppgtt_ofs, update_idx, page_ofs = 0;
1873 	u32 num_updates = 0, current_update = 0;
1874 	u64 addr;
1875 	int err = 0;
1876 	bool is_migrate = pt_update_ops->q == m->q;
1877 	bool usm = is_migrate && xe->info.has_usm;
1878 
1879 	for (i = 0; i < pt_update_ops->num_ops; ++i) {
1880 		struct xe_vm_pgtable_update_op *pt_op = &pt_update_ops->ops[i];
1881 		struct xe_vm_pgtable_update *updates = pt_op->entries;
1882 
1883 		num_updates += pt_op->num_entries;
1884 		for (j = 0; j < pt_op->num_entries; ++j) {
1885 			u32 num_cmds = DIV_ROUND_UP(updates[j].qwords,
1886 						    MAX_PTE_PER_SDI);
1887 
1888 			/* align noop + MI_STORE_DATA_IMM cmd prefix */
1889 			batch_size += 4 * num_cmds + updates[j].qwords * 2;
1890 		}
1891 	}
1892 
1893 	/* fixed + PTE entries */
1894 	if (IS_DGFX(xe))
1895 		batch_size += 2;
1896 	else
1897 		batch_size += 6 * (num_updates / MAX_PTE_PER_SDI + 1) +
1898 			num_updates * 2;
1899 
1900 	bb = xe_bb_new(gt, batch_size, usm);
1901 	if (IS_ERR(bb))
1902 		return ERR_CAST(bb);
1903 
1904 	/* For sysmem PTE's, need to map them in our hole.. */
1905 	if (!IS_DGFX(xe)) {
1906 		u16 pat_index = xe_cache_pat_idx(xe, XE_CACHE_WB);
1907 		u32 ptes, ofs;
1908 
1909 		ppgtt_ofs = NUM_KERNEL_PDE - 1;
1910 		if (!is_migrate) {
1911 			u32 num_units = DIV_ROUND_UP(num_updates,
1912 						     NUM_VMUSA_WRITES_PER_UNIT);
1913 
1914 			if (num_units > m->vm_update_sa.size) {
1915 				err = -ENOBUFS;
1916 				goto err_bb;
1917 			}
1918 			sa_bo = drm_suballoc_new(&m->vm_update_sa, num_units,
1919 						 GFP_KERNEL, true, 0);
1920 			if (IS_ERR(sa_bo)) {
1921 				err = PTR_ERR(sa_bo);
1922 				goto err_bb;
1923 			}
1924 
1925 			ppgtt_ofs = NUM_KERNEL_PDE +
1926 				(drm_suballoc_soffset(sa_bo) /
1927 				 NUM_VMUSA_UNIT_PER_PAGE);
1928 			page_ofs = (drm_suballoc_soffset(sa_bo) %
1929 				    NUM_VMUSA_UNIT_PER_PAGE) *
1930 				VM_SA_UPDATE_UNIT_SIZE;
1931 		}
1932 
1933 		/* Map our PT's to gtt */
1934 		i = 0;
1935 		j = 0;
1936 		ptes = num_updates;
1937 		ofs = ppgtt_ofs * XE_PAGE_SIZE + page_ofs;
1938 		while (ptes) {
1939 			u32 chunk = min(MAX_PTE_PER_SDI, ptes);
1940 			u32 idx = 0;
1941 
1942 			bb->cs[bb->len++] = MI_STORE_DATA_IMM |
1943 				MI_SDI_NUM_QW(chunk);
1944 			bb->cs[bb->len++] = ofs;
1945 			bb->cs[bb->len++] = 0; /* upper_32_bits */
1946 
1947 			for (; i < pt_update_ops->num_ops; ++i) {
1948 				struct xe_vm_pgtable_update_op *pt_op =
1949 					&pt_update_ops->ops[i];
1950 				struct xe_vm_pgtable_update *updates = pt_op->entries;
1951 
1952 				for (; j < pt_op->num_entries; ++j, ++current_update, ++idx) {
1953 					struct xe_vm *vm = pt_update->vops->vm;
1954 					struct xe_bo *pt_bo = updates[j].pt_bo;
1955 
1956 					if (idx == chunk)
1957 						goto next_cmd;
1958 
1959 					xe_tile_assert(tile, xe_bo_size(pt_bo) == SZ_4K);
1960 
1961 					/* Map a PT at most once */
1962 					if (pt_bo->update_index < 0)
1963 						pt_bo->update_index = current_update;
1964 
1965 					addr = vm->pt_ops->pte_encode_bo(pt_bo, 0,
1966 									 pat_index, 0);
1967 					bb->cs[bb->len++] = lower_32_bits(addr);
1968 					bb->cs[bb->len++] = upper_32_bits(addr);
1969 				}
1970 
1971 				j = 0;
1972 			}
1973 
1974 next_cmd:
1975 			ptes -= chunk;
1976 			ofs += chunk * sizeof(u64);
1977 		}
1978 
1979 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
1980 		update_idx = bb->len;
1981 
1982 		addr = xe_migrate_vm_addr(ppgtt_ofs, 0) +
1983 			(page_ofs / sizeof(u64)) * XE_PAGE_SIZE;
1984 		for (i = 0; i < pt_update_ops->num_ops; ++i) {
1985 			struct xe_vm_pgtable_update_op *pt_op =
1986 				&pt_update_ops->ops[i];
1987 			struct xe_vm_pgtable_update *updates = pt_op->entries;
1988 
1989 			for (j = 0; j < pt_op->num_entries; ++j) {
1990 				struct xe_bo *pt_bo = updates[j].pt_bo;
1991 
1992 				write_pgtable(tile, bb, addr +
1993 					      pt_bo->update_index * XE_PAGE_SIZE,
1994 					      pt_op, &updates[j], pt_update);
1995 			}
1996 		}
1997 	} else {
1998 		/* phys pages, no preamble required */
1999 		bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
2000 		update_idx = bb->len;
2001 
2002 		for (i = 0; i < pt_update_ops->num_ops; ++i) {
2003 			struct xe_vm_pgtable_update_op *pt_op =
2004 				&pt_update_ops->ops[i];
2005 			struct xe_vm_pgtable_update *updates = pt_op->entries;
2006 
2007 			for (j = 0; j < pt_op->num_entries; ++j)
2008 				write_pgtable(tile, bb, 0, pt_op, &updates[j],
2009 					      pt_update);
2010 		}
2011 	}
2012 
2013 	job = xe_bb_create_migration_job(pt_update_ops->q, bb,
2014 					 xe_migrate_batch_base(m, usm),
2015 					 update_idx);
2016 	if (IS_ERR(job)) {
2017 		err = PTR_ERR(job);
2018 		goto err_sa;
2019 	}
2020 
2021 	xe_sched_job_add_migrate_flush(job, MI_INVALIDATE_TLB);
2022 
2023 	if (ops->pre_commit) {
2024 		pt_update->job = job;
2025 		err = ops->pre_commit(pt_update);
2026 		if (err)
2027 			goto err_job;
2028 	}
2029 	if (is_migrate)
2030 		mutex_lock(&m->job_mutex);
2031 
2032 	xe_sched_job_arm(job);
2033 	fence = dma_fence_get(&job->drm.s_fence->finished);
2034 	xe_sched_job_push(job);
2035 
2036 	if (is_migrate)
2037 		mutex_unlock(&m->job_mutex);
2038 
2039 	xe_bb_free(bb, fence);
2040 	drm_suballoc_free(sa_bo, fence);
2041 
2042 	return fence;
2043 
2044 err_job:
2045 	xe_sched_job_put(job);
2046 err_sa:
2047 	drm_suballoc_free(sa_bo, NULL);
2048 err_bb:
2049 	xe_bb_free(bb, NULL);
2050 	return ERR_PTR(err);
2051 }
2052 
2053 /**
2054  * xe_migrate_update_pgtables() - Pipelined page-table update
2055  * @m: The migrate context.
2056  * @pt_update: PT update arguments
2057  *
2058  * Perform a pipelined page-table update. The update descriptors are typically
2059  * built under the same lock critical section as a call to this function. If
2060  * using the default engine for the updates, they will be performed in the
2061  * order they grab the job_mutex. If different engines are used, external
2062  * synchronization is needed for overlapping updates to maintain page-table
2063  * consistency. Note that the meaning of "overlapping" is that the updates
2064  * touch the same page-table, which might be a higher-level page-directory.
2065  * If no pipelining is needed, then updates may be performed by the cpu.
2066  *
2067  * Return: A dma_fence that, when signaled, indicates the update completion.
2068  */
2069 struct dma_fence *
2070 xe_migrate_update_pgtables(struct xe_migrate *m,
2071 			   struct xe_migrate_pt_update *pt_update)
2072 
2073 {
2074 	struct xe_vm_pgtable_update_ops *pt_update_ops =
2075 		&pt_update->vops->pt_update_ops[pt_update->tile_id];
2076 	struct dma_fence *fence;
2077 
2078 	fence =  xe_migrate_update_pgtables_cpu(m, pt_update);
2079 
2080 	/* -ETIME indicates a job is needed, anything else is legit error */
2081 	if (!IS_ERR(fence) || PTR_ERR(fence) != -ETIME)
2082 		return fence;
2083 
2084 	return __xe_migrate_update_pgtables(m, pt_update, pt_update_ops);
2085 }
2086 
2087 /**
2088  * xe_migrate_wait() - Complete all operations using the xe_migrate context
2089  * @m: Migrate context to wait for.
2090  *
2091  * Waits until the GPU no longer uses the migrate context's default engine
2092  * or its page-table objects. FIXME: What about separate page-table update
2093  * engines?
2094  */
2095 void xe_migrate_wait(struct xe_migrate *m)
2096 {
2097 	if (m->fence)
2098 		dma_fence_wait(m->fence, false);
2099 }
2100 
2101 static u32 pte_update_cmd_size(u64 size)
2102 {
2103 	u32 num_dword;
2104 	u64 entries = DIV_U64_ROUND_UP(size, XE_PAGE_SIZE);
2105 
2106 	XE_WARN_ON(size > MAX_PREEMPTDISABLE_TRANSFER);
2107 
2108 	/*
2109 	 * MI_STORE_DATA_IMM command is used to update page table. Each
2110 	 * instruction can update maximumly MAX_PTE_PER_SDI pte entries. To
2111 	 * update n (n <= MAX_PTE_PER_SDI) pte entries, we need:
2112 	 *
2113 	 * - 1 dword for the MI_STORE_DATA_IMM command header (opcode etc)
2114 	 * - 2 dword for the page table's physical location
2115 	 * - 2*n dword for value of pte to fill (each pte entry is 2 dwords)
2116 	 */
2117 	num_dword = (1 + 2) * DIV_U64_ROUND_UP(entries, MAX_PTE_PER_SDI);
2118 	num_dword += entries * 2;
2119 
2120 	return num_dword;
2121 }
2122 
2123 static void build_pt_update_batch_sram(struct xe_migrate *m,
2124 				       struct xe_bb *bb, u32 pt_offset,
2125 				       struct drm_pagemap_addr *sram_addr,
2126 				       u32 size, int level)
2127 {
2128 	u16 pat_index = xe_cache_pat_idx(tile_to_xe(m->tile), XE_CACHE_WB);
2129 	u64 gpu_page_size = 0x1ull << xe_pt_shift(level);
2130 	u32 ptes;
2131 	int i = 0;
2132 
2133 	xe_tile_assert(m->tile, PAGE_ALIGNED(size));
2134 
2135 	ptes = DIV_ROUND_UP(size, gpu_page_size);
2136 	while (ptes) {
2137 		u32 chunk = min(MAX_PTE_PER_SDI, ptes);
2138 
2139 		if (!level)
2140 			chunk = ALIGN_DOWN(chunk, PAGE_SIZE / XE_PAGE_SIZE);
2141 
2142 		bb->cs[bb->len++] = MI_STORE_DATA_IMM | MI_SDI_NUM_QW(chunk);
2143 		bb->cs[bb->len++] = pt_offset;
2144 		bb->cs[bb->len++] = 0;
2145 
2146 		pt_offset += chunk * 8;
2147 		ptes -= chunk;
2148 
2149 		while (chunk--) {
2150 			u64 addr = sram_addr[i].addr;
2151 			u64 pte;
2152 
2153 			xe_tile_assert(m->tile, sram_addr[i].proto ==
2154 				       DRM_INTERCONNECT_SYSTEM ||
2155 				       sram_addr[i].proto == XE_INTERCONNECT_P2P);
2156 			xe_tile_assert(m->tile, addr);
2157 			xe_tile_assert(m->tile, PAGE_ALIGNED(addr));
2158 
2159 again:
2160 			pte = m->q->vm->pt_ops->pte_encode_addr(m->tile->xe,
2161 								addr, pat_index,
2162 								level, false, 0);
2163 			bb->cs[bb->len++] = lower_32_bits(pte);
2164 			bb->cs[bb->len++] = upper_32_bits(pte);
2165 
2166 			if (gpu_page_size < PAGE_SIZE) {
2167 				addr += XE_PAGE_SIZE;
2168 				if (!PAGE_ALIGNED(addr)) {
2169 					chunk--;
2170 					goto again;
2171 				}
2172 				i++;
2173 			} else {
2174 				i += gpu_page_size / PAGE_SIZE;
2175 			}
2176 		}
2177 	}
2178 }
2179 
2180 static bool xe_migrate_vram_use_pde(struct drm_pagemap_addr *sram_addr,
2181 				    unsigned long size)
2182 {
2183 	u32 large_size = (0x1 << xe_pt_shift(1));
2184 	unsigned long i, incr = large_size / PAGE_SIZE;
2185 
2186 	for (i = 0; i < DIV_ROUND_UP(size, PAGE_SIZE); i += incr)
2187 		if (PAGE_SIZE << sram_addr[i].order != large_size)
2188 			return false;
2189 
2190 	return true;
2191 }
2192 
2193 #define XE_CACHELINE_BYTES	64ull
2194 #define XE_CACHELINE_MASK	(XE_CACHELINE_BYTES - 1)
2195 
2196 static u32 xe_migrate_copy_pitch(struct xe_device *xe, u32 len)
2197 {
2198 	u32 pitch;
2199 
2200 	if (IS_ALIGNED(len, PAGE_SIZE))
2201 		pitch = PAGE_SIZE;
2202 	else if (IS_ALIGNED(len, SZ_4K))
2203 		pitch = SZ_4K;
2204 	else if (IS_ALIGNED(len, SZ_256))
2205 		pitch = SZ_256;
2206 	else if (IS_ALIGNED(len, 4))
2207 		pitch = 4;
2208 	else
2209 		pitch = 1;
2210 
2211 	xe_assert(xe, pitch > 1 || xe->info.has_mem_copy_instr);
2212 	return pitch;
2213 }
2214 
2215 static struct dma_fence *xe_migrate_vram(struct xe_migrate *m,
2216 					 unsigned long len,
2217 					 unsigned long sram_offset,
2218 					 struct drm_pagemap_addr *sram_addr,
2219 					 u64 vram_addr,
2220 					 struct dma_fence *deps,
2221 					 const enum xe_migrate_copy_dir dir)
2222 {
2223 	struct xe_gt *gt = m->tile->primary_gt;
2224 	struct xe_device *xe = gt_to_xe(gt);
2225 	bool use_usm_batch = xe->info.has_usm;
2226 	struct dma_fence *fence = NULL;
2227 	u32 batch_size = 1;
2228 	u64 src_L0_ofs, dst_L0_ofs;
2229 	struct xe_sched_job *job;
2230 	struct xe_bb *bb;
2231 	u32 update_idx, pt_slot = 0;
2232 	unsigned long npages = DIV_ROUND_UP(len + sram_offset, PAGE_SIZE);
2233 	unsigned int pitch = xe_migrate_copy_pitch(xe, len);
2234 	int err;
2235 	unsigned long i, j;
2236 	bool use_pde = xe_migrate_vram_use_pde(sram_addr, len + sram_offset);
2237 
2238 	if (!xe->info.has_mem_copy_instr &&
2239 	    drm_WARN_ON(&xe->drm,
2240 			(!IS_ALIGNED(len, pitch)) || (sram_offset | vram_addr) & XE_CACHELINE_MASK))
2241 		return ERR_PTR(-EOPNOTSUPP);
2242 
2243 	xe_assert(xe, npages * PAGE_SIZE <= MAX_PREEMPTDISABLE_TRANSFER);
2244 
2245 	batch_size += pte_update_cmd_size(npages << PAGE_SHIFT);
2246 	batch_size += emit_copy_cmd_len(xe);
2247 
2248 	bb = xe_bb_new(gt, batch_size, use_usm_batch);
2249 	if (IS_ERR(bb)) {
2250 		err = PTR_ERR(bb);
2251 		return ERR_PTR(err);
2252 	}
2253 
2254 	/*
2255 	 * If the order of a struct drm_pagemap_addr entry is greater than 0,
2256 	 * the entry is populated by GPU pagemap but subsequent entries within
2257 	 * the range of that order are not populated.
2258 	 * build_pt_update_batch_sram() expects a fully populated array of
2259 	 * struct drm_pagemap_addr. Ensure this is the case even with higher
2260 	 * orders.
2261 	 */
2262 	for (i = 0; !use_pde && i < npages;) {
2263 		unsigned int order = sram_addr[i].order;
2264 
2265 		for (j = 1; j < NR_PAGES(order) && i + j < npages; j++)
2266 			if (!sram_addr[i + j].addr)
2267 				sram_addr[i + j].addr = sram_addr[i].addr + j * PAGE_SIZE;
2268 
2269 		i += NR_PAGES(order);
2270 	}
2271 
2272 	if (use_pde)
2273 		build_pt_update_batch_sram(m, bb, m->large_page_copy_pdes,
2274 					   sram_addr, npages << PAGE_SHIFT, 1);
2275 	else
2276 		build_pt_update_batch_sram(m, bb, pt_slot * XE_PAGE_SIZE,
2277 					   sram_addr, npages << PAGE_SHIFT, 0);
2278 
2279 	if (dir == XE_MIGRATE_COPY_TO_VRAM) {
2280 		if (use_pde)
2281 			src_L0_ofs = m->large_page_copy_ofs + sram_offset;
2282 		else
2283 			src_L0_ofs = xe_migrate_vm_addr(pt_slot, 0) + sram_offset;
2284 		dst_L0_ofs = xe_migrate_vram_ofs(xe, vram_addr, false);
2285 
2286 	} else {
2287 		src_L0_ofs = xe_migrate_vram_ofs(xe, vram_addr, false);
2288 		if (use_pde)
2289 			dst_L0_ofs = m->large_page_copy_ofs + sram_offset;
2290 		else
2291 			dst_L0_ofs = xe_migrate_vm_addr(pt_slot, 0) + sram_offset;
2292 	}
2293 
2294 	bb->cs[bb->len++] = MI_BATCH_BUFFER_END;
2295 	update_idx = bb->len;
2296 
2297 	emit_copy(gt, bb, src_L0_ofs, dst_L0_ofs, len, pitch);
2298 
2299 	job = xe_bb_create_migration_job(m->q, bb,
2300 					 xe_migrate_batch_base(m, use_usm_batch),
2301 					 update_idx);
2302 	if (IS_ERR(job)) {
2303 		err = PTR_ERR(job);
2304 		goto err;
2305 	}
2306 
2307 	xe_sched_job_add_migrate_flush(job, MI_INVALIDATE_TLB);
2308 
2309 	if (deps && !dma_fence_is_signaled(deps)) {
2310 		dma_fence_get(deps);
2311 		err = drm_sched_job_add_dependency(&job->drm, deps);
2312 		if (err)
2313 			dma_fence_wait(deps, false);
2314 		err = 0;
2315 	}
2316 
2317 	mutex_lock(&m->job_mutex);
2318 	xe_sched_job_arm(job);
2319 	fence = dma_fence_get(&job->drm.s_fence->finished);
2320 	xe_sched_job_push(job);
2321 
2322 	dma_fence_put(m->fence);
2323 	m->fence = dma_fence_get(fence);
2324 	mutex_unlock(&m->job_mutex);
2325 
2326 	xe_bb_free(bb, fence);
2327 
2328 	return fence;
2329 
2330 err:
2331 	xe_bb_free(bb, NULL);
2332 
2333 	return ERR_PTR(err);
2334 }
2335 
2336 /**
2337  * xe_migrate_to_vram() - Migrate to VRAM
2338  * @m: The migration context.
2339  * @npages: Number of pages to migrate.
2340  * @src_addr: Array of DMA information (source of migrate)
2341  * @dst_addr: Device physical address of VRAM (destination of migrate)
2342  * @deps: struct dma_fence representing the dependencies that need
2343  * to be signaled before migration.
2344  *
2345  * Copy from an array dma addresses to a VRAM device physical address
2346  *
2347  * Return: dma fence for migrate to signal completion on success, ERR_PTR on
2348  * failure
2349  */
2350 struct dma_fence *xe_migrate_to_vram(struct xe_migrate *m,
2351 				     unsigned long npages,
2352 				     struct drm_pagemap_addr *src_addr,
2353 				     u64 dst_addr,
2354 				     struct dma_fence *deps)
2355 {
2356 	return xe_migrate_vram(m, npages * PAGE_SIZE, 0, src_addr, dst_addr,
2357 			       deps, XE_MIGRATE_COPY_TO_VRAM);
2358 }
2359 
2360 /**
2361  * xe_migrate_from_vram() - Migrate from VRAM
2362  * @m: The migration context.
2363  * @npages: Number of pages to migrate.
2364  * @src_addr: Device physical address of VRAM (source of migrate)
2365  * @dst_addr: Array of DMA information (destination of migrate)
2366  * @deps: struct dma_fence representing the dependencies that need
2367  * to be signaled before migration.
2368  *
2369  * Copy from a VRAM device physical address to an array dma addresses
2370  *
2371  * Return: dma fence for migrate to signal completion on success, ERR_PTR on
2372  * failure
2373  */
2374 struct dma_fence *xe_migrate_from_vram(struct xe_migrate *m,
2375 				       unsigned long npages,
2376 				       u64 src_addr,
2377 				       struct drm_pagemap_addr *dst_addr,
2378 				       struct dma_fence *deps)
2379 {
2380 	return xe_migrate_vram(m, npages * PAGE_SIZE, 0, dst_addr, src_addr,
2381 			       deps, XE_MIGRATE_COPY_TO_SRAM);
2382 }
2383 
2384 static void xe_migrate_dma_unmap(struct xe_device *xe,
2385 				 struct drm_pagemap_addr *pagemap_addr,
2386 				 int len, int write)
2387 {
2388 	unsigned long i, npages = DIV_ROUND_UP(len, PAGE_SIZE);
2389 
2390 	for (i = 0; i < npages; ++i) {
2391 		if (!pagemap_addr[i].addr)
2392 			break;
2393 
2394 		dma_unmap_page(xe->drm.dev, pagemap_addr[i].addr, PAGE_SIZE,
2395 			       write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
2396 	}
2397 	kfree(pagemap_addr);
2398 }
2399 
2400 static struct drm_pagemap_addr *xe_migrate_dma_map(struct xe_device *xe,
2401 						   void *buf, int len,
2402 						   int write)
2403 {
2404 	struct drm_pagemap_addr *pagemap_addr;
2405 	unsigned long i, npages = DIV_ROUND_UP(len, PAGE_SIZE);
2406 
2407 	pagemap_addr = kzalloc_objs(*pagemap_addr, npages);
2408 	if (!pagemap_addr)
2409 		return ERR_PTR(-ENOMEM);
2410 
2411 	for (i = 0; i < npages; ++i) {
2412 		dma_addr_t addr;
2413 		struct page *page;
2414 		enum dma_data_direction dir = write ? DMA_TO_DEVICE :
2415 						      DMA_FROM_DEVICE;
2416 
2417 		if (is_vmalloc_addr(buf))
2418 			page = vmalloc_to_page(buf);
2419 		else
2420 			page = virt_to_page(buf);
2421 
2422 		addr = dma_map_page(xe->drm.dev, page, 0, PAGE_SIZE, dir);
2423 		if (dma_mapping_error(xe->drm.dev, addr))
2424 			goto err_fault;
2425 
2426 		pagemap_addr[i] =
2427 			drm_pagemap_addr_encode(addr,
2428 						DRM_INTERCONNECT_SYSTEM,
2429 						0, dir);
2430 		buf += PAGE_SIZE;
2431 	}
2432 
2433 	return pagemap_addr;
2434 
2435 err_fault:
2436 	xe_migrate_dma_unmap(xe, pagemap_addr, len, write);
2437 	return ERR_PTR(-EFAULT);
2438 }
2439 
2440 /**
2441  * xe_migrate_access_memory - Access memory of a BO via GPU
2442  *
2443  * @m: The migration context.
2444  * @bo: buffer object
2445  * @offset: access offset into buffer object
2446  * @buf: pointer to caller memory to read into or write from
2447  * @len: length of access
2448  * @write: write access
2449  *
2450  * Access memory of a BO via GPU either reading in or writing from a passed in
2451  * pointer. Pointer is dma mapped for GPU access and GPU commands are issued to
2452  * read to or write from pointer.
2453  *
2454  * Returns:
2455  * 0 if successful, negative error code on failure.
2456  */
2457 int xe_migrate_access_memory(struct xe_migrate *m, struct xe_bo *bo,
2458 			     unsigned long offset, void *buf, int len,
2459 			     int write)
2460 {
2461 	struct xe_tile *tile = m->tile;
2462 	struct xe_device *xe = tile_to_xe(tile);
2463 	struct xe_res_cursor cursor;
2464 	struct dma_fence *fence = NULL;
2465 	struct drm_pagemap_addr *pagemap_addr;
2466 	unsigned long page_offset = (unsigned long)buf & ~PAGE_MASK;
2467 	int bytes_left = len, current_page = 0;
2468 	void *orig_buf = buf;
2469 
2470 	xe_bo_assert_held(bo);
2471 
2472 	/* Use bounce buffer for small access and unaligned access */
2473 	if (!xe->info.has_mem_copy_instr &&
2474 	    (!IS_ALIGNED(len, 4) ||
2475 	     !IS_ALIGNED(page_offset, XE_CACHELINE_BYTES) ||
2476 	     !IS_ALIGNED(offset, XE_CACHELINE_BYTES))) {
2477 		int buf_offset = 0;
2478 		void *bounce;
2479 		int err;
2480 
2481 		BUILD_BUG_ON(!is_power_of_2(XE_CACHELINE_BYTES));
2482 		bounce = kmalloc(XE_CACHELINE_BYTES, GFP_KERNEL);
2483 		if (!bounce)
2484 			return -ENOMEM;
2485 
2486 		/*
2487 		 * Less than ideal for large unaligned access but this should be
2488 		 * fairly rare, can fixup if this becomes common.
2489 		 */
2490 		do {
2491 			int copy_bytes = min_t(int, bytes_left,
2492 					       XE_CACHELINE_BYTES -
2493 					       (offset & XE_CACHELINE_MASK));
2494 			int ptr_offset = offset & XE_CACHELINE_MASK;
2495 
2496 			err = xe_migrate_access_memory(m, bo,
2497 						       offset &
2498 						       ~XE_CACHELINE_MASK,
2499 						       bounce,
2500 						       XE_CACHELINE_BYTES, 0);
2501 			if (err)
2502 				break;
2503 
2504 			if (write) {
2505 				memcpy(bounce + ptr_offset, buf + buf_offset, copy_bytes);
2506 
2507 				err = xe_migrate_access_memory(m, bo,
2508 							       offset & ~XE_CACHELINE_MASK,
2509 							       bounce,
2510 							       XE_CACHELINE_BYTES, write);
2511 				if (err)
2512 					break;
2513 			} else {
2514 				memcpy(buf + buf_offset, bounce + ptr_offset,
2515 				       copy_bytes);
2516 			}
2517 
2518 			bytes_left -= copy_bytes;
2519 			buf_offset += copy_bytes;
2520 			offset += copy_bytes;
2521 		} while (bytes_left);
2522 
2523 		kfree(bounce);
2524 		return err;
2525 	}
2526 
2527 	pagemap_addr = xe_migrate_dma_map(xe, buf, len + page_offset, write);
2528 	if (IS_ERR(pagemap_addr))
2529 		return PTR_ERR(pagemap_addr);
2530 
2531 	xe_res_first(bo->ttm.resource, offset, xe_bo_size(bo) - offset, &cursor);
2532 
2533 	do {
2534 		struct dma_fence *__fence;
2535 		u64 vram_addr = vram_region_gpu_offset(bo->ttm.resource) +
2536 			cursor.start;
2537 		int current_bytes;
2538 		u32 pitch;
2539 
2540 		if (cursor.size > MAX_PREEMPTDISABLE_TRANSFER)
2541 			current_bytes = min_t(int, bytes_left,
2542 					      MAX_PREEMPTDISABLE_TRANSFER);
2543 		else
2544 			current_bytes = min_t(int, bytes_left, cursor.size);
2545 
2546 		pitch = xe_migrate_copy_pitch(xe, current_bytes);
2547 		if (xe->info.has_mem_copy_instr)
2548 			current_bytes = min_t(int, current_bytes, U16_MAX * pitch);
2549 		else
2550 			current_bytes = min_t(int, current_bytes,
2551 					      round_down(S16_MAX * pitch,
2552 							 XE_CACHELINE_BYTES));
2553 
2554 		__fence = xe_migrate_vram(m, current_bytes,
2555 					  (unsigned long)buf & ~PAGE_MASK,
2556 					  &pagemap_addr[current_page],
2557 					  vram_addr, NULL, write ?
2558 					  XE_MIGRATE_COPY_TO_VRAM :
2559 					  XE_MIGRATE_COPY_TO_SRAM);
2560 		if (IS_ERR(__fence)) {
2561 			if (fence) {
2562 				dma_fence_wait(fence, false);
2563 				dma_fence_put(fence);
2564 			}
2565 			fence = __fence;
2566 			goto out_err;
2567 		}
2568 
2569 		dma_fence_put(fence);
2570 		fence = __fence;
2571 
2572 		buf += current_bytes;
2573 		offset += current_bytes;
2574 		current_page = (int)(buf - orig_buf) / PAGE_SIZE;
2575 		bytes_left -= current_bytes;
2576 		if (bytes_left)
2577 			xe_res_next(&cursor, current_bytes);
2578 	} while (bytes_left);
2579 
2580 	dma_fence_wait(fence, false);
2581 	dma_fence_put(fence);
2582 
2583 out_err:
2584 	xe_migrate_dma_unmap(xe, pagemap_addr, len + page_offset, write);
2585 	return IS_ERR(fence) ? PTR_ERR(fence) : 0;
2586 }
2587 
2588 /**
2589  * xe_migrate_job_lock() - Lock migrate job lock
2590  * @m: The migration context.
2591  * @q: Queue associated with the operation which requires a lock
2592  *
2593  * Lock the migrate job lock if the queue is a migration queue, otherwise
2594  * assert the VM's dma-resv is held (user queue's have own locking).
2595  */
2596 void xe_migrate_job_lock(struct xe_migrate *m, struct xe_exec_queue *q)
2597 {
2598 	bool is_migrate = q == m->q;
2599 
2600 	if (is_migrate)
2601 		mutex_lock(&m->job_mutex);
2602 	else
2603 		xe_vm_assert_held(q->user_vm);	/* User queues VM's should be locked */
2604 }
2605 
2606 /**
2607  * xe_migrate_job_unlock() - Unlock migrate job lock
2608  * @m: The migration context.
2609  * @q: Queue associated with the operation which requires a lock
2610  *
2611  * Unlock the migrate job lock if the queue is a migration queue, otherwise
2612  * assert the VM's dma-resv is held (user queue's have own locking).
2613  */
2614 void xe_migrate_job_unlock(struct xe_migrate *m, struct xe_exec_queue *q)
2615 {
2616 	bool is_migrate = q == m->q;
2617 
2618 	if (is_migrate)
2619 		mutex_unlock(&m->job_mutex);
2620 	else
2621 		xe_vm_assert_held(q->user_vm);	/* User queues VM's should be locked */
2622 }
2623 
2624 #if IS_ENABLED(CONFIG_PROVE_LOCKING)
2625 /**
2626  * xe_migrate_job_lock_assert() - Assert migrate job lock held of queue
2627  * @q: Migrate queue
2628  */
2629 void xe_migrate_job_lock_assert(struct xe_exec_queue *q)
2630 {
2631 	struct xe_migrate *m = gt_to_tile(q->gt)->migrate;
2632 
2633 	xe_gt_assert(q->gt, q == m->q);
2634 	lockdep_assert_held(&m->job_mutex);
2635 }
2636 #endif
2637 
2638 #if IS_ENABLED(CONFIG_DRM_XE_KUNIT_TEST)
2639 #include "tests/xe_migrate.c"
2640 #endif
2641