1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2020 Intel Corporation
4  */
5 
6 #include "i915_drv.h"
7 #include "intel_context.h"
8 #include "intel_gpu_commands.h"
9 #include "intel_gt.h"
10 #include "intel_gtt.h"
11 #include "intel_migrate.h"
12 #include "intel_ring.h"
13 #include "gem/i915_gem_lmem.h"
14 
15 struct insert_pte_data {
16 	u64 offset;
17 };
18 
19 #define CHUNK_SZ SZ_8M /* ~1ms at 8GiB/s preemption delay */
20 
21 #define GET_CCS_BYTES(i915, size)	(HAS_FLAT_CCS(i915) ? \
22 					 DIV_ROUND_UP(size, NUM_BYTES_PER_CCS_BYTE) : 0)
23 static bool engine_supports_migration(struct intel_engine_cs *engine)
24 {
25 	if (!engine)
26 		return false;
27 
28 	/*
29 	 * We need the ability to prevent aribtration (MI_ARB_ON_OFF),
30 	 * the ability to write PTE using inline data (MI_STORE_DATA)
31 	 * and of course the ability to do the block transfer (blits).
32 	 */
33 	GEM_BUG_ON(engine->class != COPY_ENGINE_CLASS);
34 
35 	return true;
36 }
37 
38 static void xehpsdv_toggle_pdes(struct i915_address_space *vm,
39 				struct i915_page_table *pt,
40 				void *data)
41 {
42 	struct insert_pte_data *d = data;
43 
44 	/*
45 	 * Insert a dummy PTE into every PT that will map to LMEM to ensure
46 	 * we have a correctly setup PDE structure for later use.
47 	 */
48 	vm->insert_page(vm, 0, d->offset, I915_CACHE_NONE, PTE_LM);
49 	GEM_BUG_ON(!pt->is_compact);
50 	d->offset += SZ_2M;
51 }
52 
53 static void xehpsdv_insert_pte(struct i915_address_space *vm,
54 			       struct i915_page_table *pt,
55 			       void *data)
56 {
57 	struct insert_pte_data *d = data;
58 
59 	/*
60 	 * We are playing tricks here, since the actual pt, from the hw
61 	 * pov, is only 256bytes with 32 entries, or 4096bytes with 512
62 	 * entries, but we are still guaranteed that the physical
63 	 * alignment is 64K underneath for the pt, and we are careful
64 	 * not to access the space in the void.
65 	 */
66 	vm->insert_page(vm, px_dma(pt), d->offset, I915_CACHE_NONE, PTE_LM);
67 	d->offset += SZ_64K;
68 }
69 
70 static void insert_pte(struct i915_address_space *vm,
71 		       struct i915_page_table *pt,
72 		       void *data)
73 {
74 	struct insert_pte_data *d = data;
75 
76 	vm->insert_page(vm, px_dma(pt), d->offset, I915_CACHE_NONE,
77 			i915_gem_object_is_lmem(pt->base) ? PTE_LM : 0);
78 	d->offset += PAGE_SIZE;
79 }
80 
81 static struct i915_address_space *migrate_vm(struct intel_gt *gt)
82 {
83 	struct i915_vm_pt_stash stash = {};
84 	struct i915_ppgtt *vm;
85 	int err;
86 	int i;
87 
88 	/*
89 	 * We construct a very special VM for use by all migration contexts,
90 	 * it is kept pinned so that it can be used at any time. As we need
91 	 * to pre-allocate the page directories for the migration VM, this
92 	 * limits us to only using a small number of prepared vma.
93 	 *
94 	 * To be able to pipeline and reschedule migration operations while
95 	 * avoiding unnecessary contention on the vm itself, the PTE updates
96 	 * are inline with the blits. All the blits use the same fixed
97 	 * addresses, with the backing store redirection being updated on the
98 	 * fly. Only 2 implicit vma are used for all migration operations.
99 	 *
100 	 * We lay the ppGTT out as:
101 	 *
102 	 *	[0, CHUNK_SZ) -> first object
103 	 *	[CHUNK_SZ, 2 * CHUNK_SZ) -> second object
104 	 *	[2 * CHUNK_SZ, 2 * CHUNK_SZ + 2 * CHUNK_SZ >> 9] -> PTE
105 	 *
106 	 * By exposing the dma addresses of the page directories themselves
107 	 * within the ppGTT, we are then able to rewrite the PTE prior to use.
108 	 * But the PTE update and subsequent migration operation must be atomic,
109 	 * i.e. within the same non-preemptible window so that we do not switch
110 	 * to another migration context that overwrites the PTE.
111 	 *
112 	 * This changes quite a bit on platforms with HAS_64K_PAGES support,
113 	 * where we instead have three windows, each CHUNK_SIZE in size. The
114 	 * first is reserved for mapping system-memory, and that just uses the
115 	 * 512 entry layout using 4K GTT pages. The other two windows just map
116 	 * lmem pages and must use the new compact 32 entry layout using 64K GTT
117 	 * pages, which ensures we can address any lmem object that the user
118 	 * throws at us. We then also use the xehpsdv_toggle_pdes as a way of
119 	 * just toggling the PDE bit(GEN12_PDE_64K) for us, to enable the
120 	 * compact layout for each of these page-tables, that fall within the
121 	 * [CHUNK_SIZE, 3 * CHUNK_SIZE) range.
122 	 *
123 	 * We lay the ppGTT out as:
124 	 *
125 	 * [0, CHUNK_SZ) -> first window/object, maps smem
126 	 * [CHUNK_SZ, 2 * CHUNK_SZ) -> second window/object, maps lmem src
127 	 * [2 * CHUNK_SZ, 3 * CHUNK_SZ) -> third window/object, maps lmem dst
128 	 *
129 	 * For the PTE window it's also quite different, since each PTE must
130 	 * point to some 64K page, one for each PT(since it's in lmem), and yet
131 	 * each is only <= 4096bytes, but since the unused space within that PTE
132 	 * range is never touched, this should be fine.
133 	 *
134 	 * So basically each PT now needs 64K of virtual memory, instead of 4K,
135 	 * which looks like:
136 	 *
137 	 * [3 * CHUNK_SZ, 3 * CHUNK_SZ + ((3 * CHUNK_SZ / SZ_2M) * SZ_64K)] -> PTE
138 	 */
139 
140 	vm = i915_ppgtt_create(gt, I915_BO_ALLOC_PM_EARLY);
141 	if (IS_ERR(vm))
142 		return ERR_CAST(vm);
143 
144 	if (!vm->vm.allocate_va_range || !vm->vm.foreach) {
145 		err = -ENODEV;
146 		goto err_vm;
147 	}
148 
149 	if (HAS_64K_PAGES(gt->i915))
150 		stash.pt_sz = I915_GTT_PAGE_SIZE_64K;
151 
152 	/*
153 	 * Each engine instance is assigned its own chunk in the VM, so
154 	 * that we can run multiple instances concurrently
155 	 */
156 	for (i = 0; i < ARRAY_SIZE(gt->engine_class[COPY_ENGINE_CLASS]); i++) {
157 		struct intel_engine_cs *engine;
158 		u64 base = (u64)i << 32;
159 		struct insert_pte_data d = {};
160 		struct i915_gem_ww_ctx ww;
161 		u64 sz;
162 
163 		engine = gt->engine_class[COPY_ENGINE_CLASS][i];
164 		if (!engine_supports_migration(engine))
165 			continue;
166 
167 		/*
168 		 * We copy in 8MiB chunks. Each PDE covers 2MiB, so we need
169 		 * 4x2 page directories for source/destination.
170 		 */
171 		if (HAS_64K_PAGES(gt->i915))
172 			sz = 3 * CHUNK_SZ;
173 		else
174 			sz = 2 * CHUNK_SZ;
175 		d.offset = base + sz;
176 
177 		/*
178 		 * We need another page directory setup so that we can write
179 		 * the 8x512 PTE in each chunk.
180 		 */
181 		if (HAS_64K_PAGES(gt->i915))
182 			sz += (sz / SZ_2M) * SZ_64K;
183 		else
184 			sz += (sz >> 12) * sizeof(u64);
185 
186 		err = i915_vm_alloc_pt_stash(&vm->vm, &stash, sz);
187 		if (err)
188 			goto err_vm;
189 
190 		for_i915_gem_ww(&ww, err, true) {
191 			err = i915_vm_lock_objects(&vm->vm, &ww);
192 			if (err)
193 				continue;
194 			err = i915_vm_map_pt_stash(&vm->vm, &stash);
195 			if (err)
196 				continue;
197 
198 			vm->vm.allocate_va_range(&vm->vm, &stash, base, sz);
199 		}
200 		i915_vm_free_pt_stash(&vm->vm, &stash);
201 		if (err)
202 			goto err_vm;
203 
204 		/* Now allow the GPU to rewrite the PTE via its own ppGTT */
205 		if (HAS_64K_PAGES(gt->i915)) {
206 			vm->vm.foreach(&vm->vm, base, d.offset - base,
207 				       xehpsdv_insert_pte, &d);
208 			d.offset = base + CHUNK_SZ;
209 			vm->vm.foreach(&vm->vm,
210 				       d.offset,
211 				       2 * CHUNK_SZ,
212 				       xehpsdv_toggle_pdes, &d);
213 		} else {
214 			vm->vm.foreach(&vm->vm, base, d.offset - base,
215 				       insert_pte, &d);
216 		}
217 	}
218 
219 	return &vm->vm;
220 
221 err_vm:
222 	i915_vm_put(&vm->vm);
223 	return ERR_PTR(err);
224 }
225 
226 static struct intel_engine_cs *first_copy_engine(struct intel_gt *gt)
227 {
228 	struct intel_engine_cs *engine;
229 	int i;
230 
231 	for (i = 0; i < ARRAY_SIZE(gt->engine_class[COPY_ENGINE_CLASS]); i++) {
232 		engine = gt->engine_class[COPY_ENGINE_CLASS][i];
233 		if (engine_supports_migration(engine))
234 			return engine;
235 	}
236 
237 	return NULL;
238 }
239 
240 static struct intel_context *pinned_context(struct intel_gt *gt)
241 {
242 	static struct lock_class_key key;
243 	struct intel_engine_cs *engine;
244 	struct i915_address_space *vm;
245 	struct intel_context *ce;
246 
247 	engine = first_copy_engine(gt);
248 	if (!engine)
249 		return ERR_PTR(-ENODEV);
250 
251 	vm = migrate_vm(gt);
252 	if (IS_ERR(vm))
253 		return ERR_CAST(vm);
254 
255 	ce = intel_engine_create_pinned_context(engine, vm, SZ_512K,
256 						I915_GEM_HWS_MIGRATE,
257 						&key, "migrate");
258 	i915_vm_put(vm);
259 	return ce;
260 }
261 
262 int intel_migrate_init(struct intel_migrate *m, struct intel_gt *gt)
263 {
264 	struct intel_context *ce;
265 
266 	memset(m, 0, sizeof(*m));
267 
268 	ce = pinned_context(gt);
269 	if (IS_ERR(ce))
270 		return PTR_ERR(ce);
271 
272 	m->context = ce;
273 	return 0;
274 }
275 
276 static int random_index(unsigned int max)
277 {
278 	return upper_32_bits(mul_u32_u32(get_random_u32(), max));
279 }
280 
281 static struct intel_context *__migrate_engines(struct intel_gt *gt)
282 {
283 	struct intel_engine_cs *engines[MAX_ENGINE_INSTANCE];
284 	struct intel_engine_cs *engine;
285 	unsigned int count, i;
286 
287 	count = 0;
288 	for (i = 0; i < ARRAY_SIZE(gt->engine_class[COPY_ENGINE_CLASS]); i++) {
289 		engine = gt->engine_class[COPY_ENGINE_CLASS][i];
290 		if (engine_supports_migration(engine))
291 			engines[count++] = engine;
292 	}
293 
294 	return intel_context_create(engines[random_index(count)]);
295 }
296 
297 struct intel_context *intel_migrate_create_context(struct intel_migrate *m)
298 {
299 	struct intel_context *ce;
300 
301 	/*
302 	 * We randomly distribute contexts across the engines upon constrction,
303 	 * as they all share the same pinned vm, and so in order to allow
304 	 * multiple blits to run in parallel, we must construct each blit
305 	 * to use a different range of the vm for its GTT. This has to be
306 	 * known at construction, so we can not use the late greedy load
307 	 * balancing of the virtual-engine.
308 	 */
309 	ce = __migrate_engines(m->context->engine->gt);
310 	if (IS_ERR(ce))
311 		return ce;
312 
313 	ce->ring = NULL;
314 	ce->ring_size = SZ_256K;
315 
316 	i915_vm_put(ce->vm);
317 	ce->vm = i915_vm_get(m->context->vm);
318 
319 	return ce;
320 }
321 
322 static inline struct sgt_dma sg_sgt(struct scatterlist *sg)
323 {
324 	dma_addr_t addr = sg_dma_address(sg);
325 
326 	return (struct sgt_dma){ sg, addr, addr + sg_dma_len(sg) };
327 }
328 
329 static int emit_no_arbitration(struct i915_request *rq)
330 {
331 	u32 *cs;
332 
333 	cs = intel_ring_begin(rq, 2);
334 	if (IS_ERR(cs))
335 		return PTR_ERR(cs);
336 
337 	/* Explicitly disable preemption for this request. */
338 	*cs++ = MI_ARB_ON_OFF;
339 	*cs++ = MI_NOOP;
340 	intel_ring_advance(rq, cs);
341 
342 	return 0;
343 }
344 
345 static int emit_pte(struct i915_request *rq,
346 		    struct sgt_dma *it,
347 		    enum i915_cache_level cache_level,
348 		    bool is_lmem,
349 		    u64 offset,
350 		    int length)
351 {
352 	bool has_64K_pages = HAS_64K_PAGES(rq->engine->i915);
353 	const u64 encode = rq->context->vm->pte_encode(0, cache_level,
354 						       is_lmem ? PTE_LM : 0);
355 	struct intel_ring *ring = rq->ring;
356 	int pkt, dword_length;
357 	u32 total = 0;
358 	u32 page_size;
359 	u32 *hdr, *cs;
360 
361 	GEM_BUG_ON(GRAPHICS_VER(rq->engine->i915) < 8);
362 
363 	page_size = I915_GTT_PAGE_SIZE;
364 	dword_length = 0x400;
365 
366 	/* Compute the page directory offset for the target address range */
367 	if (has_64K_pages) {
368 		GEM_BUG_ON(!IS_ALIGNED(offset, SZ_2M));
369 
370 		offset /= SZ_2M;
371 		offset *= SZ_64K;
372 		offset += 3 * CHUNK_SZ;
373 
374 		if (is_lmem) {
375 			page_size = I915_GTT_PAGE_SIZE_64K;
376 			dword_length = 0x40;
377 		}
378 	} else {
379 		offset >>= 12;
380 		offset *= sizeof(u64);
381 		offset += 2 * CHUNK_SZ;
382 	}
383 
384 	offset += (u64)rq->engine->instance << 32;
385 
386 	cs = intel_ring_begin(rq, 6);
387 	if (IS_ERR(cs))
388 		return PTR_ERR(cs);
389 
390 	/* Pack as many PTE updates as possible into a single MI command */
391 	pkt = min_t(int, dword_length, ring->space / sizeof(u32) + 5);
392 	pkt = min_t(int, pkt, (ring->size - ring->emit) / sizeof(u32) + 5);
393 
394 	hdr = cs;
395 	*cs++ = MI_STORE_DATA_IMM | REG_BIT(21); /* as qword elements */
396 	*cs++ = lower_32_bits(offset);
397 	*cs++ = upper_32_bits(offset);
398 
399 	do {
400 		if (cs - hdr >= pkt) {
401 			int dword_rem;
402 
403 			*hdr += cs - hdr - 2;
404 			*cs++ = MI_NOOP;
405 
406 			ring->emit = (void *)cs - ring->vaddr;
407 			intel_ring_advance(rq, cs);
408 			intel_ring_update_space(ring);
409 
410 			cs = intel_ring_begin(rq, 6);
411 			if (IS_ERR(cs))
412 				return PTR_ERR(cs);
413 
414 			dword_rem = dword_length;
415 			if (has_64K_pages) {
416 				if (IS_ALIGNED(total, SZ_2M)) {
417 					offset = round_up(offset, SZ_64K);
418 				} else {
419 					dword_rem = SZ_2M - (total & (SZ_2M - 1));
420 					dword_rem /= page_size;
421 					dword_rem *= 2;
422 				}
423 			}
424 
425 			pkt = min_t(int, dword_rem, ring->space / sizeof(u32) + 5);
426 			pkt = min_t(int, pkt, (ring->size - ring->emit) / sizeof(u32) + 5);
427 
428 			hdr = cs;
429 			*cs++ = MI_STORE_DATA_IMM | REG_BIT(21);
430 			*cs++ = lower_32_bits(offset);
431 			*cs++ = upper_32_bits(offset);
432 		}
433 
434 		GEM_BUG_ON(!IS_ALIGNED(it->dma, page_size));
435 
436 		*cs++ = lower_32_bits(encode | it->dma);
437 		*cs++ = upper_32_bits(encode | it->dma);
438 
439 		offset += 8;
440 		total += page_size;
441 
442 		it->dma += page_size;
443 		if (it->dma >= it->max) {
444 			it->sg = __sg_next(it->sg);
445 			if (!it->sg || sg_dma_len(it->sg) == 0)
446 				break;
447 
448 			it->dma = sg_dma_address(it->sg);
449 			it->max = it->dma + sg_dma_len(it->sg);
450 		}
451 	} while (total < length);
452 
453 	*hdr += cs - hdr - 2;
454 	*cs++ = MI_NOOP;
455 
456 	ring->emit = (void *)cs - ring->vaddr;
457 	intel_ring_advance(rq, cs);
458 	intel_ring_update_space(ring);
459 
460 	return total;
461 }
462 
463 static bool wa_1209644611_applies(int ver, u32 size)
464 {
465 	u32 height = size >> PAGE_SHIFT;
466 
467 	if (ver != 11)
468 		return false;
469 
470 	return height % 4 == 3 && height <= 8;
471 }
472 
473 /**
474  * DOC: Flat-CCS - Memory compression for Local memory
475  *
476  * On Xe-HP and later devices, we use dedicated compression control state (CCS)
477  * stored in local memory for each surface, to support the 3D and media
478  * compression formats.
479  *
480  * The memory required for the CCS of the entire local memory is 1/256 of the
481  * local memory size. So before the kernel boot, the required memory is reserved
482  * for the CCS data and a secure register will be programmed with the CCS base
483  * address.
484  *
485  * Flat CCS data needs to be cleared when a lmem object is allocated.
486  * And CCS data can be copied in and out of CCS region through
487  * XY_CTRL_SURF_COPY_BLT. CPU can't access the CCS data directly.
488  *
489  * I915 supports Flat-CCS on lmem only objects. When an objects has smem in
490  * its preference list, on memory pressure, i915 needs to migrate the lmem
491  * content into smem. If the lmem object is Flat-CCS compressed by userspace,
492  * then i915 needs to decompress it. But I915 lack the required information
493  * for such decompression. Hence I915 supports Flat-CCS only on lmem only objects.
494  *
495  * When we exhaust the lmem, Flat-CCS capable objects' lmem backing memory can
496  * be temporarily evicted to smem, along with the auxiliary CCS state, where
497  * it can be potentially swapped-out at a later point, if required.
498  * If userspace later touches the evicted pages, then we always move
499  * the backing memory back to lmem, which includes restoring the saved CCS state,
500  * and potentially performing any required swap-in.
501  *
502  * For the migration of the lmem objects with smem in placement list, such as
503  * {lmem, smem}, objects are treated as non Flat-CCS capable objects.
504  */
505 
506 static inline u32 *i915_flush_dw(u32 *cmd, u32 flags)
507 {
508 	*cmd++ = MI_FLUSH_DW | flags;
509 	*cmd++ = 0;
510 	*cmd++ = 0;
511 
512 	return cmd;
513 }
514 
515 static int emit_copy_ccs(struct i915_request *rq,
516 			 u32 dst_offset, u8 dst_access,
517 			 u32 src_offset, u8 src_access, int size)
518 {
519 	struct drm_i915_private *i915 = rq->engine->i915;
520 	int mocs = rq->engine->gt->mocs.uc_index << 1;
521 	u32 num_ccs_blks;
522 	u32 *cs;
523 
524 	cs = intel_ring_begin(rq, 12);
525 	if (IS_ERR(cs))
526 		return PTR_ERR(cs);
527 
528 	num_ccs_blks = DIV_ROUND_UP(GET_CCS_BYTES(i915, size),
529 				    NUM_CCS_BYTES_PER_BLOCK);
530 	GEM_BUG_ON(num_ccs_blks > NUM_CCS_BLKS_PER_XFER);
531 	cs = i915_flush_dw(cs, MI_FLUSH_DW_LLC | MI_FLUSH_DW_CCS);
532 
533 	/*
534 	 * The XY_CTRL_SURF_COPY_BLT instruction is used to copy the CCS
535 	 * data in and out of the CCS region.
536 	 *
537 	 * We can copy at most 1024 blocks of 256 bytes using one
538 	 * XY_CTRL_SURF_COPY_BLT instruction.
539 	 *
540 	 * In case we need to copy more than 1024 blocks, we need to add
541 	 * another instruction to the same batch buffer.
542 	 *
543 	 * 1024 blocks of 256 bytes of CCS represent a total 256KB of CCS.
544 	 *
545 	 * 256 KB of CCS represents 256 * 256 KB = 64 MB of LMEM.
546 	 */
547 	*cs++ = XY_CTRL_SURF_COPY_BLT |
548 		src_access << SRC_ACCESS_TYPE_SHIFT |
549 		dst_access << DST_ACCESS_TYPE_SHIFT |
550 		((num_ccs_blks - 1) & CCS_SIZE_MASK) << CCS_SIZE_SHIFT;
551 	*cs++ = src_offset;
552 	*cs++ = rq->engine->instance |
553 		FIELD_PREP(XY_CTRL_SURF_MOCS_MASK, mocs);
554 	*cs++ = dst_offset;
555 	*cs++ = rq->engine->instance |
556 		FIELD_PREP(XY_CTRL_SURF_MOCS_MASK, mocs);
557 
558 	cs = i915_flush_dw(cs, MI_FLUSH_DW_LLC | MI_FLUSH_DW_CCS);
559 	*cs++ = MI_NOOP;
560 
561 	intel_ring_advance(rq, cs);
562 
563 	return 0;
564 }
565 
566 static int emit_copy(struct i915_request *rq,
567 		     u32 dst_offset, u32 src_offset, int size)
568 {
569 	const int ver = GRAPHICS_VER(rq->engine->i915);
570 	u32 instance = rq->engine->instance;
571 	u32 *cs;
572 
573 	cs = intel_ring_begin(rq, ver >= 8 ? 10 : 6);
574 	if (IS_ERR(cs))
575 		return PTR_ERR(cs);
576 
577 	if (ver >= 9 && !wa_1209644611_applies(ver, size)) {
578 		*cs++ = GEN9_XY_FAST_COPY_BLT_CMD | (10 - 2);
579 		*cs++ = BLT_DEPTH_32 | PAGE_SIZE;
580 		*cs++ = 0;
581 		*cs++ = size >> PAGE_SHIFT << 16 | PAGE_SIZE / 4;
582 		*cs++ = dst_offset;
583 		*cs++ = instance;
584 		*cs++ = 0;
585 		*cs++ = PAGE_SIZE;
586 		*cs++ = src_offset;
587 		*cs++ = instance;
588 	} else if (ver >= 8) {
589 		*cs++ = XY_SRC_COPY_BLT_CMD | BLT_WRITE_RGBA | (10 - 2);
590 		*cs++ = BLT_DEPTH_32 | BLT_ROP_SRC_COPY | PAGE_SIZE;
591 		*cs++ = 0;
592 		*cs++ = size >> PAGE_SHIFT << 16 | PAGE_SIZE / 4;
593 		*cs++ = dst_offset;
594 		*cs++ = instance;
595 		*cs++ = 0;
596 		*cs++ = PAGE_SIZE;
597 		*cs++ = src_offset;
598 		*cs++ = instance;
599 	} else {
600 		GEM_BUG_ON(instance);
601 		*cs++ = SRC_COPY_BLT_CMD | BLT_WRITE_RGBA | (6 - 2);
602 		*cs++ = BLT_DEPTH_32 | BLT_ROP_SRC_COPY | PAGE_SIZE;
603 		*cs++ = size >> PAGE_SHIFT << 16 | PAGE_SIZE;
604 		*cs++ = dst_offset;
605 		*cs++ = PAGE_SIZE;
606 		*cs++ = src_offset;
607 	}
608 
609 	intel_ring_advance(rq, cs);
610 	return 0;
611 }
612 
613 static u64 scatter_list_length(struct scatterlist *sg)
614 {
615 	u64 len = 0;
616 
617 	while (sg && sg_dma_len(sg)) {
618 		len += sg_dma_len(sg);
619 		sg = sg_next(sg);
620 	}
621 
622 	return len;
623 }
624 
625 static int
626 calculate_chunk_sz(struct drm_i915_private *i915, bool src_is_lmem,
627 		   u64 bytes_to_cpy, u64 ccs_bytes_to_cpy)
628 {
629 	if (ccs_bytes_to_cpy && !src_is_lmem)
630 		/*
631 		 * When CHUNK_SZ is passed all the pages upto CHUNK_SZ
632 		 * will be taken for the blt. in Flat-ccs supported
633 		 * platform Smem obj will have more pages than required
634 		 * for main meory hence limit it to the required size
635 		 * for main memory
636 		 */
637 		return min_t(u64, bytes_to_cpy, CHUNK_SZ);
638 	else
639 		return CHUNK_SZ;
640 }
641 
642 static void get_ccs_sg_sgt(struct sgt_dma *it, u64 bytes_to_cpy)
643 {
644 	u64 len;
645 
646 	do {
647 		GEM_BUG_ON(!it->sg || !sg_dma_len(it->sg));
648 		len = it->max - it->dma;
649 		if (len > bytes_to_cpy) {
650 			it->dma += bytes_to_cpy;
651 			break;
652 		}
653 
654 		bytes_to_cpy -= len;
655 
656 		it->sg = __sg_next(it->sg);
657 		it->dma = sg_dma_address(it->sg);
658 		it->max = it->dma + sg_dma_len(it->sg);
659 	} while (bytes_to_cpy);
660 }
661 
662 int
663 intel_context_migrate_copy(struct intel_context *ce,
664 			   const struct i915_deps *deps,
665 			   struct scatterlist *src,
666 			   enum i915_cache_level src_cache_level,
667 			   bool src_is_lmem,
668 			   struct scatterlist *dst,
669 			   enum i915_cache_level dst_cache_level,
670 			   bool dst_is_lmem,
671 			   struct i915_request **out)
672 {
673 	struct sgt_dma it_src = sg_sgt(src), it_dst = sg_sgt(dst), it_ccs;
674 	struct drm_i915_private *i915 = ce->engine->i915;
675 	u64 ccs_bytes_to_cpy = 0, bytes_to_cpy;
676 	enum i915_cache_level ccs_cache_level;
677 	u32 src_offset, dst_offset;
678 	u8 src_access, dst_access;
679 	struct i915_request *rq;
680 	u64 src_sz, dst_sz;
681 	bool ccs_is_src, overwrite_ccs;
682 	int err;
683 
684 	GEM_BUG_ON(ce->vm != ce->engine->gt->migrate.context->vm);
685 	GEM_BUG_ON(IS_DGFX(ce->engine->i915) && (!src_is_lmem && !dst_is_lmem));
686 	*out = NULL;
687 
688 	GEM_BUG_ON(ce->ring->size < SZ_64K);
689 
690 	src_sz = scatter_list_length(src);
691 	bytes_to_cpy = src_sz;
692 
693 	if (HAS_FLAT_CCS(i915) && src_is_lmem ^ dst_is_lmem) {
694 		src_access = !src_is_lmem && dst_is_lmem;
695 		dst_access = !src_access;
696 
697 		dst_sz = scatter_list_length(dst);
698 		if (src_is_lmem) {
699 			it_ccs = it_dst;
700 			ccs_cache_level = dst_cache_level;
701 			ccs_is_src = false;
702 		} else if (dst_is_lmem) {
703 			bytes_to_cpy = dst_sz;
704 			it_ccs = it_src;
705 			ccs_cache_level = src_cache_level;
706 			ccs_is_src = true;
707 		}
708 
709 		/*
710 		 * When there is a eviction of ccs needed smem will have the
711 		 * extra pages for the ccs data
712 		 *
713 		 * TO-DO: Want to move the size mismatch check to a WARN_ON,
714 		 * but still we have some requests of smem->lmem with same size.
715 		 * Need to fix it.
716 		 */
717 		ccs_bytes_to_cpy = src_sz != dst_sz ? GET_CCS_BYTES(i915, bytes_to_cpy) : 0;
718 		if (ccs_bytes_to_cpy)
719 			get_ccs_sg_sgt(&it_ccs, bytes_to_cpy);
720 	}
721 
722 	overwrite_ccs = HAS_FLAT_CCS(i915) && !ccs_bytes_to_cpy && dst_is_lmem;
723 
724 	src_offset = 0;
725 	dst_offset = CHUNK_SZ;
726 	if (HAS_64K_PAGES(ce->engine->i915)) {
727 		src_offset = 0;
728 		dst_offset = 0;
729 		if (src_is_lmem)
730 			src_offset = CHUNK_SZ;
731 		if (dst_is_lmem)
732 			dst_offset = 2 * CHUNK_SZ;
733 	}
734 
735 	do {
736 		int len;
737 
738 		rq = i915_request_create(ce);
739 		if (IS_ERR(rq)) {
740 			err = PTR_ERR(rq);
741 			goto out_ce;
742 		}
743 
744 		if (deps) {
745 			err = i915_request_await_deps(rq, deps);
746 			if (err)
747 				goto out_rq;
748 
749 			if (rq->engine->emit_init_breadcrumb) {
750 				err = rq->engine->emit_init_breadcrumb(rq);
751 				if (err)
752 					goto out_rq;
753 			}
754 
755 			deps = NULL;
756 		}
757 
758 		/* The PTE updates + copy must not be interrupted. */
759 		err = emit_no_arbitration(rq);
760 		if (err)
761 			goto out_rq;
762 
763 		src_sz = calculate_chunk_sz(i915, src_is_lmem,
764 					    bytes_to_cpy, ccs_bytes_to_cpy);
765 
766 		len = emit_pte(rq, &it_src, src_cache_level, src_is_lmem,
767 			       src_offset, src_sz);
768 		if (!len) {
769 			err = -EINVAL;
770 			goto out_rq;
771 		}
772 		if (len < 0) {
773 			err = len;
774 			goto out_rq;
775 		}
776 
777 		err = emit_pte(rq, &it_dst, dst_cache_level, dst_is_lmem,
778 			       dst_offset, len);
779 		if (err < 0)
780 			goto out_rq;
781 		if (err < len) {
782 			err = -EINVAL;
783 			goto out_rq;
784 		}
785 
786 		err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
787 		if (err)
788 			goto out_rq;
789 
790 		err = emit_copy(rq, dst_offset,	src_offset, len);
791 		if (err)
792 			goto out_rq;
793 
794 		bytes_to_cpy -= len;
795 
796 		if (ccs_bytes_to_cpy) {
797 			int ccs_sz;
798 
799 			err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
800 			if (err)
801 				goto out_rq;
802 
803 			ccs_sz = GET_CCS_BYTES(i915, len);
804 			err = emit_pte(rq, &it_ccs, ccs_cache_level, false,
805 				       ccs_is_src ? src_offset : dst_offset,
806 				       ccs_sz);
807 			if (err < 0)
808 				goto out_rq;
809 			if (err < ccs_sz) {
810 				err = -EINVAL;
811 				goto out_rq;
812 			}
813 
814 			err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
815 			if (err)
816 				goto out_rq;
817 
818 			err = emit_copy_ccs(rq, dst_offset, dst_access,
819 					    src_offset, src_access, len);
820 			if (err)
821 				goto out_rq;
822 
823 			err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
824 			if (err)
825 				goto out_rq;
826 			ccs_bytes_to_cpy -= ccs_sz;
827 		} else if (overwrite_ccs) {
828 			err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
829 			if (err)
830 				goto out_rq;
831 
832 			/*
833 			 * While we can't always restore/manage the CCS state,
834 			 * we still need to ensure we don't leak the CCS state
835 			 * from the previous user, so make sure we overwrite it
836 			 * with something.
837 			 */
838 			err = emit_copy_ccs(rq, dst_offset, INDIRECT_ACCESS,
839 					    dst_offset, DIRECT_ACCESS, len);
840 			if (err)
841 				goto out_rq;
842 
843 			err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
844 			if (err)
845 				goto out_rq;
846 		}
847 
848 		/* Arbitration is re-enabled between requests. */
849 out_rq:
850 		if (*out)
851 			i915_request_put(*out);
852 		*out = i915_request_get(rq);
853 		i915_request_add(rq);
854 
855 		if (err)
856 			break;
857 
858 		if (!bytes_to_cpy && !ccs_bytes_to_cpy) {
859 			if (src_is_lmem)
860 				WARN_ON(it_src.sg && sg_dma_len(it_src.sg));
861 			else
862 				WARN_ON(it_dst.sg && sg_dma_len(it_dst.sg));
863 			break;
864 		}
865 
866 		if (WARN_ON(!it_src.sg || !sg_dma_len(it_src.sg) ||
867 			    !it_dst.sg || !sg_dma_len(it_dst.sg) ||
868 			    (ccs_bytes_to_cpy && (!it_ccs.sg ||
869 						  !sg_dma_len(it_ccs.sg))))) {
870 			err = -EINVAL;
871 			break;
872 		}
873 
874 		cond_resched();
875 	} while (1);
876 
877 out_ce:
878 	return err;
879 }
880 
881 static int emit_clear(struct i915_request *rq, u32 offset, int size,
882 		      u32 value, bool is_lmem)
883 {
884 	struct drm_i915_private *i915 = rq->engine->i915;
885 	int mocs = rq->engine->gt->mocs.uc_index << 1;
886 	const int ver = GRAPHICS_VER(i915);
887 	int ring_sz;
888 	u32 *cs;
889 
890 	GEM_BUG_ON(size >> PAGE_SHIFT > S16_MAX);
891 
892 	if (HAS_FLAT_CCS(i915) && ver >= 12)
893 		ring_sz = XY_FAST_COLOR_BLT_DW;
894 	else if (ver >= 8)
895 		ring_sz = 8;
896 	else
897 		ring_sz = 6;
898 
899 	cs = intel_ring_begin(rq, ring_sz);
900 	if (IS_ERR(cs))
901 		return PTR_ERR(cs);
902 
903 	if (HAS_FLAT_CCS(i915) && ver >= 12) {
904 		*cs++ = XY_FAST_COLOR_BLT_CMD | XY_FAST_COLOR_BLT_DEPTH_32 |
905 			(XY_FAST_COLOR_BLT_DW - 2);
906 		*cs++ = FIELD_PREP(XY_FAST_COLOR_BLT_MOCS_MASK, mocs) |
907 			(PAGE_SIZE - 1);
908 		*cs++ = 0;
909 		*cs++ = size >> PAGE_SHIFT << 16 | PAGE_SIZE / 4;
910 		*cs++ = offset;
911 		*cs++ = rq->engine->instance;
912 		*cs++ = !is_lmem << XY_FAST_COLOR_BLT_MEM_TYPE_SHIFT;
913 		/* BG7 */
914 		*cs++ = value;
915 		*cs++ = 0;
916 		*cs++ = 0;
917 		*cs++ = 0;
918 		/* BG11 */
919 		*cs++ = 0;
920 		*cs++ = 0;
921 		/* BG13 */
922 		*cs++ = 0;
923 		*cs++ = 0;
924 		*cs++ = 0;
925 	} else if (ver >= 8) {
926 		*cs++ = XY_COLOR_BLT_CMD | BLT_WRITE_RGBA | (7 - 2);
927 		*cs++ = BLT_DEPTH_32 | BLT_ROP_COLOR_COPY | PAGE_SIZE;
928 		*cs++ = 0;
929 		*cs++ = size >> PAGE_SHIFT << 16 | PAGE_SIZE / 4;
930 		*cs++ = offset;
931 		*cs++ = rq->engine->instance;
932 		*cs++ = value;
933 		*cs++ = MI_NOOP;
934 	} else {
935 		*cs++ = XY_COLOR_BLT_CMD | BLT_WRITE_RGBA | (6 - 2);
936 		*cs++ = BLT_DEPTH_32 | BLT_ROP_COLOR_COPY | PAGE_SIZE;
937 		*cs++ = 0;
938 		*cs++ = size >> PAGE_SHIFT << 16 | PAGE_SIZE / 4;
939 		*cs++ = offset;
940 		*cs++ = value;
941 	}
942 
943 	intel_ring_advance(rq, cs);
944 	return 0;
945 }
946 
947 int
948 intel_context_migrate_clear(struct intel_context *ce,
949 			    const struct i915_deps *deps,
950 			    struct scatterlist *sg,
951 			    enum i915_cache_level cache_level,
952 			    bool is_lmem,
953 			    u32 value,
954 			    struct i915_request **out)
955 {
956 	struct drm_i915_private *i915 = ce->engine->i915;
957 	struct sgt_dma it = sg_sgt(sg);
958 	struct i915_request *rq;
959 	u32 offset;
960 	int err;
961 
962 	GEM_BUG_ON(ce->vm != ce->engine->gt->migrate.context->vm);
963 	*out = NULL;
964 
965 	GEM_BUG_ON(ce->ring->size < SZ_64K);
966 
967 	offset = 0;
968 	if (HAS_64K_PAGES(i915) && is_lmem)
969 		offset = CHUNK_SZ;
970 
971 	do {
972 		int len;
973 
974 		rq = i915_request_create(ce);
975 		if (IS_ERR(rq)) {
976 			err = PTR_ERR(rq);
977 			goto out_ce;
978 		}
979 
980 		if (deps) {
981 			err = i915_request_await_deps(rq, deps);
982 			if (err)
983 				goto out_rq;
984 
985 			if (rq->engine->emit_init_breadcrumb) {
986 				err = rq->engine->emit_init_breadcrumb(rq);
987 				if (err)
988 					goto out_rq;
989 			}
990 
991 			deps = NULL;
992 		}
993 
994 		/* The PTE updates + clear must not be interrupted. */
995 		err = emit_no_arbitration(rq);
996 		if (err)
997 			goto out_rq;
998 
999 		len = emit_pte(rq, &it, cache_level, is_lmem, offset, CHUNK_SZ);
1000 		if (len <= 0) {
1001 			err = len;
1002 			goto out_rq;
1003 		}
1004 
1005 		err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
1006 		if (err)
1007 			goto out_rq;
1008 
1009 		err = emit_clear(rq, offset, len, value, is_lmem);
1010 		if (err)
1011 			goto out_rq;
1012 
1013 		if (HAS_FLAT_CCS(i915) && is_lmem && !value) {
1014 			/*
1015 			 * copy the content of memory into corresponding
1016 			 * ccs surface
1017 			 */
1018 			err = emit_copy_ccs(rq, offset, INDIRECT_ACCESS, offset,
1019 					    DIRECT_ACCESS, len);
1020 			if (err)
1021 				goto out_rq;
1022 		}
1023 
1024 		err = rq->engine->emit_flush(rq, EMIT_INVALIDATE);
1025 
1026 		/* Arbitration is re-enabled between requests. */
1027 out_rq:
1028 		if (*out)
1029 			i915_request_put(*out);
1030 		*out = i915_request_get(rq);
1031 		i915_request_add(rq);
1032 		if (err || !it.sg || !sg_dma_len(it.sg))
1033 			break;
1034 
1035 		cond_resched();
1036 	} while (1);
1037 
1038 out_ce:
1039 	return err;
1040 }
1041 
1042 int intel_migrate_copy(struct intel_migrate *m,
1043 		       struct i915_gem_ww_ctx *ww,
1044 		       const struct i915_deps *deps,
1045 		       struct scatterlist *src,
1046 		       enum i915_cache_level src_cache_level,
1047 		       bool src_is_lmem,
1048 		       struct scatterlist *dst,
1049 		       enum i915_cache_level dst_cache_level,
1050 		       bool dst_is_lmem,
1051 		       struct i915_request **out)
1052 {
1053 	struct intel_context *ce;
1054 	int err;
1055 
1056 	*out = NULL;
1057 	if (!m->context)
1058 		return -ENODEV;
1059 
1060 	ce = intel_migrate_create_context(m);
1061 	if (IS_ERR(ce))
1062 		ce = intel_context_get(m->context);
1063 	GEM_BUG_ON(IS_ERR(ce));
1064 
1065 	err = intel_context_pin_ww(ce, ww);
1066 	if (err)
1067 		goto out;
1068 
1069 	err = intel_context_migrate_copy(ce, deps,
1070 					 src, src_cache_level, src_is_lmem,
1071 					 dst, dst_cache_level, dst_is_lmem,
1072 					 out);
1073 
1074 	intel_context_unpin(ce);
1075 out:
1076 	intel_context_put(ce);
1077 	return err;
1078 }
1079 
1080 int
1081 intel_migrate_clear(struct intel_migrate *m,
1082 		    struct i915_gem_ww_ctx *ww,
1083 		    const struct i915_deps *deps,
1084 		    struct scatterlist *sg,
1085 		    enum i915_cache_level cache_level,
1086 		    bool is_lmem,
1087 		    u32 value,
1088 		    struct i915_request **out)
1089 {
1090 	struct intel_context *ce;
1091 	int err;
1092 
1093 	*out = NULL;
1094 	if (!m->context)
1095 		return -ENODEV;
1096 
1097 	ce = intel_migrate_create_context(m);
1098 	if (IS_ERR(ce))
1099 		ce = intel_context_get(m->context);
1100 	GEM_BUG_ON(IS_ERR(ce));
1101 
1102 	err = intel_context_pin_ww(ce, ww);
1103 	if (err)
1104 		goto out;
1105 
1106 	err = intel_context_migrate_clear(ce, deps, sg, cache_level,
1107 					  is_lmem, value, out);
1108 
1109 	intel_context_unpin(ce);
1110 out:
1111 	intel_context_put(ce);
1112 	return err;
1113 }
1114 
1115 void intel_migrate_fini(struct intel_migrate *m)
1116 {
1117 	struct intel_context *ce;
1118 
1119 	ce = fetch_and_zero(&m->context);
1120 	if (!ce)
1121 		return;
1122 
1123 	intel_engine_destroy_pinned_context(ce);
1124 }
1125 
1126 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
1127 #include "selftest_migrate.c"
1128 #endif
1129