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