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